diff --git a/Amplify/Amplify.swift b/Amplify/Amplify.swift index fdc88954a3..b6f8bb79d7 100644 --- a/Amplify/Amplify.swift +++ b/Amplify/Amplify.swift @@ -33,37 +33,37 @@ public class Amplify { // ease of testing. /// - Tag: Amplify.Analytics - public static internal(set) var Analytics = AnalyticsCategory() + public internal(set) static var Analytics = AnalyticsCategory() /// - Tag: Amplify.API - public static internal(set) var API: APICategory = APICategory() + public internal(set) static var API = APICategory() /// - Tag: Amplify.Auth - public static internal(set) var Auth = AuthCategory() + public internal(set) static var Auth = AuthCategory() /// - Tag: Amplify.DataStore - public static internal(set) var DataStore = DataStoreCategory() + public internal(set) static var DataStore = DataStoreCategory() /// - Tag: Amplify.Geo - public static internal(set) var Geo = GeoCategory() + public internal(set) static var Geo = GeoCategory() /// - Tag: Amplify.Hub - public static internal(set) var Hub = HubCategory() + public internal(set) static var Hub = HubCategory() /// - Tag: Amplify.Notifications - public static internal(set) var Notifications = NotificationsCategory() + public internal(set) static var Notifications = NotificationsCategory() /// - Tag: Amplify.Predictions - public static internal(set) var Predictions = PredictionsCategory() + public internal(set) static var Predictions = PredictionsCategory() /// - Tag: Amplify.Storage - public static internal(set) var Storage = StorageCategory() + public internal(set) static var Storage = StorageCategory() /// Special case category. We protect this with an AtomicValue because it is used by reset() /// methods during setup & teardown of tests /// /// - Tag: Amplify.Logging - public static internal(set) var Logging: LoggingCategory { + public internal(set) static var Logging: LoggingCategory { get { loggingAtomic.get() } @@ -73,13 +73,15 @@ public class Amplify { } private static let loggingAtomic = AtomicValue(initialValue: LoggingCategory()) + // swiftlint:disable cyclomatic_complexity + /// Adds `plugin` to the category /// /// See: [Category.removePlugin(for:)](x-source-tag://Category.removePlugin) /// /// - Parameter plugin: The plugin to add /// - Tag: Amplify.add_plugin - public static func add(plugin: P) throws { + public static func add(plugin: some Plugin) throws { log.debug("Adding plugin: \(plugin))") switch plugin { case let plugin as AnalyticsCategoryPlugin: @@ -105,8 +107,11 @@ public class Amplify { default: throw PluginError.pluginConfigurationError( "Plugin category does not exist.", - "Verify that the library version is correct and supports the plugin's category.") + "Verify that the library version is correct and supports the plugin's category." + ) } + + // swiftlint:enable cyclomatic_complexity } } diff --git a/Amplify/Categories/API/APICategory.swift b/Amplify/Categories/API/APICategory.swift index 4725180daa..9478ff26d0 100644 --- a/Amplify/Categories/API/APICategory.swift +++ b/Amplify/Categories/API/APICategory.swift @@ -6,7 +6,7 @@ // /// The API category provides a solution for making HTTP requests to REST and GraphQL endpoints. -final public class APICategory: Category { +public final class APICategory: Category { /// The category type for API public var categoryType: CategoryType { .api @@ -57,8 +57,10 @@ final public class APICategory: Category { let key = plugin.key guard !key.isEmpty else { let pluginDescription = String(describing: plugin) - let error = APIError.invalidConfiguration("Plugin \(pluginDescription) has an empty `key`.", - "Set the `key` property for \(String(describing: plugin))") + let error = APIError.invalidConfiguration( + "Plugin \(pluginDescription) has an empty `key`.", + "Set the `key` property for \(String(describing: plugin))" + ) throw error } @@ -81,8 +83,10 @@ final public class APICategory: Category { public func getPlugin(for key: PluginKey) throws -> APICategoryPlugin { guard let plugin = plugins[key] else { let keys = plugins.keys.joined(separator: ", ") - let error = APIError.invalidConfiguration("No plugin has been added for '\(key)'.", - "Either add a plugin for '\(key)', or use one of the known keys: \(keys)") + let error = APIError.invalidConfiguration( + "No plugin has been added for '\(key)'.", + "Either add a plugin for '\(key)', or use one of the known keys: \(keys)" + ) throw error } return plugin diff --git a/Amplify/Categories/API/ClientBehavior/APICategory+ReachabilityBehavior.swift b/Amplify/Categories/API/ClientBehavior/APICategory+ReachabilityBehavior.swift index 1f714f94ef..050a0b7f68 100644 --- a/Amplify/Categories/API/ClientBehavior/APICategory+ReachabilityBehavior.swift +++ b/Amplify/Categories/API/ClientBehavior/APICategory+ReachabilityBehavior.swift @@ -6,8 +6,8 @@ // #if canImport(Combine) -import Foundation import Combine +import Foundation extension APICategory: APICategoryReachabilityBehavior { #if !os(watchOS) diff --git a/Amplify/Categories/API/ClientBehavior/APICategoryBehavior.swift b/Amplify/Categories/API/ClientBehavior/APICategoryBehavior.swift index 3c2356d564..d17b2f98d3 100644 --- a/Amplify/Categories/API/ClientBehavior/APICategoryBehavior.swift +++ b/Amplify/Categories/API/ClientBehavior/APICategoryBehavior.swift @@ -7,8 +7,8 @@ /// Behavior of the API category that clients will use public typealias APICategoryBehavior = - APICategoryRESTBehavior & + APICategoryAuthProviderFactoryBehavior & APICategoryGraphQLBehavior & APICategoryInterceptorBehavior & - APICategoryReachabilityBehavior & - APICategoryAuthProviderFactoryBehavior + APICategoryRESTBehavior & + APICategoryReachabilityBehavior diff --git a/Amplify/Categories/API/ClientBehavior/APICategoryGraphQLBehavior.swift b/Amplify/Categories/API/ClientBehavior/APICategoryGraphQLBehavior.swift index d149b5d945..05bda4d470 100644 --- a/Amplify/Categories/API/ClientBehavior/APICategoryGraphQLBehavior.swift +++ b/Amplify/Categories/API/ClientBehavior/APICategoryGraphQLBehavior.swift @@ -35,7 +35,7 @@ public protocol APICategoryGraphQLBehavior: AnyObject { /// - request: The GraphQL request containing apiName, document, variables, and responseType /// - valueListener: Invoked when the GraphQL subscription receives a new value from the service /// - completionListener: Invoked when the subscription has terminated - /// - Returns: The AmplifyInProcessReportingOperation being enqueued + /// - Returns: The AmplifyInProcessReportingOperation being enqueued func subscribe( request: GraphQLRequest ) -> AmplifyAsyncThrowingSequence> diff --git a/Amplify/Categories/API/ClientBehavior/APICategoryReachabilityBehavior.swift b/Amplify/Categories/API/ClientBehavior/APICategoryReachabilityBehavior.swift index d14ab48a3b..ad28239d43 100644 --- a/Amplify/Categories/API/ClientBehavior/APICategoryReachabilityBehavior.swift +++ b/Amplify/Categories/API/ClientBehavior/APICategoryReachabilityBehavior.swift @@ -6,8 +6,8 @@ // #if canImport(Combine) -import Foundation import Combine +import Foundation /// API Reachability Behavior public protocol APICategoryReachabilityBehavior { diff --git a/Amplify/Categories/API/Operation/AmplifyOperation+APIPublishers.swift b/Amplify/Categories/API/Operation/AmplifyOperation+APIPublishers.swift index 83a3d25e76..0f2132d04d 100644 --- a/Amplify/Categories/API/Operation/AmplifyOperation+APIPublishers.swift +++ b/Amplify/Categories/API/Operation/AmplifyOperation+APIPublishers.swift @@ -6,8 +6,8 @@ // #if canImport(Combine) -import Foundation import Combine +import Foundation // MARK: - GraphQLSubscriptionOperation diff --git a/Amplify/Categories/API/Operation/NondeterminsticOperation.swift b/Amplify/Categories/API/Operation/NondeterminsticOperation.swift index cd17b65fe5..292cb7d1f3 100644 --- a/Amplify/Categories/API/Operation/NondeterminsticOperation.swift +++ b/Amplify/Categories/API/Operation/NondeterminsticOperation.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // - import Combine + /** A non-deterministic operation offers multiple paths to accomplish its task. It attempts the next path if all preceding paths have failed with an error that allows for continuation. @@ -62,7 +62,7 @@ final class NondeterminsticOperation { self?.task = Task { [weak self] in do { if let self { - promise(.success(try await self.run())) + try await promise(.success(run())) } else { promise(.failure(NondeterminsticOperationError.cancelled)) } diff --git a/Amplify/Categories/API/Operation/RetryableGraphQLOperation.swift b/Amplify/Categories/API/Operation/RetryableGraphQLOperation.swift index d746ba4905..197427bcae 100644 --- a/Amplify/Categories/API/Operation/RetryableGraphQLOperation.swift +++ b/Amplify/Categories/API/Operation/RetryableGraphQLOperation.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation // MARK: - RetryableGraphQLOperation @@ -16,7 +16,7 @@ public final class RetryableGraphQLOperation { private let nondeterminsticOperation: NondeterminsticOperation.Success> public init( - requestStream: AsyncStream<() async throws -> GraphQLTask.Success> + requestStream: AsyncStream < () async throws -> GraphQLTask.Success> ) { self.nondeterminsticOperation = NondeterminsticOperation( operations: requestStream, @@ -80,7 +80,7 @@ public final class RetryableGraphQLSubscriptionOperation { private let nondeterminsticOperation: NondeterminsticOperation> public init( - requestStream: AsyncStream<() async throws -> AmplifyAsyncThrowingSequence> + requestStream: AsyncStream < () async throws -> AmplifyAsyncThrowingSequence < SubscriptionEvents>> ) { self.nondeterminsticOperation = NondeterminsticOperation(operations: requestStream) } @@ -91,7 +91,7 @@ public final class RetryableGraphQLSubscriptionOperation { public func subscribe() -> AnyPublisher { let subject = PassthroughSubject() - self.task = Task { await self.trySubscribe(subject) } + task = Task { await self.trySubscribe(subject) } return subject.eraseToAnyPublisher() } @@ -99,7 +99,7 @@ public final class RetryableGraphQLSubscriptionOperation { var apiError: APIError? do { try Task.checkCancellation() - let sequence = try await self.nondeterminsticOperation.run() + let sequence = try await nondeterminsticOperation.run() defer { sequence.cancel() } for try await event in sequence { try Task.checkCancellation() @@ -122,13 +122,13 @@ public final class RetryableGraphQLSubscriptionOperation { } public func cancel() { - self.task?.cancel() - self.nondeterminsticOperation.cancel() + task?.cancel() + nondeterminsticOperation.cancel() } } -extension AsyncSequence { - fileprivate var asyncStream: AsyncStream { +private extension AsyncSequence { + var asyncStream: AsyncStream { AsyncStream { continuation in Task { var it = self.makeAsyncIterator() @@ -145,11 +145,11 @@ extension AsyncSequence { } } -extension RetryableGraphQLSubscriptionOperation { - public static var log: Logger { +public extension RetryableGraphQLSubscriptionOperation { + static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.api.displayName, forNamespace: String(describing: self)) } - public var log: Logger { + var log: Logger { Self.log } } diff --git a/Amplify/Categories/API/Request/GraphQLOperationRequest.swift b/Amplify/Categories/API/Request/GraphQLOperationRequest.swift index 2f5ebf1ed2..994b30c5b6 100644 --- a/Amplify/Categories/API/Request/GraphQLOperationRequest.swift +++ b/Amplify/Categories/API/Request/GraphQLOperationRequest.swift @@ -32,14 +32,16 @@ public struct GraphQLOperationRequest: AmplifyOperationRequest { public let options: Options /// Initializer for GraphQLOperationRequest - public init(apiName: String?, - operationType: GraphQLOperationType, - document: String, - variables: [String: Any]? = nil, - responseType: R.Type, - decodePath: String? = nil, - authMode: AuthorizationMode? = nil, - options: Options) { + public init( + apiName: String?, + operationType: GraphQLOperationType, + document: String, + variables: [String: Any]? = nil, + responseType: R.Type, + decodePath: String? = nil, + authMode: AuthorizationMode? = nil, + options: Options + ) { self.apiName = apiName self.operationType = operationType self.document = document diff --git a/Amplify/Categories/API/Request/GraphQLRequest.swift b/Amplify/Categories/API/Request/GraphQLRequest.swift index ba0086de66..88915bb0ba 100644 --- a/Amplify/Categories/API/Request/GraphQLRequest.swift +++ b/Amplify/Categories/API/Request/GraphQLRequest.swift @@ -35,13 +35,15 @@ public struct GraphQLRequest { /// Options to adjust the behavior of this request, including plugin-options public var options: Options? - public init(apiName: String? = nil, - document: String, - variables: [String: Any]? = nil, - responseType: R.Type, - decodePath: String? = nil, - authMode: AuthorizationMode? = nil, - options: GraphQLRequest.Options? = nil) { + public init( + apiName: String? = nil, + document: String, + variables: [String: Any]? = nil, + responseType: R.Type, + decodePath: String? = nil, + authMode: AuthorizationMode? = nil, + options: GraphQLRequest.Options? = nil + ) { self.apiName = apiName self.document = document self.variables = variables diff --git a/Amplify/Categories/API/Request/RESTOperationRequest.swift b/Amplify/Categories/API/Request/RESTOperationRequest.swift index b1e5deaf8e..a9af7576b6 100644 --- a/Amplify/Categories/API/Request/RESTOperationRequest.swift +++ b/Amplify/Categories/API/Request/RESTOperationRequest.swift @@ -32,13 +32,15 @@ public struct RESTOperationRequest: AmplifyOperationRequest { public let options: Options /// Initializer with all properties - public init(apiName: String?, - operationType: RESTOperationType, - path: String? = nil, - headers: [String: String]? = nil, - queryParameters: [String: String]? = nil, - body: Data? = nil, - options: Options) { + public init( + apiName: String?, + operationType: RESTOperationType, + path: String? = nil, + headers: [String: String]? = nil, + queryParameters: [String: String]? = nil, + body: Data? = nil, + options: Options + ) { self.apiName = apiName self.operationType = operationType self.path = path diff --git a/Amplify/Categories/API/Request/RESTRequest.swift b/Amplify/Categories/API/Request/RESTRequest.swift index 5af207568e..a576983ee3 100644 --- a/Amplify/Categories/API/Request/RESTRequest.swift +++ b/Amplify/Categories/API/Request/RESTRequest.swift @@ -27,11 +27,13 @@ public class RESTRequest { public let body: Data? /// Initializer with all properties - public init(apiName: String? = nil, - path: String? = nil, - headers: [String: String]? = nil, - queryParameters: [String: String]? = nil, - body: Data? = nil) { + public init( + apiName: String? = nil, + path: String? = nil, + headers: [String: String]? = nil, + queryParameters: [String: String]? = nil, + body: Data? = nil + ) { let inputHeaders = headers ?? [:] self.headers = inputHeaders.merging( ["Cache-Control": "no-store"], diff --git a/Amplify/Categories/API/Response/GraphQLError.swift b/Amplify/Categories/API/Response/GraphQLError.swift index 7d1d21f104..b970a20870 100644 --- a/Amplify/Categories/API/Response/GraphQLError.swift +++ b/Amplify/Categories/API/Response/GraphQLError.swift @@ -21,10 +21,12 @@ public struct GraphQLError: Decodable { public let extensions: [String: JSONValue]? /// Initializer with all properties - public init(message: String, - locations: [Location]? = nil, - path: [JSONValue]? = nil, - extensions: [String: JSONValue]? = nil) { + public init( + message: String, + locations: [Location]? = nil, + path: [JSONValue]? = nil, + extensions: [String: JSONValue]? = nil + ) { self.message = message self.locations = locations self.path = path @@ -32,10 +34,10 @@ public struct GraphQLError: Decodable { } } -extension GraphQLError { +public extension GraphQLError { /// Both `line` and `column` are positive numbers describing the beginning of an associated syntax element - public struct Location: Decodable { + struct Location: Decodable { /// The line describing the associated syntax element public let line: Int diff --git a/Amplify/Categories/Analytics/AnalyticsCategory+ClientBehavior.swift b/Amplify/Categories/Analytics/AnalyticsCategory+ClientBehavior.swift index e73abe1c15..0f184b96ff 100644 --- a/Amplify/Categories/Analytics/AnalyticsCategory+ClientBehavior.swift +++ b/Amplify/Categories/Analytics/AnalyticsCategory+ClientBehavior.swift @@ -40,14 +40,14 @@ extension AnalyticsCategory: AnalyticsCategoryBehavior { } /// Methods that wrap `AnalyticsCategoryBehavior` to provides additional useful calling patterns -extension AnalyticsCategory { +public extension AnalyticsCategory { /// Registered global properties can be unregistered though this method. In case no keys are provided, *all* /// registered global properties will be unregistered. Duplicate keys will be ignored. This method can be called /// from `Amplify.Analytics` and is a wrapper for `unregisterGlobalProperties(_ keys: Set? = nil)` /// /// - Parameter keys: one or more of property names to unregister - public func unregisterGlobalProperties(_ keys: String...) { + func unregisterGlobalProperties(_ keys: String...) { plugin.unregisterGlobalProperties(keys.isEmpty ? nil : Set(keys)) } @@ -56,7 +56,7 @@ extension AnalyticsCategory { /// from `Amplify.Analytics` and is a wrapper for `unregisterGlobalProperties(_ keys: Set? = nil)` /// /// - Parameter keys: an array of property names to unregister - public func unregisterGlobalProperties(_ keys: [String]) { + func unregisterGlobalProperties(_ keys: [String]) { plugin.unregisterGlobalProperties(keys.isEmpty ? nil : Set(keys)) } } diff --git a/Amplify/Categories/Analytics/AnalyticsCategory.swift b/Amplify/Categories/Analytics/AnalyticsCategory.swift index 4697d51685..79a0d53976 100644 --- a/Amplify/Categories/Analytics/AnalyticsCategory.swift +++ b/Amplify/Categories/Analytics/AnalyticsCategory.swift @@ -6,7 +6,7 @@ // /// The Analytics category enables you to collect analytics data for your app. -final public class AnalyticsCategory: Category { +public final class AnalyticsCategory: Category { /// Analytics category type public let categoryType = CategoryType.analytics @@ -56,7 +56,8 @@ final public class AnalyticsCategory: Category { let pluginDescription = String(describing: plugin) let error = AnalyticsError.configuration( "Plugin \(pluginDescription) has an empty `key`.", - "Set the `key` property for \(String(describing: plugin))") + "Set the `key` property for \(String(describing: plugin))" + ) throw error } @@ -81,7 +82,8 @@ final public class AnalyticsCategory: Category { let keys = plugins.keys.joined(separator: ", ") let error = AnalyticsError.configuration( "No plugin has been added for '\(key)'.", - "Either add a plugin for '\(key)', or use one of the known keys: \(keys)") + "Either add a plugin for '\(key)', or use one of the known keys: \(keys)" + ) throw error } return plugin diff --git a/Amplify/Categories/Analytics/AnalyticsProfile.swift b/Amplify/Categories/Analytics/AnalyticsProfile.swift index d4f1d6e3e4..1f480a5e35 100644 --- a/Amplify/Categories/Analytics/AnalyticsProfile.swift +++ b/Amplify/Categories/Analytics/AnalyticsProfile.swift @@ -32,11 +32,13 @@ public struct AnalyticsUserProfile { /// - plan: The plan for the user /// - location: Location data about the user /// - properties: Properties of the user profile - public init(name: String? = nil, - email: String? = nil, - plan: String? = nil, - location: Location? = nil, - properties: AnalyticsProperties? = nil) { + public init( + name: String? = nil, + email: String? = nil, + plan: String? = nil, + location: Location? = nil, + properties: AnalyticsProperties? = nil + ) { self.name = name self.email = email self.plan = plan @@ -45,10 +47,10 @@ public struct AnalyticsUserProfile { } } -extension AnalyticsUserProfile { +public extension AnalyticsUserProfile { /// Location specific data - public typealias Location = UserProfileLocation + typealias Location = UserProfileLocation } extension AnalyticsUserProfile: UserProfile { diff --git a/Amplify/Categories/Analytics/Event/BasicAnalyticsEvent.swift b/Amplify/Categories/Analytics/Event/BasicAnalyticsEvent.swift index 2e2792a153..ce9762ac15 100644 --- a/Amplify/Categories/Analytics/Event/BasicAnalyticsEvent.swift +++ b/Amplify/Categories/Analytics/Event/BasicAnalyticsEvent.swift @@ -20,8 +20,10 @@ public struct BasicAnalyticsEvent: AnalyticsEvent { /// - Parameters: /// - name: The name of the event /// - properties: Properties of the event - public init(name: String, - properties: AnalyticsProperties? = nil) { + public init( + name: String, + properties: AnalyticsProperties? = nil + ) { self.name = name self.properties = properties } diff --git a/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift b/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift index 5907f36810..4a5a8c3481 100644 --- a/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift @@ -17,9 +17,11 @@ extension AuthCategory: AuthCategoryBehavior { return try await plugin.signUp(username: username, password: password, options: options) } - public func confirmSignUp(for username: String, - confirmationCode: String, - options: AuthConfirmSignUpRequest.Options? = nil) async throws -> AuthSignUpResult { + public func confirmSignUp( + for username: String, + confirmationCode: String, + options: AuthConfirmSignUpRequest.Options? = nil + ) async throws -> AuthSignUpResult { return try await plugin.confirmSignUp(for: username, confirmationCode: confirmationCode, options: options) } @@ -30,26 +32,32 @@ extension AuthCategory: AuthCategoryBehavior { return try await plugin.resendSignUpCode(for: username, options: options) } - public func signIn(username: String? = nil, - password: String? = nil, - options: AuthSignInRequest.Options? = nil) async throws -> AuthSignInResult { + public func signIn( + username: String? = nil, + password: String? = nil, + options: AuthSignInRequest.Options? = nil + ) async throws -> AuthSignInResult { return try await plugin.signIn(username: username, password: password, options: options) } #if os(iOS) || os(macOS) || os(visionOS) public func signInWithWebUI( presentationAnchor: AuthUIPresentationAnchor? = nil, - options: AuthWebUISignInRequest.Options? = nil) async throws -> AuthSignInResult { + options: AuthWebUISignInRequest.Options? = nil + ) async throws -> AuthSignInResult { return try await plugin.signInWithWebUI(presentationAnchor: presentationAnchor, options: options) } public func signInWithWebUI( for authProvider: AuthProvider, presentationAnchor: AuthUIPresentationAnchor? = nil, - options: AuthWebUISignInRequest.Options? = nil) async throws -> AuthSignInResult { - return try await plugin.signInWithWebUI(for: authProvider, - presentationAnchor: presentationAnchor, - options: options) + options: AuthWebUISignInRequest.Options? = nil + ) async throws -> AuthSignInResult { + return try await plugin.signInWithWebUI( + for: authProvider, + presentationAnchor: presentationAnchor, + options: options + ) } #endif @@ -80,8 +88,8 @@ extension AuthCategory: AuthCategoryBehavior { } public func confirmResetPassword( - for username: String, with - newPassword: String, + for username: String, + with newPassword: String, confirmationCode: String, options: AuthConfirmResetPasswordRequest.Options? = nil ) async throws { diff --git a/Amplify/Categories/Auth/AuthCategory+UserBehavior.swift b/Amplify/Categories/Auth/AuthCategory+UserBehavior.swift index 6589e03083..9c4651a6b5 100644 --- a/Amplify/Categories/Auth/AuthCategory+UserBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategory+UserBehavior.swift @@ -26,8 +26,10 @@ extension AuthCategory: AuthCategoryUserBehavior { try await plugin.update(userAttribute: userAttribute, options: options) } - public func update(userAttributes: [AuthUserAttribute], - options: AuthUpdateUserAttributesRequest.Options? = nil) + public func update( + userAttributes: [AuthUserAttribute], + options: AuthUpdateUserAttributesRequest.Options? = nil + ) async throws -> [AuthUserAttributeKey: AuthUpdateAttributeResult] { try await plugin.update(userAttributes: userAttributes, options: options) } @@ -47,9 +49,11 @@ extension AuthCategory: AuthCategoryUserBehavior { try await plugin.sendVerificationCode(forUserAttributeKey: userAttributeKey, options: options) } - public func confirm(userAttribute: AuthUserAttributeKey, - confirmationCode: String, - options: AuthConfirmUserAttributeRequest.Options? = nil) async throws { + public func confirm( + userAttribute: AuthUserAttributeKey, + confirmationCode: String, + options: AuthConfirmUserAttributeRequest.Options? = nil + ) async throws { try await plugin.confirm( userAttribute: userAttribute, confirmationCode: confirmationCode, diff --git a/Amplify/Categories/Auth/AuthCategory.swift b/Amplify/Categories/Auth/AuthCategory.swift index 04fb854778..afa4b22c76 100644 --- a/Amplify/Categories/Auth/AuthCategory.swift +++ b/Amplify/Categories/Auth/AuthCategory.swift @@ -5,7 +5,7 @@ // SPDX-License-Identifier: Apache-2.0 // -final public class AuthCategory: Category { +public final class AuthCategory: Category { public let categoryType = CategoryType.auth @@ -51,8 +51,10 @@ final public class AuthCategory: Category { let key = plugin.key guard !key.isEmpty else { let pluginDescription = String(describing: plugin) - let error = AuthError.configuration("Plugin \(pluginDescription) has an empty `key`.", - "Set the `key` property for \(String(describing: plugin))") + let error = AuthError.configuration( + "Plugin \(pluginDescription) has an empty `key`.", + "Set the `key` property for \(String(describing: plugin))" + ) throw error } @@ -75,8 +77,10 @@ final public class AuthCategory: Category { public func getPlugin(for key: PluginKey) throws -> AuthCategoryPlugin { guard let plugin = plugins[key] else { let keys = plugins.keys.joined(separator: ", ") - let error = AuthError.configuration("No plugin has been added for '\(key)'.", - "Either add a plugin for '\(key)', or use one of the known keys: \(keys)") + let error = AuthError.configuration( + "No plugin has been added for '\(key)'.", + "Either add a plugin for '\(key)', or use one of the known keys: \(keys)" + ) throw error } return plugin diff --git a/Amplify/Categories/Auth/AuthCategoryBehavior.swift b/Amplify/Categories/Auth/AuthCategoryBehavior.swift index 4af66a67dd..0baf19305f 100644 --- a/Amplify/Categories/Auth/AuthCategoryBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategoryBehavior.swift @@ -8,6 +8,7 @@ import Foundation #if os(iOS) || os(macOS) || os(visionOS) import AuthenticationServices + public typealias AuthUIPresentationAnchor = ASPresentationAnchor #endif @@ -39,9 +40,11 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - username: Username used that was used to signUp. /// - confirmationCode: Confirmation code received to the user. /// - options: Parameters specific to plugin behavior - func confirmSignUp(for username: String, - confirmationCode: String, - options: AuthConfirmSignUpRequest.Options?) async throws -> AuthSignUpResult + func confirmSignUp( + for username: String, + confirmationCode: String, + options: AuthConfirmSignUpRequest.Options? + ) async throws -> AuthSignUpResult /// Resends the confirmation code to confirm the signUp process /// @@ -62,9 +65,11 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - username: Username to signIn the user /// - password: Password to signIn the user /// - options: Parameters specific to plugin behavior - func signIn(username: String?, - password: String?, - options: AuthSignInRequest.Options?) async throws -> AuthSignInResult + func signIn( + username: String?, + password: String?, + options: AuthSignInRequest.Options? + ) async throws -> AuthSignInResult #if os(iOS) || os(macOS) || os(visionOS) /// SignIn using pre configured web UI. @@ -74,8 +79,10 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - Parameters: /// - presentationAnchor: Anchor on which the UI is presented. /// - options: Parameters specific to plugin behavior. - func signInWithWebUI(presentationAnchor: AuthUIPresentationAnchor?, - options: AuthWebUISignInRequest.Options?) async throws -> AuthSignInResult + func signInWithWebUI( + presentationAnchor: AuthUIPresentationAnchor?, + options: AuthWebUISignInRequest.Options? + ) async throws -> AuthSignInResult /// SignIn using an auth provider on a web UI /// @@ -87,9 +94,11 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - authProvider: Auth provider used to signIn. /// - presentationAnchor: Anchor on which the UI is presented. /// - options: Parameters specific to plugin behavior. - func signInWithWebUI(for authProvider: AuthProvider, - presentationAnchor: AuthUIPresentationAnchor?, - options: AuthWebUISignInRequest.Options?) async throws -> AuthSignInResult + func signInWithWebUI( + for authProvider: AuthProvider, + presentationAnchor: AuthUIPresentationAnchor?, + options: AuthWebUISignInRequest.Options? + ) async throws -> AuthSignInResult #endif /// Confirms a next step in signIn flow. @@ -122,8 +131,10 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - Parameters: /// - username: username whose password need to reset /// - options: Parameters specific to plugin behavior - func resetPassword(for username: String, - options: AuthResetPasswordRequest.Options?) async throws -> AuthResetPasswordResult + func resetPassword( + for username: String, + options: AuthResetPasswordRequest.Options? + ) async throws -> AuthResetPasswordResult /// Confirms a reset password flow /// @@ -140,10 +151,10 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi ) async throws /// Initiates TOTP Setup - /// + /// /// Invoke this operation to setup TOTP for the user while signed in. - /// Calling this method will initiate TOTP setup process and - /// returns a shared secret that can be used to generate QR code. + /// Calling this method will initiate TOTP setup process and + /// returns a shared secret that can be used to generate QR code. /// The setup details also contains a URI generator helper that can be used to retireve a TOTP Setup URI. /// func setUpTOTP() async throws -> TOTPSetupDetails diff --git a/Amplify/Categories/Auth/Models/AuthCodeDeliveryDetails.swift b/Amplify/Categories/Auth/Models/AuthCodeDeliveryDetails.swift index 1f73a5ec0e..af5b81ff46 100644 --- a/Amplify/Categories/Auth/Models/AuthCodeDeliveryDetails.swift +++ b/Amplify/Categories/Auth/Models/AuthCodeDeliveryDetails.swift @@ -18,8 +18,10 @@ public struct AuthCodeDeliveryDetails { /// Attribute that is confirmed or verified. public let attributeKey: AuthUserAttributeKey? - public init(destination: DeliveryDestination, - attributeKey: AuthUserAttributeKey? = nil) { + public init( + destination: DeliveryDestination, + attributeKey: AuthUserAttributeKey? = nil + ) { self.destination = destination self.attributeKey = attributeKey } diff --git a/Amplify/Categories/Auth/Models/AuthSignUpStep.swift b/Amplify/Categories/Auth/Models/AuthSignUpStep.swift index 2d66d9cf56..15e74aa8f0 100644 --- a/Amplify/Categories/Auth/Models/AuthSignUpStep.swift +++ b/Amplify/Categories/Auth/Models/AuthSignUpStep.swift @@ -14,7 +14,8 @@ public enum AuthSignUpStep { case confirmUser( AuthCodeDeliveryDetails? = nil, AdditionalInfo? = nil, - UserId? = nil) + UserId? = nil + ) /// Sign up is complete case done diff --git a/Amplify/Categories/Auth/Models/TOTPSetupDetails.swift b/Amplify/Categories/Auth/Models/TOTPSetupDetails.swift index 608ddcab77..fe432e2e8d 100644 --- a/Amplify/Categories/Auth/Models/TOTPSetupDetails.swift +++ b/Amplify/Categories/Auth/Models/TOTPSetupDetails.swift @@ -26,15 +26,18 @@ public struct TOTPSetupDetails { /// (for example, if the parameter string contains characters that are illegal in a URL, or is an empty string). public func getSetupURI( appName: String, - accountName: String? = nil) throws -> URL { + accountName: String? = nil + ) throws -> URL { guard let URL = URL( - string: "otpauth://totp/\(appName):\(accountName ?? username)?secret=\(sharedSecret)&issuer=\(appName)") else { + string: "otpauth://totp/\(appName):\(accountName ?? username)?secret=\(sharedSecret)&issuer=\(appName)") + else { throw AuthError.validation( "appName or accountName", "Invalid Parameters. Cannot form URL from the supplied appName or accountName", "Please make sure that the supplied parameters don't contain any characters that are illegal in a URL or is an empty String", - nil) + nil + ) } return URL } diff --git a/Amplify/Categories/Auth/Request/AuthAttributeResendConfirmationCodeRequest.swift b/Amplify/Categories/Auth/Request/AuthAttributeResendConfirmationCodeRequest.swift index 4c514c97fb..790c48490c 100644 --- a/Amplify/Categories/Auth/Request/AuthAttributeResendConfirmationCodeRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthAttributeResendConfirmationCodeRequest.swift @@ -18,8 +18,10 @@ public struct AuthAttributeResendConfirmationCodeRequest: AmplifyOperationReques /// Extra request options defined in `AuthAttributeResendConfirmationCodeRequest.Options` public var options: Options - public init(attributeKey: AuthUserAttributeKey, - options: Options) { + public init( + attributeKey: AuthUserAttributeKey, + options: Options + ) { self.attributeKey = attributeKey self.options = options } diff --git a/Amplify/Categories/Auth/Request/AuthAttributeSendVerificationCodeRequest.swift b/Amplify/Categories/Auth/Request/AuthAttributeSendVerificationCodeRequest.swift index ec5f0a4683..4e48b30f7b 100644 --- a/Amplify/Categories/Auth/Request/AuthAttributeSendVerificationCodeRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthAttributeSendVerificationCodeRequest.swift @@ -18,8 +18,10 @@ public struct AuthSendUserAttributeVerificationCodeRequest: AmplifyOperationRequ /// Extra request options defined in `AuthSendUserAttributeVerificationCodeRequest.Options` public var options: Options - public init(attributeKey: AuthUserAttributeKey, - options: Options) { + public init( + attributeKey: AuthUserAttributeKey, + options: Options + ) { self.attributeKey = attributeKey self.options = options } diff --git a/Amplify/Categories/Auth/Request/AuthChangePasswordRequest.swift b/Amplify/Categories/Auth/Request/AuthChangePasswordRequest.swift index d385b95d52..fbd9bb1f93 100644 --- a/Amplify/Categories/Auth/Request/AuthChangePasswordRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthChangePasswordRequest.swift @@ -19,9 +19,11 @@ public struct AuthChangePasswordRequest: AmplifyOperationRequest { /// Extra request options defined in `AuthChangePasswordRequest.Options` public var options: Options - public init(oldPassword: String, - newPassword: String, - options: Options) { + public init( + oldPassword: String, + newPassword: String, + options: Options + ) { self.oldPassword = oldPassword self.newPassword = newPassword self.options = options diff --git a/Amplify/Categories/Auth/Request/AuthConfirmResetPasswordRequest.swift b/Amplify/Categories/Auth/Request/AuthConfirmResetPasswordRequest.swift index c4e0be2e19..d09406b999 100644 --- a/Amplify/Categories/Auth/Request/AuthConfirmResetPasswordRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthConfirmResetPasswordRequest.swift @@ -22,10 +22,12 @@ public struct AuthConfirmResetPasswordRequest: AmplifyOperationRequest { /// Extra request options defined in `AuthConfirmResetPasswordRequest.Options` public var options: Options - public init(username: String, - newPassword: String, - confirmationCode: String, - options: Options) { + public init( + username: String, + newPassword: String, + confirmationCode: String, + options: Options + ) { self.username = username self.newPassword = newPassword self.confirmationCode = confirmationCode diff --git a/Amplify/Categories/Auth/Request/AuthConfirmUserAttributeRequest.swift b/Amplify/Categories/Auth/Request/AuthConfirmUserAttributeRequest.swift index 57650da6cb..6c6e9713cf 100644 --- a/Amplify/Categories/Auth/Request/AuthConfirmUserAttributeRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthConfirmUserAttributeRequest.swift @@ -19,9 +19,11 @@ public struct AuthConfirmUserAttributeRequest: AmplifyOperationRequest { /// Extra request options defined in `AuthConfirmUserAttributeRequest.Options` public var options: Options - public init(attributeKey: AuthUserAttributeKey, - confirmationCode: String, - options: Options) { + public init( + attributeKey: AuthUserAttributeKey, + confirmationCode: String, + options: Options + ) { self.attributeKey = attributeKey self.confirmationCode = confirmationCode self.options = options diff --git a/Amplify/Categories/Auth/Request/AuthFetchSessionRequest.swift b/Amplify/Categories/Auth/Request/AuthFetchSessionRequest.swift index debdb449e4..569575f0d2 100644 --- a/Amplify/Categories/Auth/Request/AuthFetchSessionRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthFetchSessionRequest.swift @@ -35,15 +35,16 @@ public extension AuthFetchSessionRequest { public init( forceRefresh: Bool = false, - pluginOptions: Any? = nil) { + pluginOptions: Any? = nil + ) { self.forceRefresh = forceRefresh self.pluginOptions = pluginOptions } } } -extension AuthFetchSessionRequest.Options { - public static func forceRefresh() -> AuthFetchSessionRequest.Options { +public extension AuthFetchSessionRequest.Options { + static func forceRefresh() -> AuthFetchSessionRequest.Options { return AuthFetchSessionRequest.Options(forceRefresh: true) } } diff --git a/Amplify/Categories/Auth/Request/AuthForgetDeviceRequest.swift b/Amplify/Categories/Auth/Request/AuthForgetDeviceRequest.swift index 530c0e1f4b..1e59e17e56 100644 --- a/Amplify/Categories/Auth/Request/AuthForgetDeviceRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthForgetDeviceRequest.swift @@ -18,8 +18,10 @@ public struct AuthForgetDeviceRequest: AmplifyOperationRequest { /// Extra request options defined in `AuthForgetDeviceRequest.Options` public var options: Options - public init(device: AuthDevice? = nil, - options: Options) { + public init( + device: AuthDevice? = nil, + options: Options + ) { self.device = device self.options = options } diff --git a/Amplify/Categories/Auth/Request/AuthResetPasswordRequest.swift b/Amplify/Categories/Auth/Request/AuthResetPasswordRequest.swift index 79038d6406..85079dbac0 100644 --- a/Amplify/Categories/Auth/Request/AuthResetPasswordRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthResetPasswordRequest.swift @@ -15,8 +15,10 @@ public struct AuthResetPasswordRequest: AmplifyOperationRequest { /// Extra request options defined in `AuthResetPasswordRequest.Options` public var options: Options - public init(username: String, - options: Options) { + public init( + username: String, + options: Options + ) { self.username = username self.options = options } diff --git a/Amplify/Categories/Auth/Request/AuthSignOutRequest.swift b/Amplify/Categories/Auth/Request/AuthSignOutRequest.swift index fd3343e750..46daad5bbb 100644 --- a/Amplify/Categories/Auth/Request/AuthSignOutRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthSignOutRequest.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AuthenticationServices +import Foundation /// Request for sign out user public struct AuthSignOutRequest: AmplifyOperationRequest { @@ -37,9 +37,11 @@ public extension AuthSignOutRequest { /// in the presentation anchor provided. public let presentationAnchorForWebUI: AuthUIPresentationAnchor? - public init(globalSignOut: Bool = false, - presentationAnchor: AuthUIPresentationAnchor? = nil, - pluginOptions: Any? = nil) { + public init( + globalSignOut: Bool = false, + presentationAnchor: AuthUIPresentationAnchor? = nil, + pluginOptions: Any? = nil + ) { self.globalSignOut = globalSignOut self.pluginOptions = pluginOptions self.presentationAnchorForWebUI = presentationAnchor @@ -55,8 +57,8 @@ public extension AuthSignOutRequest { } #if os(iOS) || os(macOS) || os(visionOS) -extension AuthSignOutRequest.Options { - public static func presentationAnchor(_ anchor: AuthUIPresentationAnchor) -> AuthSignOutRequest.Options { +public extension AuthSignOutRequest.Options { + static func presentationAnchor(_ anchor: AuthUIPresentationAnchor) -> AuthSignOutRequest.Options { return AuthSignOutRequest.Options(presentationAnchor: anchor) } } diff --git a/Amplify/Categories/Auth/Request/AuthSignUpRequest.swift b/Amplify/Categories/Auth/Request/AuthSignUpRequest.swift index e8145e454f..ed61d97a62 100644 --- a/Amplify/Categories/Auth/Request/AuthSignUpRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthSignUpRequest.swift @@ -38,8 +38,10 @@ public extension AuthSignUpRequest { /// key/values public let pluginOptions: Any? - public init(userAttributes: [AuthUserAttribute]? = nil, - pluginOptions: Any? = nil) { + public init( + userAttributes: [AuthUserAttribute]? = nil, + pluginOptions: Any? = nil + ) { self.userAttributes = userAttributes self.pluginOptions = pluginOptions } diff --git a/Amplify/Categories/Auth/Request/AuthUpdateUserAttributeRequest.swift b/Amplify/Categories/Auth/Request/AuthUpdateUserAttributeRequest.swift index be3b978526..b1b76f47c2 100644 --- a/Amplify/Categories/Auth/Request/AuthUpdateUserAttributeRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthUpdateUserAttributeRequest.swift @@ -16,8 +16,10 @@ public struct AuthUpdateUserAttributeRequest: AmplifyOperationRequest { /// Extra request options defined in `AuthUpdateUserAttributeRequest.Options` public var options: Options - public init(userAttribute: AuthUserAttribute, - options: Options) { + public init( + userAttribute: AuthUserAttribute, + options: Options + ) { self.userAttribute = userAttribute self.options = options } diff --git a/Amplify/Categories/Auth/Request/AuthUpdateUserAttributesRequest.swift b/Amplify/Categories/Auth/Request/AuthUpdateUserAttributesRequest.swift index 32a87a794d..41310d470e 100644 --- a/Amplify/Categories/Auth/Request/AuthUpdateUserAttributesRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthUpdateUserAttributesRequest.swift @@ -16,8 +16,10 @@ public struct AuthUpdateUserAttributesRequest: AmplifyOperationRequest { /// Extra request options defined in `AuthUpdateUserAttributesRequest.Options` public var options: Options - public init(userAttributes: [AuthUserAttribute], - options: Options) { + public init( + userAttributes: [AuthUserAttribute], + options: Options + ) { self.userAttributes = userAttributes self.options = options } diff --git a/Amplify/Categories/Auth/Request/AuthWebUISignInRequest.swift b/Amplify/Categories/Auth/Request/AuthWebUISignInRequest.swift index 1946770d02..790c75a9a7 100644 --- a/Amplify/Categories/Auth/Request/AuthWebUISignInRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthWebUISignInRequest.swift @@ -22,9 +22,11 @@ public struct AuthWebUISignInRequest: AmplifyOperationRequest { /// Presentation anchor on which the webUI is displayed public let presentationAnchor: AuthUIPresentationAnchor? - public init(presentationAnchor: AuthUIPresentationAnchor?, - authProvider: AuthProvider? = nil, - options: Options) { + public init( + presentationAnchor: AuthUIPresentationAnchor?, + authProvider: AuthProvider? = nil, + options: Options + ) { self.presentationAnchor = presentationAnchor self.authProvider = authProvider self.options = options @@ -43,8 +45,10 @@ public extension AuthWebUISignInRequest { /// key/values public let pluginOptions: Any? - public init(scopes: [String]? = nil, - pluginOptions: Any? = nil) { + public init( + scopes: [String]? = nil, + pluginOptions: Any? = nil + ) { self.scopes = scopes self.pluginOptions = pluginOptions } diff --git a/Amplify/Categories/Auth/Request/VerifyTOTPSetupRequest.swift b/Amplify/Categories/Auth/Request/VerifyTOTPSetupRequest.swift index 4a03d3ff21..6a3fbfc166 100644 --- a/Amplify/Categories/Auth/Request/VerifyTOTPSetupRequest.swift +++ b/Amplify/Categories/Auth/Request/VerifyTOTPSetupRequest.swift @@ -18,7 +18,8 @@ public struct VerifyTOTPSetupRequest: AmplifyOperationRequest { public init( code: String, - options: Options) { + options: Options + ) { self.code = code self.options = options } diff --git a/Amplify/Categories/DataStore/DataStoreCallback+Combine.swift b/Amplify/Categories/DataStore/DataStoreCallback+Combine.swift index 58bae6f161..c5b9672604 100644 --- a/Amplify/Categories/DataStore/DataStoreCallback+Combine.swift +++ b/Amplify/Categories/DataStore/DataStoreCallback+Combine.swift @@ -7,9 +7,9 @@ import Combine -extension DataStoreResult where Success: Any { +public extension DataStoreResult where Success: Any { - public func resolve(promise: Future.Promise) { + func resolve(promise: Future.Promise) { switch self { case .success(let result): promise(.success(result)) diff --git a/Amplify/Categories/DataStore/DataStoreCallback.swift b/Amplify/Categories/DataStore/DataStoreCallback.swift index be75ee967f..e3afc14dde 100644 --- a/Amplify/Categories/DataStore/DataStoreCallback.swift +++ b/Amplify/Categories/DataStore/DataStoreCallback.swift @@ -11,7 +11,7 @@ import Foundation /// - seealso: [DataStoreCallback](#DataStoreCallback) public typealias DataStoreResult = Result -extension DataStoreResult { +public extension DataStoreResult { /// Creates a `DataStoreResult` based on a error raised during `DataStore` operations. /// In case the error is not already a `DataStoreError`, it gets wrapped @@ -19,12 +19,12 @@ extension DataStoreResult { /// /// - Parameter error: the root cause of the failure /// - Returns: a `DataStoreResult.error` - public static func failure(causedBy error: Error) -> DataStoreResult { + static func failure(causedBy error: Error) -> DataStoreResult { let dataStoreError = error as? DataStoreError ?? .invalidOperation(causedBy: error) return .failure(dataStoreError) } - public static var emptyResult: DataStoreResult { + static var emptyResult: DataStoreResult { .successfulVoid } diff --git a/Amplify/Categories/DataStore/DataStoreCategory+Behavior.swift b/Amplify/Categories/DataStore/DataStoreCategory+Behavior.swift index 4d15a9bff1..489b02e8bf 100644 --- a/Amplify/Categories/DataStore/DataStoreCategory+Behavior.swift +++ b/Amplify/Categories/DataStore/DataStoreCategory+Behavior.swift @@ -8,61 +8,81 @@ extension DataStoreCategory: DataStoreBaseBehavior { @discardableResult - public func save(_ model: M, - where condition: QueryPredicate? = nil) async throws -> M { + public func save( + _ model: M, + where condition: QueryPredicate? = nil + ) async throws -> M { try await plugin.save(model, where: condition) } - public func query(_ modelType: M.Type, - byId id: String) async throws -> M? { + public func query( + _ modelType: M.Type, + byId id: String + ) async throws -> M? { try await plugin.query(modelType, byId: id) } - public func query(_ modelType: M.Type, - byIdentifier id: String) async throws -> M? + public func query( + _ modelType: M.Type, + byIdentifier id: String + ) async throws -> M? where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { try await plugin.query(modelType, byIdentifier: id) } - public func query(_ modelType: M.Type, - byIdentifier identifier: ModelIdentifier) + public func query( + _ modelType: M.Type, + byIdentifier identifier: ModelIdentifier + ) async throws -> M? where M: ModelIdentifiable { try await plugin.query(modelType, byIdentifier: identifier) } - public func query(_ modelType: M.Type, - where predicate: QueryPredicate? = nil, - sort sortInput: QuerySortInput? = nil, - paginate paginationInput: QueryPaginationInput? = nil) async throws -> [M] { + public func query( + _ modelType: M.Type, + where predicate: QueryPredicate? = nil, + sort sortInput: QuerySortInput? = nil, + paginate paginationInput: QueryPaginationInput? = nil + ) async throws -> [M] { try await plugin.query(modelType, where: predicate, sort: sortInput, paginate: paginationInput) } - public func delete(_ model: M, - where predicate: QueryPredicate? = nil) async throws { + public func delete( + _ model: some Model, + where predicate: QueryPredicate? = nil + ) async throws { try await plugin.delete(model, where: predicate) } - public func delete(_ modelType: M.Type, - withId id: String, - where predicate: QueryPredicate? = nil) async throws { + public func delete( + _ modelType: (some Model).Type, + withId id: String, + where predicate: QueryPredicate? = nil + ) async throws { try await plugin.delete(modelType, withId: id, where: predicate) } - public func delete(_ modelType: M.Type, - withIdentifier id: String, - where predicate: QueryPredicate? = nil) async throws + public func delete( + _ modelType: M.Type, + withIdentifier id: String, + where predicate: QueryPredicate? = nil + ) async throws where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { try await plugin.delete(modelType, withIdentifier: id, where: predicate) } - public func delete(_ modelType: M.Type, - withIdentifier id: ModelIdentifier, - where predicate: QueryPredicate? = nil) async throws where M: ModelIdentifiable { + public func delete( + _ modelType: M.Type, + withIdentifier id: ModelIdentifier, + where predicate: QueryPredicate? = nil + ) async throws where M: ModelIdentifiable { try await plugin.delete(modelType, withIdentifier: id, where: predicate) } - public func delete(_ modelType: M.Type, - where predicate: QueryPredicate) async throws { + public func delete( + _ modelType: (some Model).Type, + where predicate: QueryPredicate + ) async throws { try await plugin.delete(modelType, where: predicate) } diff --git a/Amplify/Categories/DataStore/DataStoreCategory.swift b/Amplify/Categories/DataStore/DataStoreCategory.swift index ec2e8a29ab..7e2fc4f85e 100644 --- a/Amplify/Categories/DataStore/DataStoreCategory.swift +++ b/Amplify/Categories/DataStore/DataStoreCategory.swift @@ -7,7 +7,7 @@ import Foundation -final public class DataStoreCategory: Category { +public final class DataStoreCategory: Category { /// Always .dataStore public let categoryType: CategoryType = .dataStore @@ -54,8 +54,10 @@ final public class DataStoreCategory: Category { let key = plugin.key guard !key.isEmpty else { let pluginDescription = String(describing: plugin) - let error = DataStoreError.configuration("Plugin \(pluginDescription) has an empty `key`.", - "Set the `key` property for \(String(describing: plugin))") + let error = DataStoreError.configuration( + "Plugin \(pluginDescription) has an empty `key`.", + "Set the `key` property for \(String(describing: plugin))" + ) throw error } @@ -78,8 +80,10 @@ final public class DataStoreCategory: Category { public func getPlugin(for key: PluginKey) throws -> DataStoreCategoryPlugin { guard let plugin = plugins[key] else { let keys = plugins.keys.joined(separator: ", ") - let error = DataStoreError.configuration("No plugin has been added for '\(key)'.", - "Either add a plugin for '\(key)', or use one of the known keys: \(keys)") + let error = DataStoreError.configuration( + "No plugin has been added for '\(key)'.", + "Either add a plugin for '\(key)', or use one of the known keys: \(keys)" + ) throw error } return plugin diff --git a/Amplify/Categories/DataStore/DataStoreCategoryBehavior.swift b/Amplify/Categories/DataStore/DataStoreCategoryBehavior.swift index 43aa4d3892..88ef599cb2 100644 --- a/Amplify/Categories/DataStore/DataStoreCategoryBehavior.swift +++ b/Amplify/Categories/DataStore/DataStoreCategoryBehavior.swift @@ -13,44 +13,64 @@ public protocol DataStoreBaseBehavior { /// Saves the model to storage. If sync is enabled, also initiates a sync of the mutation to the remote API @discardableResult - func save(_ model: M, - where condition: QueryPredicate?) async throws -> M + func save( + _ model: M, + where condition: QueryPredicate? + ) async throws -> M @available(*, deprecated, renamed: "query(byIdentifier:)") - func query(_ modelType: M.Type, - byId id: String) async throws -> M? - - func query(_ modelType: M.Type, - byIdentifier id: String) async throws -> M? + func query( + _ modelType: M.Type, + byId id: String + ) async throws -> M? + + func query( + _ modelType: M.Type, + byIdentifier id: String + ) async throws -> M? where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default - func query(_ modelType: M.Type, - byIdentifier id: ModelIdentifier) async throws -> M? + func query( + _ modelType: M.Type, + byIdentifier id: ModelIdentifier + ) async throws -> M? where M: ModelIdentifiable - func query(_ modelType: M.Type, - where predicate: QueryPredicate?, - sort sortInput: QuerySortInput?, - paginate paginationInput: QueryPaginationInput?) async throws -> [M] - - func delete(_ model: M, - where predicate: QueryPredicate?) async throws - - func delete(_ modelType: M.Type, - withId id: String, - where predicate: QueryPredicate?) async throws - - func delete(_ modelType: M.Type, - withIdentifier id: String, - where predicate: QueryPredicate?) async throws where M: ModelIdentifiable, + func query( + _ modelType: M.Type, + where predicate: QueryPredicate?, + sort sortInput: QuerySortInput?, + paginate paginationInput: QueryPaginationInput? + ) async throws -> [M] + + func delete( + _ model: M, + where predicate: QueryPredicate? + ) async throws + + func delete( + _ modelType: M.Type, + withId id: String, + where predicate: QueryPredicate? + ) async throws + + func delete( + _ modelType: M.Type, + withIdentifier id: String, + where predicate: QueryPredicate? + ) async throws where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default - func delete(_ modelType: M.Type, - withIdentifier id: ModelIdentifier, - where predicate: QueryPredicate?) async throws where M: ModelIdentifiable + func delete( + _ modelType: M.Type, + withIdentifier id: ModelIdentifier, + where predicate: QueryPredicate? + ) async throws where M: ModelIdentifiable - func delete(_ modelType: M.Type, - where predicate: QueryPredicate) async throws + func delete( + _ modelType: M.Type, + where predicate: QueryPredicate + ) async throws /** Synchronization starts automatically whenever you run any DataStore operation (query(), save(), delete()) @@ -89,8 +109,10 @@ public protocol DataStoreSubscribeBehavior { /// - modelType: The model type to observe /// - predicate: The predicate to match for filtered results /// - sortInput: The field and order of data to be returned - func observeQuery(for modelType: M.Type, - where predicate: QueryPredicate?, - sort sortInput: QuerySortInput?) + func observeQuery( + for modelType: M.Type, + where predicate: QueryPredicate?, + sort sortInput: QuerySortInput? + ) -> AmplifyAsyncThrowingSequence> } diff --git a/Amplify/Categories/DataStore/Model/Internal/Embedded.swift b/Amplify/Categories/DataStore/Model/Internal/Embedded.swift index 0a588d1d43..3e5adada7d 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Embedded.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Embedded.swift @@ -23,12 +23,16 @@ public protocol Embeddable: Codable { static var schema: ModelSchema { get } } -extension Embeddable { - public static func defineSchema(name: String? = nil, - attributes: ModelAttribute..., - define: (inout ModelSchemaDefinition) -> Void) -> ModelSchema { - var definition = ModelSchemaDefinition(name: name ?? "", - attributes: attributes) +public extension Embeddable { + static func defineSchema( + name: String? = nil, + attributes: ModelAttribute..., + define: (inout ModelSchemaDefinition) -> Void + ) -> ModelSchema { + var definition = ModelSchemaDefinition( + name: name ?? "", + attributes: attributes + ) define(&definition) return definition.build() } diff --git a/Amplify/Categories/DataStore/Model/Internal/Model+Array.swift b/Amplify/Categories/DataStore/Model/Internal/Model+Array.swift index 4054f30af8..8a0b17b405 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Model+Array.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Model+Array.swift @@ -7,13 +7,13 @@ import Foundation -extension Array where Element: Model { +public extension Array where Element: Model { /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public func unique() throws -> Element? { + func unique() throws -> Element? { guard (0 ... 1).contains(count) else { throw DataStoreError.nonUniqueResult(model: Element.modelName, count: count) } @@ -21,13 +21,13 @@ extension Array where Element: Model { } } -extension Array where Element == Model { +public extension [Model] { /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public func unique() throws -> Element? { + func unique() throws -> Element? { guard (0 ... 1).contains(count) else { let firstModelName = self[0].modelName throw DataStoreError.nonUniqueResult(model: firstModelName, count: count) diff --git a/Amplify/Categories/DataStore/Model/Internal/Model+Codable.swift b/Amplify/Categories/DataStore/Model/Internal/Model+Codable.swift index 2eff95f1e7..58fb41b0e2 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Model+Codable.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Model+Codable.swift @@ -8,7 +8,7 @@ import Foundation /// Adds JSON serialization behavior to all types that conform to the `Model` protocol. -extension Model where Self: Codable { +public extension Model where Self: Codable { /// De-serialize a JSON string into an instance of the concrete type that conforms /// to the `Model` protocol. @@ -24,13 +24,14 @@ extension Model where Self: Codable { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public static func from(json: String, - decoder: JSONDecoder? = nil) throws -> Self { - let resolvedDecoder: JSONDecoder - if let decoder = decoder { - resolvedDecoder = decoder + static func from( + json: String, + decoder: JSONDecoder? = nil + ) throws -> Self { + let resolvedDecoder: JSONDecoder = if let decoder { + decoder } else { - resolvedDecoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy) + JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy) } return try resolvedDecoder.decode(Self.self, from: Data(json.utf8)) @@ -47,7 +48,7 @@ extension Model where Self: Codable { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public static func from(dictionary: [String: Any]) throws -> Self { + static func from(dictionary: [String: Any]) throws -> Self { let data = try JSONSerialization.data(withJSONObject: dictionary) let decoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy) return try decoder.decode(Self.self, from: data) @@ -63,7 +64,7 @@ extension Model where Self: Codable { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public func toJSON(encoder: JSONEncoder? = nil) throws -> String { + func toJSON(encoder: JSONEncoder? = nil) throws -> String { var resolvedEncoder = encoder ?? JSONEncoder( dateEncodingStrategy: ModelDateFormatting.encodingStrategy ) diff --git a/Amplify/Categories/DataStore/Model/Internal/Model+DateFormatting.swift b/Amplify/Categories/DataStore/Model/Internal/Model+DateFormatting.swift index 8540f066a9..489f9d108e 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Model+DateFormatting.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Model+DateFormatting.swift @@ -11,7 +11,7 @@ import Foundation /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. -public struct ModelDateFormatting { +public enum ModelDateFormatting { public static let decodingStrategy: JSONDecoder.DateDecodingStrategy = { let strategy = JSONDecoder.DateDecodingStrategy.custom { decoder -> Date in diff --git a/Amplify/Categories/DataStore/Model/Internal/Model+Subscript.swift b/Amplify/Categories/DataStore/Model/Internal/Model+Subscript.swift index 97aed1b40c..4b5eff6930 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Model+Subscript.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Model+Subscript.swift @@ -10,13 +10,13 @@ /// ```swift /// let id = model["id"] /// ``` -extension Model { +public extension Model { /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public subscript(_ key: String) -> Any?? { + subscript(_ key: String) -> Any?? { if let jsonModel = self as? JSONValueHolder { let value = jsonModel.jsonValue(for: key) diff --git a/Amplify/Categories/DataStore/Model/Internal/ModelListDecoder.swift b/Amplify/Categories/DataStore/Model/Internal/ModelListDecoder.swift index f3d30371f4..1cf2a88816 100644 --- a/Amplify/Categories/DataStore/Model/Internal/ModelListDecoder.swift +++ b/Amplify/Categories/DataStore/Model/Internal/ModelListDecoder.swift @@ -14,7 +14,7 @@ import Foundation /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a breaking /// change. -public struct ModelListDecoderRegistry { +public enum ModelListDecoderRegistry { public static var listDecoders = AtomicValue(initialValue: [ModelListDecoder.Type]()) /// Register a decoder during plugin configuration time, to allow runtime retrievals of list providers. diff --git a/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift b/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift index 98c93dfa00..384dffda7f 100644 --- a/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift +++ b/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift @@ -6,6 +6,7 @@ // import Foundation + // swiftlint:disable type_name /// Protocol used as a marker to detect when the type is a `LazyReference`. /// Used to retrieve either the `reference` or the `identifiers` of the Model directly, without having load a not diff --git a/Amplify/Categories/DataStore/Model/Internal/ModelProviderDecoder.swift b/Amplify/Categories/DataStore/Model/Internal/ModelProviderDecoder.swift index 8470cba587..0b14cefbad 100644 --- a/Amplify/Categories/DataStore/Model/Internal/ModelProviderDecoder.swift +++ b/Amplify/Categories/DataStore/Model/Internal/ModelProviderDecoder.swift @@ -14,7 +14,7 @@ import Foundation /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a breaking /// change. -public struct ModelProviderRegistry { +public enum ModelProviderRegistry { static var decoders = AtomicValue(initialValue: [ModelProviderDecoder.Type]()) /// Register a decoder during plugin configuration time, to allow runtime retrievals of model providers. @@ -33,8 +33,8 @@ extension ModelProviderRegistry { public extension ModelProviderRegistry { /// Static decoder sources that will be referenced to initialize different type of decoders having source as - /// a metadata. - struct DecoderSource { + /// a metadata. + enum DecoderSource { public static let dataStore = "DataStore" public static let appSync = "AppSync" } diff --git a/Amplify/Categories/DataStore/Model/Internal/ModelRegistry.swift b/Amplify/Categories/DataStore/Model/Internal/ModelRegistry.swift index ff3fd6ef1c..6d6b5a4979 100644 --- a/Amplify/Categories/DataStore/Model/Internal/ModelRegistry.swift +++ b/Amplify/Categories/DataStore/Model/Internal/ModelRegistry.swift @@ -9,9 +9,11 @@ import Foundation /// - Warning: Although this has `public` access, it is intended for internal use and should not be used directly /// by host applications. The behavior of this may change without warning. -public struct ModelRegistry { - private static let concurrencyQueue = DispatchQueue(label: "com.amazonaws.ModelRegistry.concurrency", - target: DispatchQueue.global()) +public enum ModelRegistry { + private static let concurrencyQueue = DispatchQueue( + label: "com.amazonaws.ModelRegistry.concurrency", + target: DispatchQueue.global() + ) /// ModelDecoders are used to decode untyped model data, looking up by model name private typealias ModelDecoder = (String, JSONDecoder?) throws -> Model @@ -35,16 +37,20 @@ public struct ModelRegistry { } public static func register(modelType: Model.Type) { - register(modelType: modelType, - modelSchema: modelType.schema) { (jsonString, jsonDecoder) -> Model in + register( + modelType: modelType, + modelSchema: modelType.schema + ) { jsonString, jsonDecoder -> Model in let model = try modelType.from(json: jsonString, decoder: jsonDecoder) return model } } - public static func register(modelType: Model.Type, - modelSchema: ModelSchema, - jsonDecoder: @escaping (String, JSONDecoder?) throws -> Model) { + public static func register( + modelType: Model.Type, + modelSchema: ModelSchema, + jsonDecoder: @escaping (String, JSONDecoder?) throws -> Model + ) { concurrencyQueue.sync { let modelDecoder: ModelDecoder = { jsonString, decoder in return try jsonDecoder(jsonString, decoder) @@ -75,9 +81,11 @@ public struct ModelRegistry { } } - public static func decode(modelName: ModelName, - from jsonString: String, - jsonDecoder: JSONDecoder? = nil) throws -> Model { + public static func decode( + modelName: ModelName, + from jsonString: String, + jsonDecoder: JSONDecoder? = nil + ) throws -> Model { try concurrencyQueue.sync { guard let decoder = modelDecoders[modelName] else { throw DataStoreError.decodingError( @@ -85,7 +93,8 @@ public struct ModelRegistry { """ There is no decoder registered for the model named \(modelName). \ Register models with `ModelRegistry.register(modelName:)` at startup. - """) + """ + ) } return try decoder(jsonString, jsonDecoder) diff --git a/Amplify/Categories/DataStore/Model/Internal/Persistable.swift b/Amplify/Categories/DataStore/Model/Internal/Persistable.swift index 92fd149d8d..cb3c62051e 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Persistable.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Persistable.swift @@ -30,7 +30,7 @@ extension Temporal.Date: Persistable {} extension Temporal.DateTime: Persistable {} extension Temporal.Time: Persistable {} -struct PersistableHelper { +enum PersistableHelper { /// Polymorphic utility that allows two persistable references to be checked /// for equality regardless of their concrete type. diff --git a/Amplify/Categories/DataStore/Model/Internal/Schema/AuthRule.swift b/Amplify/Categories/DataStore/Model/Internal/Schema/AuthRule.swift index 8a5c6b4aeb..f50034b4d0 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Schema/AuthRule.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Schema/AuthRule.swift @@ -50,14 +50,16 @@ public struct AuthRule { public let operations: [ModelOperation] public let provider: AuthRuleProvider? - public init(allow: AuthStrategy, - ownerField: String? = nil, - identityClaim: String? = nil, - groupClaim: String? = nil, - groups: [String] = [], - groupsField: String? = nil, - provider: AuthRuleProvider? = nil, - operations: [ModelOperation] = []) { + public init( + allow: AuthStrategy, + ownerField: String? = nil, + identityClaim: String? = nil, + groupClaim: String? = nil, + groups: [String] = [], + groupsField: String? = nil, + provider: AuthRuleProvider? = nil, + operations: [ModelOperation] = [] + ) { self.allow = allow self.ownerField = ownerField self.identityClaim = identityClaim diff --git a/Amplify/Categories/DataStore/Model/Internal/Schema/Model+Schema.swift b/Amplify/Categories/DataStore/Model/Internal/Schema/Model+Schema.swift index 7a09d82580..4139e01560 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Schema/Model+Schema.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Schema/Model+Schema.swift @@ -7,13 +7,13 @@ import Foundation -extension Model { +public extension Model { /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public static var schema: ModelSchema { + static var schema: ModelSchema { // TODO load schema from JSON when this it not overridden by specific models ModelSchema(name: modelName, fields: [:]) } @@ -22,7 +22,7 @@ extension Model { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var schema: ModelSchema { + var schema: ModelSchema { type(of: self).schema } @@ -46,32 +46,40 @@ extension Model { /// - Returns: a valid `ModelSchema` instance /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used /// directly by host applications. The behavior of this may change without warning. - public static func defineSchema(name: String? = nil, - attributes: ModelAttribute..., - define: (inout ModelSchemaDefinition) -> Void) -> ModelSchema { - var definition = ModelSchemaDefinition(name: name ?? modelName, - attributes: attributes) + static func defineSchema( + name: String? = nil, + attributes: ModelAttribute..., + define: (inout ModelSchemaDefinition) -> Void + ) -> ModelSchema { + var definition = ModelSchemaDefinition( + name: name ?? modelName, + attributes: attributes + ) define(&definition) return definition.build() } /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used /// directly by host applications. The behavior of this may change without warning. - public static func rule(allow: AuthStrategy, - ownerField: String? = nil, - identityClaim: String? = nil, - groupClaim: String? = nil, - groups: [String] = [], - groupsField: String? = nil, - provider: AuthRuleProvider? = nil, - operations: [ModelOperation] = []) -> AuthRule { - return AuthRule(allow: allow, - ownerField: ownerField, - identityClaim: identityClaim, - groupClaim: groupClaim, - groups: groups, - groupsField: groupsField, - provider: provider, - operations: operations) + static func rule( + allow: AuthStrategy, + ownerField: String? = nil, + identityClaim: String? = nil, + groupClaim: String? = nil, + groups: [String] = [], + groupsField: String? = nil, + provider: AuthRuleProvider? = nil, + operations: [ModelOperation] = [] + ) -> AuthRule { + return AuthRule( + allow: allow, + ownerField: ownerField, + identityClaim: identityClaim, + groupClaim: groupClaim, + groups: groups, + groupsField: groupsField, + provider: provider, + operations: operations + ) } } diff --git a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelField+Association.swift b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelField+Association.swift index 4ebe4bcb5a..c8031a8933 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelField+Association.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelField+Association.swift @@ -104,7 +104,7 @@ public enum ModelAssociation { ) -> ModelAssociation { return .hasMany( associatedFieldName: associatedWith?.stringValue, - associatedFieldNames: associatedFields.map { $0.stringValue } + associatedFieldNames: associatedFields.map(\.stringValue) ) } @@ -117,11 +117,13 @@ public enum ModelAssociation { public static func hasOne( associatedWith: CodingKey? = nil, associatedFields: [CodingKey] = [], - targetNames: [String] = []) -> ModelAssociation { + targetNames: [String] = [] + ) -> ModelAssociation { return .hasOne( associatedFieldName: associatedWith?.stringValue, - associatedFieldNames: associatedFields.map { $0.stringValue }, - targetNames: targetNames) + associatedFieldNames: associatedFields.map(\.stringValue), + targetNames: targetNames + ) } @available(*, deprecated, message: "Use belongsTo(associatedWith:targetNames:)") @@ -136,13 +138,13 @@ public enum ModelAssociation { } -extension ModelField { +public extension ModelField { /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var hasAssociation: Bool { + var hasAssociation: Bool { return association != nil } @@ -156,7 +158,7 @@ extension ModelField { @available(*, deprecated, message: """ Use of associated model type is deprecated, use `associatedModelName` instead. """) - public var associatedModel: Model.Type? { + var associatedModel: Model.Type? { switch type { case .model(let modelName), .collection(let modelName): return ModelRegistry.modelType(from: modelName) @@ -172,7 +174,7 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var associatedModelName: ModelName? { + var associatedModelName: ModelName? { switch type { case .model(let modelName), .collection(let modelName): return modelName @@ -196,7 +198,7 @@ extension ModelField { Use of requiredAssociatedModel with Model.Type is deprecated, use `requiredAssociatedModelName` that return ModelName instead. """) - public var requiredAssociatedModel: Model.Type { + var requiredAssociatedModel: Model.Type { guard let modelType = associatedModel else { return Fatal.preconditionFailure(""" Model fields that are foreign keys must be connected to another Model. @@ -217,7 +219,7 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var requiredAssociatedModelName: ModelName { + var requiredAssociatedModelName: ModelName { guard let modelName = associatedModelName else { return Fatal.preconditionFailure(""" Model fields that are foreign keys must be connected to another Model. @@ -231,7 +233,7 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var isAssociationOwner: Bool { + var isAssociationOwner: Bool { guard case .belongsTo = association else { return false } @@ -242,7 +244,7 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var _isBelongsToOrHasOne: Bool { // swiftlint:disable:this identifier_name + var _isBelongsToOrHasOne: Bool { // swiftlint:disable:this identifier_name switch association { case .belongsTo, .hasOne: return true @@ -255,7 +257,7 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var associatedField: ModelField? { + var associatedField: ModelField? { if hasAssociation { let associatedModel = requiredAssociatedModelName switch association { @@ -277,10 +279,10 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var associatedFieldNames: [String] { + var associatedFieldNames: [String] { switch association { case .hasMany(let associatedKey, let associatedKeys): - if associatedKeys.isEmpty, let associatedKey = associatedKey { + if associatedKeys.isEmpty, let associatedKey { return [associatedKey] } return associatedKeys @@ -300,7 +302,7 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var isOneToOne: Bool { + var isOneToOne: Bool { if case .hasOne = association { return true } @@ -314,7 +316,7 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var isOneToMany: Bool { + var isOneToMany: Bool { if case .hasMany = association, case .belongsTo = associatedField?.association { return true } @@ -325,7 +327,7 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var isManyToOne: Bool { + var isManyToOne: Bool { if case .belongsTo = association, case .hasMany = associatedField?.association { return true } @@ -339,7 +341,7 @@ extension ModelField { @available(*, deprecated, message: """ Use `embeddedType` is deprecated, use `embeddedTypeSchema` instead. """) - public var embeddedType: Embeddable.Type? { + var embeddedType: Embeddable.Type? { switch type { case .embedded(let type, _), .embeddedCollection(let type, _): if let embeddedType = type as? Embeddable.Type { @@ -355,7 +357,7 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var embeddedTypeSchema: ModelSchema? { + var embeddedTypeSchema: ModelSchema? { switch type { case .embedded(_, let modelSchema), .embeddedCollection(_, let modelSchema): return modelSchema @@ -368,7 +370,7 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var isEmbeddedType: Bool { + var isEmbeddedType: Bool { switch type { case .embedded, .embeddedCollection: return true diff --git a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelPrimaryKey.swift b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelPrimaryKey.swift index 38d8ccec63..cb38c40fa6 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelPrimaryKey.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelPrimaryKey.swift @@ -13,18 +13,22 @@ public struct ModelPrimaryKey { fields.count > 1 } - init?(allFields: ModelFields, - attributes: [ModelAttribute], - primaryKeyFieldKeys: [String] = []) { - self.fields = resolvePrimaryKeyFields(allFields: allFields, - attributes: attributes, - primaryKeyFieldKeys: primaryKeyFieldKeys) + init?( + allFields: ModelFields, + attributes: [ModelAttribute], + primaryKeyFieldKeys: [String] = [] + ) { + self.fields = resolvePrimaryKeyFields( + allFields: allFields, + attributes: attributes, + primaryKeyFieldKeys: primaryKeyFieldKeys + ) if fields.isEmpty { return nil } - self.fieldsLookup = Set(fields.map { $0.name }) + self.fieldsLookup = Set(fields.map(\.name)) } /// Returns the list of fields that make up the primary key for the model. @@ -49,9 +53,11 @@ public struct ModelPrimaryKey { /// It returns an array of fields as custom and composite primary keys are supported. /// - Parameter fields: schema model fields /// - Returns: an array of model fields - func resolvePrimaryKeyFields(allFields: ModelFields, - attributes: [ModelAttribute], - primaryKeyFieldKeys: [String]) -> [ModelField] { + func resolvePrimaryKeyFields( + allFields: ModelFields, + attributes: [ModelAttribute], + primaryKeyFieldKeys: [String] + ) -> [ModelField] { var primaryKeyFields: [ModelField] = [] if !primaryKeyFieldKeys.isEmpty { @@ -64,8 +70,8 @@ public struct ModelPrimaryKey { /// if indexes aren't defined most likely the model has a default `id` as PK /// so we have to rely on the `.primaryKey` attribute of each individual field - } else if attributes.indexes.filter({ $0.isPrimaryKeyIndex }).isEmpty { - primaryKeyFields = allFields.values.filter { $0.isPrimaryKey } + } else if attributes.indexes.filter(\.isPrimaryKeyIndex).isEmpty { + primaryKeyFields = allFields.values.filter(\.isPrimaryKey) /// Use the array of fields with a primary key index } else if let fieldNames = primaryFieldsFromIndexes(attributes: attributes) { diff --git a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+AuthRulesByOperation.swift b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+AuthRulesByOperation.swift index d7d02d2b6a..f65b31c77f 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+AuthRulesByOperation.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+AuthRulesByOperation.swift @@ -7,7 +7,7 @@ import Foundation -public extension Array where Element == AuthRule { +public extension [AuthRule] { /// Returns all the `AuthRule` that apply to a given a `ModelOperation` /// - Parameter operation: `ModelOperation` operation diff --git a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+Definition.swift b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+Definition.swift index 35e6f1210d..febe4cfc87 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+Definition.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+Definition.swift @@ -123,7 +123,7 @@ public enum ModelFieldNullability { /// directly by host applications. The behavior of this may change without warning. public struct ModelSchemaDefinition { - internal let name: String + let name: String @available(*, deprecated, message: "Use of pluralName is deprecated, use syncPluralName instead.") public var pluralName: String? @@ -132,16 +132,18 @@ public struct ModelSchemaDefinition { public var syncPluralName: String? public var authRules: AuthRules - internal var fields: ModelFields - internal var primarykeyFields: [ModelFieldName] - internal var attributes: [ModelAttribute] - - init(name: String, - pluralName: String? = nil, - listPluralName: String? = nil, - syncPluralName: String? = nil, - authRules: AuthRules = [], - attributes: [ModelAttribute] = []) { + var fields: ModelFields + var primarykeyFields: [ModelFieldName] + var attributes: [ModelAttribute] + + init( + name: String, + pluralName: String? = nil, + listPluralName: String? = nil, + syncPluralName: String? = nil, + authRules: AuthRules = [], + attributes: [ModelAttribute] = [] + ) { self.name = name self.pluralName = pluralName self.listPluralName = listPluralName @@ -153,7 +155,7 @@ public struct ModelSchemaDefinition { } public mutating func fields(_ fields: ModelFieldDefinition...) { - fields.forEach { definition in + for definition in fields { let field = definition.modelField self.fields[field.name] = field } @@ -174,43 +176,51 @@ public struct ModelSchemaDefinition { primarykeyFields = primaryKeyDefinition.first ?? [] } - internal func build() -> ModelSchema { - return ModelSchema(name: name, - pluralName: pluralName, - listPluralName: listPluralName, - syncPluralName: syncPluralName, - authRules: authRules, - attributes: attributes, - fields: fields, - primaryKeyFieldKeys: primarykeyFields) + func build() -> ModelSchema { + return ModelSchema( + name: name, + pluralName: pluralName, + listPluralName: listPluralName, + syncPluralName: syncPluralName, + authRules: authRules, + attributes: attributes, + fields: fields, + primaryKeyFieldKeys: primarykeyFields + ) } } /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used /// directly by host applications. The behavior of this may change without warning. public enum ModelFieldDefinition { - case field(name: String, - type: ModelFieldType, - nullability: ModelFieldNullability, - isReadOnly: Bool, - association: ModelAssociation?, - attributes: [ModelFieldAttribute], - authRules: AuthRules) - - public static func field(_ key: CodingKey, - is nullability: ModelFieldNullability = .required, - isReadOnly: Bool = false, - ofType type: ModelFieldType = .string, - attributes: [ModelFieldAttribute] = [], - association: ModelAssociation? = nil, - authRules: AuthRules = []) -> ModelFieldDefinition { - return .field(name: key.stringValue, - type: type, - nullability: nullability, - isReadOnly: isReadOnly, - association: association, - attributes: attributes, - authRules: authRules) + case field( + name: String, + type: ModelFieldType, + nullability: ModelFieldNullability, + isReadOnly: Bool, + association: ModelAssociation?, + attributes: [ModelFieldAttribute], + authRules: AuthRules + ) + + public static func field( + _ key: CodingKey, + is nullability: ModelFieldNullability = .required, + isReadOnly: Bool = false, + ofType type: ModelFieldType = .string, + attributes: [ModelFieldAttribute] = [], + association: ModelAssociation? = nil, + authRules: AuthRules = [] + ) -> ModelFieldDefinition { + return .field( + name: key.stringValue, + type: type, + nullability: nullability, + isReadOnly: isReadOnly, + association: association, + attributes: attributes, + authRules: authRules + ) } @available(*, deprecated, message: "Use .primaryKey(fields:)") @@ -220,123 +230,160 @@ public enum ModelFieldDefinition { @available(*, deprecated, message: "Use .primaryKey(fields:)") public static func id(_ name: String = "id") -> ModelFieldDefinition { - return .field(name: name, - type: .string, - nullability: .required, - isReadOnly: false, - association: nil, - attributes: [.primaryKey], - authRules: []) + return .field( + name: name, + type: .string, + nullability: .required, + isReadOnly: false, + association: nil, + attributes: [.primaryKey], + authRules: [] + ) } - public static func hasMany(_ key: CodingKey, - is nullability: ModelFieldNullability = .required, - isReadOnly: Bool = false, - ofType type: Model.Type, - associatedWith associatedKey: CodingKey) -> ModelFieldDefinition { - return .field(key, - is: nullability, - isReadOnly: isReadOnly, - ofType: .collection(of: type), - association: .hasMany(associatedWith: associatedKey)) + public static func hasMany( + _ key: CodingKey, + is nullability: ModelFieldNullability = .required, + isReadOnly: Bool = false, + ofType type: Model.Type, + associatedWith associatedKey: CodingKey + ) -> ModelFieldDefinition { + return .field( + key, + is: nullability, + isReadOnly: isReadOnly, + ofType: .collection(of: type), + association: .hasMany(associatedWith: associatedKey) + ) } - public static func hasMany(_ key: CodingKey, - is nullability: ModelFieldNullability = .required, - isReadOnly: Bool = false, - ofType type: Model.Type, - associatedFields associatedKeys: [CodingKey]) -> ModelFieldDefinition { - return .field(key, - is: nullability, - isReadOnly: isReadOnly, - ofType: .collection(of: type), - association: .hasMany(associatedWith: associatedKeys.first, associatedFields: associatedKeys)) + public static func hasMany( + _ key: CodingKey, + is nullability: ModelFieldNullability = .required, + isReadOnly: Bool = false, + ofType type: Model.Type, + associatedFields associatedKeys: [CodingKey] + ) -> ModelFieldDefinition { + return .field( + key, + is: nullability, + isReadOnly: isReadOnly, + ofType: .collection(of: type), + association: .hasMany(associatedWith: associatedKeys.first, associatedFields: associatedKeys) + ) } - public static func hasOne(_ key: CodingKey, - is nullability: ModelFieldNullability = .required, - isReadOnly: Bool = false, - ofType type: Model.Type, - associatedWith associatedKey: CodingKey, - targetName: String? = nil) -> ModelFieldDefinition { - return .field(key, - is: nullability, - isReadOnly: isReadOnly, - ofType: .model(type: type), - association: .hasOne(associatedWith: associatedKey, targetNames: targetName.map { [$0] } ?? [])) + public static func hasOne( + _ key: CodingKey, + is nullability: ModelFieldNullability = .required, + isReadOnly: Bool = false, + ofType type: Model.Type, + associatedWith associatedKey: CodingKey, + targetName: String? = nil + ) -> ModelFieldDefinition { + return .field( + key, + is: nullability, + isReadOnly: isReadOnly, + ofType: .model(type: type), + association: .hasOne(associatedWith: associatedKey, targetNames: targetName.map { [$0] } ?? []) + ) } - public static func hasOne(_ key: CodingKey, - is nullability: ModelFieldNullability = .required, - isReadOnly: Bool = false, - ofType type: Model.Type, - associatedWith associatedKey: CodingKey, - targetNames: [String]) -> ModelFieldDefinition { - return .field(key, - is: nullability, - isReadOnly: isReadOnly, - ofType: .model(type: type), - association: .hasOne(associatedWith: associatedKey, targetNames: targetNames)) + public static func hasOne( + _ key: CodingKey, + is nullability: ModelFieldNullability = .required, + isReadOnly: Bool = false, + ofType type: Model.Type, + associatedWith associatedKey: CodingKey, + targetNames: [String] + ) -> ModelFieldDefinition { + return .field( + key, + is: nullability, + isReadOnly: isReadOnly, + ofType: .model(type: type), + association: .hasOne(associatedWith: associatedKey, targetNames: targetNames) + ) } - public static func hasOne(_ key: CodingKey, - is nullability: ModelFieldNullability = .required, - isReadOnly: Bool = false, - ofType type: Model.Type, - associatedFields associatedKeys: [CodingKey], - targetNames: [String] = []) -> ModelFieldDefinition { - return .field(key, - is: nullability, - isReadOnly: isReadOnly, - ofType: .model(type: type), - association: .hasOne(associatedWith: associatedKeys.first, - associatedFields: associatedKeys, - targetNames: targetNames)) + public static func hasOne( + _ key: CodingKey, + is nullability: ModelFieldNullability = .required, + isReadOnly: Bool = false, + ofType type: Model.Type, + associatedFields associatedKeys: [CodingKey], + targetNames: [String] = [] + ) -> ModelFieldDefinition { + return .field( + key, + is: nullability, + isReadOnly: isReadOnly, + ofType: .model(type: type), + association: .hasOne( + associatedWith: associatedKeys.first, + associatedFields: associatedKeys, + targetNames: targetNames + ) + ) } - public static func belongsTo(_ key: CodingKey, - is nullability: ModelFieldNullability = .required, - isReadOnly: Bool = false, - ofType type: Model.Type, - associatedWith associatedKey: CodingKey? = nil, - targetName: String? = nil) -> ModelFieldDefinition { - return .field(key, - is: nullability, - isReadOnly: isReadOnly, - ofType: .model(type: type), - association: .belongsTo(associatedWith: associatedKey, targetNames: targetName.map { [$0] } ?? [])) + public static func belongsTo( + _ key: CodingKey, + is nullability: ModelFieldNullability = .required, + isReadOnly: Bool = false, + ofType type: Model.Type, + associatedWith associatedKey: CodingKey? = nil, + targetName: String? = nil + ) -> ModelFieldDefinition { + return .field( + key, + is: nullability, + isReadOnly: isReadOnly, + ofType: .model(type: type), + association: .belongsTo(associatedWith: associatedKey, targetNames: targetName.map { [$0] } ?? []) + ) } - public static func belongsTo(_ key: CodingKey, - is nullability: ModelFieldNullability = .required, - isReadOnly: Bool = false, - ofType type: Model.Type, - associatedWith associatedKey: CodingKey? = nil, - targetNames: [String]) -> ModelFieldDefinition { - return .field(key, - is: nullability, - isReadOnly: isReadOnly, - ofType: .model(type: type), - association: .belongsTo(associatedWith: associatedKey, targetNames: targetNames)) + public static func belongsTo( + _ key: CodingKey, + is nullability: ModelFieldNullability = .required, + isReadOnly: Bool = false, + ofType type: Model.Type, + associatedWith associatedKey: CodingKey? = nil, + targetNames: [String] + ) -> ModelFieldDefinition { + return .field( + key, + is: nullability, + isReadOnly: isReadOnly, + ofType: .model(type: type), + association: .belongsTo(associatedWith: associatedKey, targetNames: targetNames) + ) } public var modelField: ModelField { - guard case let .field(name, - type, - nullability, - isReadOnly, - association, - attributes, - authRules) = self else { + guard case let .field( + name, + type, + nullability, + isReadOnly, + association, + attributes, + authRules + ) = self + else { return Fatal.preconditionFailure("Unexpected enum value found: \(String(describing: self))") } - return ModelField(name: name, - type: type, - isRequired: nullability.isRequired, - isReadOnly: isReadOnly, - isArray: type.isArray, - attributes: attributes, - association: association, - authRules: authRules) + return ModelField( + name: name, + type: type, + isRequired: nullability.isRequired, + isReadOnly: isReadOnly, + isArray: type.isArray, + attributes: attributes, + association: association, + authRules: authRules + ) } } diff --git a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema.swift b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema.swift index ac1045e523..f2ae1142fb 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema.swift @@ -24,7 +24,7 @@ public enum ModelAttribute: Equatable { /// Convenience factory method to initialize a `.primaryKey` attribute by /// using the model coding keys public static func primaryKey(fields: [CodingKey]) -> ModelAttribute { - return .primaryKey(fields: fields.map { $0.stringValue }) + return .primaryKey(fields: fields.map(\.stringValue)) } } @@ -53,14 +53,16 @@ public struct ModelField { return attributes.contains { $0 == .primaryKey } } - public init(name: String, - type: ModelFieldType, - isRequired: Bool = false, - isReadOnly: Bool = false, - isArray: Bool = false, - attributes: [ModelFieldAttribute] = [], - association: ModelAssociation? = nil, - authRules: AuthRules = []) { + public init( + name: String, + type: ModelFieldType, + isRequired: Bool = false, + isReadOnly: Bool = false, + isArray: Bool = false, + attributes: [ModelFieldAttribute] = [], + association: ModelAssociation? = nil, + authRules: AuthRules = [] + ) { self.name = name self.type = type self.isRequired = isRequired @@ -106,14 +108,16 @@ public struct ModelSchema { return primaryKey } - public init(name: String, - pluralName: String? = nil, - listPluralName: String? = nil, - syncPluralName: String? = nil, - authRules: AuthRules = [], - attributes: [ModelAttribute] = [], - fields: ModelFields = [:], - primaryKeyFieldKeys: [ModelFieldName] = []) { + public init( + name: String, + pluralName: String? = nil, + listPluralName: String? = nil, + syncPluralName: String? = nil, + authRules: AuthRules = [], + attributes: [ModelAttribute] = [], + fields: ModelFields = [:], + primaryKeyFieldKeys: [ModelFieldName] = [] + ) { self.name = name self.pluralName = pluralName self.listPluralName = listPluralName @@ -122,9 +126,11 @@ public struct ModelSchema { self.attributes = attributes self.fields = fields self.indexes = attributes.indexes - self._primaryKey = ModelPrimaryKey(allFields: fields, - attributes: attributes, - primaryKeyFieldKeys: primaryKeyFieldKeys) + self._primaryKey = ModelPrimaryKey( + allFields: fields, + attributes: attributes, + primaryKeyFieldKeys: primaryKeyFieldKeys + ) let indexOfPrimaryKeyField = _primaryKey?.indexOfField ?? { (_: String) in nil } self.sortedFields = fields.sortedFields(indexOfPrimaryKeyField: indexOfPrimaryKeyField) @@ -150,7 +156,7 @@ extension ModelAttribute { /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used /// directly by host applications. The behavior of this may change without warning. -extension Array where Element == ModelAttribute { +extension [ModelAttribute] { var indexes: [ModelAttribute] { filter { switch $0 { @@ -179,7 +185,7 @@ public extension ModelSchema { // MARK: - Dictionary + ModelField -extension Dictionary where Key == String, Value == ModelField { +extension [String: ModelField] { /// Returns an array of the values sorted by some pre-defined rules: /// diff --git a/Amplify/Categories/DataStore/Model/Lazy/ArrayLiteralListProvider.swift b/Amplify/Categories/DataStore/Model/Lazy/ArrayLiteralListProvider.swift index 7c8e128853..8fc5fbf235 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/ArrayLiteralListProvider.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/ArrayLiteralListProvider.swift @@ -35,15 +35,19 @@ public struct ArrayLiteralListProvider: ModelListProvider { } public func getNextPage(completion: @escaping (Result, CoreError>) -> Void) { - completion(.failure(CoreError.clientValidation("No pagination on an array literal", - "Don't call this method", - nil))) + completion(.failure(CoreError.clientValidation( + "No pagination on an array literal", + "Don't call this method", + nil + ))) } public func getNextPage() async throws -> List { - throw CoreError.clientValidation("No pagination on an array literal", - "Don't call this method", - nil) + throw CoreError.clientValidation( + "No pagination on an array literal", + "Don't call this method", + nil + ) } public func encode(to encoder: Encoder) throws { diff --git a/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift b/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift index 343b059225..33e51c990a 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation /// A Codable struct to hold key value pairs representing the identifier's field name and value. /// Useful for maintaining order for key-value pairs when used as an Array type. @@ -20,8 +20,8 @@ public struct LazyReferenceIdentifier: Codable { } } -extension Array where Element == LazyReferenceIdentifier { - public var stringValue: String { +public extension [LazyReferenceIdentifier] { + var stringValue: String { var fields = [(String, Persistable)]() for id in self { fields.append((id.name, id.value)) @@ -88,7 +88,7 @@ public class LazyReference: Codable, _LazyReferenceValue { // MARK: - Codable implementation /// Decodable implementation is delegated to the ModelProviders. - required convenience public init(from decoder: Decoder) throws { + public required convenience init(from decoder: Decoder) throws { for modelDecoder in ModelProviderRegistry.decoders.get() { if let modelProvider = modelDecoder.decode(modelType: ModelType.self, decoder: decoder) { self.init(modelProvider: modelProvider) @@ -129,7 +129,7 @@ public class LazyReference: Codable, _LazyReferenceValue { switch loadedState { case .notLoaded: let element = try await modelProvider.load() - self.loadedState = .loaded(element) + loadedState = .loaded(element) return element case .loaded(let element): return element @@ -148,10 +148,10 @@ public class LazyReference: Codable, _LazyReferenceValue { guard let element = try await modelProvider.load() else { throw CoreError.clientValidation("Data is required but underlying data source successfully loaded no data. ", "") } - self.loadedState = .loaded(element) + loadedState = .loaded(element) return element case .loaded(let element): - guard let element = element else { + guard let element else { throw CoreError.clientValidation("Data is required but containing LazyReference is loaded with no data.", "") } return element diff --git a/Amplify/Categories/DataStore/Model/Lazy/List+Combine.swift b/Amplify/Categories/DataStore/Model/Lazy/List+Combine.swift index 271608fa2f..df6701cdff 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/List+Combine.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/List+Combine.swift @@ -8,9 +8,9 @@ #if canImport(Combine) import Combine -extension List { +public extension List { - public typealias LazyListPublisher = AnyPublisher<[Element], DataStoreError> + typealias LazyListPublisher = AnyPublisher<[Element], DataStoreError> } #endif diff --git a/Amplify/Categories/DataStore/Model/Lazy/List+LazyLoad.swift b/Amplify/Categories/DataStore/Model/Lazy/List+LazyLoad.swift index 71b833c976..8e40946bc4 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/List+LazyLoad.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/List+LazyLoad.swift @@ -10,7 +10,7 @@ import Foundation /// This extension adds lazy load logic to the `List`. Lazy loading means /// the contents of a list that represents an association between two models will only be /// loaded when it's needed. -extension List { +public extension List { // MARK: - Asynchronous API @@ -26,12 +26,12 @@ extension List { /// /// If you have directly created this list object (for example, by calling `List(elements:)`) then the collection /// has already been initialized and calling this method will have no effect. - public func fetch() async throws { + func fetch() async throws { guard case .notLoaded = loadedState else { return } do { - self.elements = try await listProvider.load() + elements = try await listProvider.load() } catch { throw error } diff --git a/Amplify/Categories/DataStore/Model/Lazy/List+Model.swift b/Amplify/Categories/DataStore/Model/Lazy/List+Model.swift index 283cc53ff7..af9965888f 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/List+Model.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/List+Model.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation /// `List` is a custom `Collection` that is capable of loading records from a data source. This is especially /// useful when dealing with Model associations that need to be lazy loaded. Lazy loading is performed when you access @@ -89,7 +89,7 @@ public class List: Collection, Codable, ExpressibleByArrayLite // MARK: - ExpressibleByArrayLiteral - required convenience public init(arrayLiteral elements: Element...) { + public required convenience init(arrayLiteral elements: Element...) { self.init(elements: elements) } @@ -150,7 +150,7 @@ public class List: Collection, Codable, ExpressibleByArrayLite /// implementations of a `ModelListProvider` for `List`. The decoders should be added to the registry by the /// plugin as part of its configuration steps. By delegating responsibility to the `ModelListDecoder`, it is up to /// the plugin to successfully return an instance of `ModelListProvider`. - required convenience public init(from decoder: Decoder) throws { + public required convenience init(from decoder: Decoder) throws { for listDecoder in ModelListDecoderRegistry.listDecoders.get() { if let listProvider = listDecoder.decode(modelType: ModelType.self, decoder: decoder) { self.init(listProvider: listProvider) diff --git a/Amplify/Categories/DataStore/Model/Lazy/List+Pagination.swift b/Amplify/Categories/DataStore/Model/Lazy/List+Pagination.swift index 28d6fb2d02..da7c312bf1 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/List+Pagination.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/List+Pagination.swift @@ -7,12 +7,12 @@ import Foundation -extension List { +public extension List { /// Check if there is subsequent data to retrieve. If true, the next page can be retrieved using /// `getNextPage(completion:)`. Calling `hasNextPage()` will load the underlying elements from the data source if not yet /// loaded before. - public func hasNextPage() -> Bool { + func hasNextPage() -> Bool { switch loadedState { case .loaded: return listProvider.hasNextPage() @@ -26,7 +26,7 @@ extension List { /// Retrieve the next page as a new in-memory List object. Calling `getNextPage(completion:)` will load the /// underlying elements of the receiver from the data source if not yet loaded before - public func getNextPage() async throws -> List { + func getNextPage() async throws -> List { switch loadedState { case .loaded: return try await listProvider.getNextPage() diff --git a/Amplify/Categories/DataStore/Model/Model+ModelName.swift b/Amplify/Categories/DataStore/Model/Model+ModelName.swift index ac6b893d12..df69c900f1 100644 --- a/Amplify/Categories/DataStore/Model/Model+ModelName.swift +++ b/Amplify/Categories/DataStore/Model/Model+ModelName.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Model { +public extension Model { - public static var modelName: String { + static var modelName: String { return String(describing: self) } - public var modelName: String { + var modelName: String { return type(of: self).modelName } } diff --git a/Amplify/Categories/DataStore/Model/Model.swift b/Amplify/Categories/DataStore/Model/Model.swift index 85b6c1a822..102997c672 100644 --- a/Amplify/Categories/DataStore/Model/Model.swift +++ b/Amplify/Categories/DataStore/Model/Model.swift @@ -38,15 +38,15 @@ public protocol Model: Codable { var identifier: String { get } } -extension Model { - public var identifier: String { +public extension Model { + var identifier: String { guard let schema = ModelRegistry.modelSchema(from: modelName) else { preconditionFailure("Schema not found for \(modelName).") } return identifier(schema: schema).stringValue } - public func identifier(schema modelSchema: ModelSchema) -> ModelIdentifierProtocol { + func identifier(schema modelSchema: ModelSchema) -> ModelIdentifierProtocol { // resolve current instance identifier fields let fields: ModelIdentifierProtocol.Fields = modelSchema.primaryKey.fields.map { guard let fieldValue = self[$0.name] else { @@ -77,5 +77,5 @@ extension Model { /// The `rootPath` is set to `nil` by default. Specific models should override this /// behavior and provide the proper path reference when available. - public static var rootPath: PropertyContainerPath? { nil } + static var rootPath: PropertyContainerPath? { nil } } diff --git a/Amplify/Categories/DataStore/Model/ModelIdentifiable.swift b/Amplify/Categories/DataStore/Model/ModelIdentifiable.swift index 141a7ff03d..9946e0878a 100644 --- a/Amplify/Categories/DataStore/Model/ModelIdentifiable.swift +++ b/Amplify/Categories/DataStore/Model/ModelIdentifiable.swift @@ -62,11 +62,11 @@ public extension ModelIdentifierProtocol { } var keys: [String] { - fields.map { $0.name } + fields.map(\.name) } var values: [Persistable] { - fields.map { $0.value } + fields.map(\.value) } var predicate: QueryPredicate { @@ -97,11 +97,11 @@ public extension ModelIdentifier where F == ModelIdentifierFormat.Custom { /// Convenience type for a ModelIdentifier with a `ModelIdentifierFormat.Default` format public typealias DefaultModelIdentifier = ModelIdentifier -extension DefaultModelIdentifier { +public extension DefaultModelIdentifier { /// Factory to instantiate a `DefaultModelIdentifier`. /// - Parameter id: model id value /// - Returns: an instance of `ModelIdentifier` for the given model type - public static func makeDefault(id: String) -> ModelIdentifier { + static func makeDefault(id: String) -> ModelIdentifier { ModelIdentifier(fields: [ (name: ModelIdentifierFormat.Default.name, value: id) ]) @@ -110,7 +110,7 @@ extension DefaultModelIdentifier { /// Convenience factory to instantiate a `DefaultModelIdentifier` from a given model /// - Parameter model: model /// - Returns: an instance of `ModelIdentifier` for the given model type - public static func makeDefault(fromModel model: M) -> ModelIdentifier { + static func makeDefault(fromModel model: M) -> ModelIdentifier { guard let idValue = model[ModelIdentifierFormat.Default.name] as? String else { fatalError("Couldn't find default identifier for model \(model)") } @@ -121,19 +121,18 @@ extension DefaultModelIdentifier { // MARK: - Persistable + stringValue private extension Persistable { var stringValue: String { - var value: String - switch self { + var value: String = switch self { case let self as Temporal.Date: - value = self.iso8601String + self.iso8601String case let self as Temporal.DateTime: - value = self.iso8601String + self.iso8601String case let self as Temporal.Time: - value = self.iso8601String + self.iso8601String default: - value = "\(self)" + "\(self)" } return value } diff --git a/Amplify/Categories/DataStore/Model/PropertyPath.swift b/Amplify/Categories/DataStore/Model/PropertyPath.swift index 212430f56d..ad67734a66 100644 --- a/Amplify/Categories/DataStore/Model/PropertyPath.swift +++ b/Amplify/Categories/DataStore/Model/PropertyPath.swift @@ -34,7 +34,7 @@ public protocol PropertyPath { /// - SeeAlso: `ModelPath` public protocol PropertyContainerPath: PropertyPath { - /// + /// func getKeyPath() -> String /// Must return a reference to the type containing the properties @@ -42,9 +42,9 @@ public protocol PropertyContainerPath: PropertyPath { } -extension PropertyContainerPath { +public extension PropertyContainerPath { - public func getKeyPath() -> String { + func getKeyPath() -> String { var metadata = getMetadata() var path = [String]() while let parent = metadata.parent { diff --git a/Amplify/Categories/DataStore/Model/Temporal/DataStoreError+Temporal.swift b/Amplify/Categories/DataStore/Model/Temporal/DataStoreError+Temporal.swift index 4cbec5437c..ef2ba29487 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/DataStoreError+Temporal.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/DataStoreError+Temporal.swift @@ -7,9 +7,9 @@ import Foundation -extension DataStoreError { +public extension DataStoreError { - public static func invalidDateFormat(_ value: String) -> DataStoreError { + static func invalidDateFormat(_ value: String) -> DataStoreError { return DataStoreError.decodingError( """ Could not parse \(value) as a Date using the ISO8601 format. @@ -17,7 +17,8 @@ extension DataStoreError { """ Check if the format used to parse the date is the correct one. Check `TemporalFormat` for all the options. - """) + """ + ) } } diff --git a/Amplify/Categories/DataStore/Model/Temporal/Date+Operation.swift b/Amplify/Categories/DataStore/Model/Temporal/Date+Operation.swift index 5bf0f19b4f..637b5b5e96 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/Date+Operation.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/Date+Operation.swift @@ -92,7 +92,7 @@ public protocol DateUnitOperable { static func - (left: Self, right: DateUnit) -> Self } -extension TemporalSpec where Self: DateUnitOperable { +public extension TemporalSpec where Self: DateUnitOperable { /// Add a `DateUnit` to a `Temporal.Date` or `Temporal.DateTime` /// @@ -102,7 +102,7 @@ extension TemporalSpec where Self: DateUnitOperable { /// - left: `Temporal.Date` or `Temporal.DateTime` /// - right: `DateUnit` to add to `left` /// - Returns: A new `Temporal.Date` or `Temporal.DateTime` the `DateUnit` was added to. - public static func + (left: Self, right: DateUnit) -> Self { + static func + (left: Self, right: DateUnit) -> Self { return left.add(value: right.value, to: right.calendarComponent) } @@ -114,7 +114,7 @@ extension TemporalSpec where Self: DateUnitOperable { /// - left: `Temporal.Date` or `Temporal.DateTime` /// - right: `DateUnit` to subtract from `left` /// - Returns: A new `Temporal.Date` or `Temporal.DateTime` the `DateUnit` was subtracted from. - public static func - (left: Self, right: DateUnit) -> Self { + static func - (left: Self, right: DateUnit) -> Self { return left.add(value: -right.value, to: right.calendarComponent) } } diff --git a/Amplify/Categories/DataStore/Model/Temporal/Date.swift b/Amplify/Categories/DataStore/Model/Temporal/Date.swift index 9b27c313e0..0c955fee9e 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/Date.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/Date.swift @@ -7,7 +7,7 @@ import Foundation -extension Temporal { +public extension Temporal { /// `Temporal.Date` represents a `Date` with specific allowable formats. /// @@ -17,7 +17,7 @@ extension Temporal { /// * `.full` => `yyyy-MM-ddZZZZZ` /// /// - Note: `.medium`, `.long`, and `.full` are the same date format. - public struct Date: TemporalSpec { + struct Date: TemporalSpec { // Inherits documentation from `TemporalSpec` public let foundationDate: Foundation.Date diff --git a/Amplify/Categories/DataStore/Model/Temporal/DateTime.swift b/Amplify/Categories/DataStore/Model/Temporal/DateTime.swift index 95c65e5f6e..b694f094b3 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/DateTime.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/DateTime.swift @@ -7,14 +7,14 @@ import Foundation -extension Temporal { +public extension Temporal { /// `Temporal.DateTime` represents a `DateTime` with specific allowable formats. /// /// * `.short` => `yyyy-MM-dd'T'HH:mm` /// * `.medium` => `yyyy-MM-dd'T'HH:mm:ss` /// * `.long` => `yyyy-MM-dd'T'HH:mm:ssZZZZZ` /// * `.full` => `yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ` - public struct DateTime: TemporalSpec { + struct DateTime: TemporalSpec { // Inherits documentation from `TemporalSpec` public let foundationDate: Foundation.Date @@ -42,7 +42,7 @@ extension Temporal { self.timeZone = timeZone - foundationDate = calendar + self.foundationDate = calendar .date(from: components) ?? date } diff --git a/Amplify/Categories/DataStore/Model/Temporal/SpecBasedDateConverting.swift b/Amplify/Categories/DataStore/Model/Temporal/SpecBasedDateConverting.swift index 5aaa135d8d..26612ab195 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/SpecBasedDateConverting.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/SpecBasedDateConverting.swift @@ -10,12 +10,12 @@ import Foundation /// Internal generic method to reduce code reuse in the `init`s of `TemporalSpec` /// conforming types @usableFromInline -internal struct SpecBasedDateConverting { +struct SpecBasedDateConverting { @usableFromInline - internal typealias DateConverter = (_ string: String, _ format: TemporalFormat?) throws -> (Date, TimeZone) + typealias DateConverter = (_ string: String, _ format: TemporalFormat?) throws -> (Date, TimeZone) @usableFromInline - internal let convert: DateConverter + let convert: DateConverter @inlinable @inline(never) @@ -25,13 +25,13 @@ internal struct SpecBasedDateConverting { @inlinable @inline(never) - internal static func `default`( + static func `default`( iso8601String: String, format: TemporalFormat? = nil ) throws -> (Date, TimeZone) { let date: Foundation.Date - let tz: TimeZone = TimeZone(iso8601DateString: iso8601String) ?? .utc - if let format = format { + let tz = TimeZone(iso8601DateString: iso8601String) ?? .utc + if let format { date = try Temporal.date( from: iso8601String, with: [format(for: Spec.self)] diff --git a/Amplify/Categories/DataStore/Model/Temporal/Temporal+Cache.swift b/Amplify/Categories/DataStore/Model/Temporal/Temporal+Cache.swift index cb3b7b051f..05ba4b6b28 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/Temporal+Cache.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/Temporal+Cache.swift @@ -19,7 +19,7 @@ extension Temporal { /// /// `identifier` is `.iso8601` /// `timeZome` is `.utc` a.k.a. `TimeZone(abbreviation: "UTC")` - internal static let iso8601Calendar: Calendar = { + static let iso8601Calendar: Calendar = { var calendar = Calendar(identifier: .iso8601) calendar.timeZone = .utc return calendar @@ -37,7 +37,7 @@ extension Temporal { /// - format: The `DateFormatter().dateFormat` /// - timeZone: The `DateFormatter().timeZone` /// - Returns: A `DateFormatter` - internal static func formatter( + static func formatter( for format: String, in timeZone: TimeZone ) -> DateFormatter { @@ -111,7 +111,7 @@ extension Temporal { /// Default is `.utc` a.k.a. `TimeZone(abbreviation: "UTC")` /// - Returns: A `Foundation.Date` if conversion was successful. /// - Throws: `DataStoreError.invalidDateFormat(_:)` if conversion was unsuccessful. - internal static func date( + static func date( from string: String, with formats: [String], in timeZone: TimeZone = .utc @@ -134,7 +134,7 @@ extension Temporal { /// - timeZone: The `TimeZone` used by the `DateFormatter` when converted. /// Default is `.utc` a.k.a. `TimeZone(abbreviation: "UTC")` /// - Returns: The `String` representation of the `date` formatted according to the `format` argument.. - internal static func string( + static func string( from date: Foundation.Date, with format: String, in timeZone: TimeZone = .utc diff --git a/Amplify/Categories/DataStore/Model/Temporal/Temporal+Codable.swift b/Amplify/Categories/DataStore/Model/Temporal/Temporal+Codable.swift index 024b534d2d..15db66b141 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/Temporal+Codable.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/Temporal+Codable.swift @@ -7,14 +7,14 @@ import Foundation -extension TemporalSpec where Self: Codable { - public init(from decoder: Decoder) throws { +public extension TemporalSpec where Self: Codable { + init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let value = try container.decode(String.self) try self.init(iso8601String: value) } - public func encode(to encoder: Encoder) throws { + func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(iso8601String) } diff --git a/Amplify/Categories/DataStore/Model/Temporal/Temporal+Comparable.swift b/Amplify/Categories/DataStore/Model/Temporal/Temporal+Comparable.swift index bc9e9e47e0..a577817edf 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/Temporal+Comparable.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/Temporal+Comparable.swift @@ -12,14 +12,14 @@ import Foundation /// takes care of deriving the other operations from those two. /// /// - Note: the implementation simply delegates to the `iso8601String` formatted date. -extension TemporalSpec where Self: Comparable { +public extension TemporalSpec where Self: Comparable { - public static func == (lhs: Self, rhs: Self) -> Bool { + static func == (lhs: Self, rhs: Self) -> Bool { return lhs.iso8601FormattedString(format: .full, timeZone: .utc) == rhs.iso8601FormattedString(format: .full, timeZone: .utc) } - public static func < (lhs: Self, rhs: Self) -> Bool { + static func < (lhs: Self, rhs: Self) -> Bool { return lhs.iso8601FormattedString(format: .full, timeZone: .utc) < rhs.iso8601FormattedString(format: .full, timeZone: .utc) } diff --git a/Amplify/Categories/DataStore/Model/Temporal/Temporal.swift b/Amplify/Categories/DataStore/Model/Temporal/Temporal.swift index e92f4f9435..ad6256d21c 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/Temporal.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/Temporal.swift @@ -72,7 +72,7 @@ public protocol TemporalSpec { func iso8601FormattedString(format: TemporalFormat, timeZone: TimeZone) -> String } -extension TemporalSpec { +public extension TemporalSpec { /// Create an iso8601 `String` with the desired format option for this spec. /// - Parameters: @@ -80,7 +80,7 @@ extension TemporalSpec { /// - timeZone: `TimeZone` that the `DateFormatter` will use in conversion. /// Default is `.utc` a.k.a. `TimeZone(abbreviation: "UTC")` /// - Returns: A `String` formatted according to the `format` and `timeZone` arguments. - public func iso8601FormattedString( + func iso8601FormattedString( format: TemporalFormat, timeZone: TimeZone = .utc ) -> String { @@ -93,12 +93,12 @@ extension TemporalSpec { /// The ISO8601 representation of the scalar using `.full` as the format and `.utc` as `TimeZone`. /// - SeeAlso: `iso8601FormattedString(format:timeZone:)` - public var iso8601String: String { + var iso8601String: String { iso8601FormattedString(format: .full, timeZone: timeZone ?? .utc) } @inlinable - public init(iso8601String: String, format: TemporalFormat) throws { + init(iso8601String: String, format: TemporalFormat) throws { let (date, tz) = try SpecBasedDateConverting() .convert(iso8601String, format) @@ -106,7 +106,7 @@ extension TemporalSpec { } @inlinable - public init( + init( iso8601String: String ) throws { let (date, tz) = try SpecBasedDateConverting() @@ -116,9 +116,9 @@ extension TemporalSpec { } } -extension TimeZone { +public extension TimeZone { /// Utility UTC ("Coordinated Universal Time") TimeZone instance. - public static var utc: TimeZone { + static var utc: TimeZone { TimeZone(abbreviation: "UTC")! } } diff --git a/Amplify/Categories/DataStore/Model/Temporal/TemporalFormat.swift b/Amplify/Categories/DataStore/Model/Temporal/TemporalFormat.swift index d9cc9ca6f7..d593ea216b 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/TemporalFormat.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/TemporalFormat.swift @@ -64,35 +64,34 @@ public struct TemporalFormat { ] private func keyPath(for type: TemporalSpec.Type) -> KeyPath { - let keyPath: KeyPath - if type == Temporal.Time.self { - keyPath = \TemporalFormat.timeFormat + let keyPath: KeyPath = if type == Temporal.Time.self { + \TemporalFormat.timeFormat } else if type == Temporal.Date.self { - keyPath = \TemporalFormat.dateFormat + \TemporalFormat.dateFormat } else { - keyPath = \TemporalFormat.dateTimeFormat + \TemporalFormat.dateTimeFormat } return keyPath } @usableFromInline - internal static func sortedFormats(for type: TemporalSpec.Type) -> [String] { + static func sortedFormats(for type: TemporalSpec.Type) -> [String] { let formats: [String] // If the TemporalSpec is `Date`, let's only return `.full` and `.short` // because `.medium`, `.long`, and `.full` are all the same format. // If the formats ever differ, this needs to be updated. - if type == Temporal.Date.self { - formats = [TemporalFormat.full, .short] + = if type == Temporal.Date.self { + [TemporalFormat.full, .short] .map { $0(for: type) } } else { - formats = Self.allCases + Self.allCases .map { $0(for: type) } } return formats } @usableFromInline - internal func callAsFunction(for type: TemporalSpec.Type) -> String { + func callAsFunction(for type: TemporalSpec.Type) -> String { self[keyPath: keyPath(for: type)] } } diff --git a/Amplify/Categories/DataStore/Model/Temporal/Time+Operation.swift b/Amplify/Categories/DataStore/Model/Temporal/Time+Operation.swift index 83166eb39a..803345bf15 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/Time+Operation.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/Time+Operation.swift @@ -109,14 +109,14 @@ public protocol TimeUnitOperable { static func - (left: Self, right: TimeUnit) -> Self } -extension TemporalSpec where Self: TimeUnitOperable { +public extension TemporalSpec where Self: TimeUnitOperable { /// Add a `TimeUnit` to a `Temporal.Time` or `Temporal.DateTime` /// - Parameters: /// - left: `Temporal.Time` or `Temporal.DateTime` /// - right: `TimeUnit` to add to `left` /// - Returns: A new `Temporal.Time` or `Temporal.DateTime` the `TimeUnit` was added to. - public static func + (left: Self, right: TimeUnit) -> Self { + static func + (left: Self, right: TimeUnit) -> Self { return left.add(value: right.value, to: right.calendarComponent) } @@ -125,7 +125,7 @@ extension TemporalSpec where Self: TimeUnitOperable { /// - left: `Temporal.Time` or `Temporal.DateTime` /// - right: `TimeUnit` to subtract from `left` /// - Returns: A new `Temporal.Time` or `Temporal.DateTime` the `TimeUnit` was subtracted from. - public static func - (left: Self, right: TimeUnit) -> Self { + static func - (left: Self, right: TimeUnit) -> Self { return left.add(value: -right.value, to: right.calendarComponent) } } diff --git a/Amplify/Categories/DataStore/Model/Temporal/Time.swift b/Amplify/Categories/DataStore/Model/Temporal/Time.swift index d4185e874d..b263b715a2 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/Time.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/Time.swift @@ -7,14 +7,14 @@ import Foundation -extension Temporal { +public extension Temporal { /// `Temporal.Time` represents a `Time` with specific allowable formats. /// /// * `.short` => `HH:mm` /// * `.medium` => `HH:mm:ss` /// * `.long` => `HH:mm:ss.SSS` /// * `.full` => `HH:mm:ss.SSSZZZZZ` - public struct Time: TemporalSpec { + struct Time: TemporalSpec { // Inherits documentation from `TemporalSpec` public let foundationDate: Foundation.Date diff --git a/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift b/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift index efbbbfb673..530cd27063 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift @@ -10,7 +10,7 @@ import Foundation extension TimeZone { @usableFromInline - internal init?(iso8601DateString: String) { + init?(iso8601DateString: String) { switch ISO8601TimeZonePart.from(iso8601DateString: iso8601DateString) { case .some(.utc): self.init(abbreviation: "UTC") diff --git a/Amplify/Categories/DataStore/Query/ModelKey.swift b/Amplify/Categories/DataStore/Query/ModelKey.swift index 860cb17061..c2f3a32e66 100644 --- a/Amplify/Categories/DataStore/Query/ModelKey.swift +++ b/Amplify/Categories/DataStore/Query/ModelKey.swift @@ -34,111 +34,111 @@ import Foundation /// ``` public protocol ModelKey: CodingKey, CaseIterable, QueryFieldOperation {} -extension CodingKey where Self: ModelKey { +public extension CodingKey where Self: ModelKey { // MARK: - attributeExists - public func attributeExists(_ value: Bool) -> QueryPredicateOperation { + func attributeExists(_ value: Bool) -> QueryPredicateOperation { return field(stringValue).attributeExists(value) } // MARK: - beginsWith - public func beginsWith(_ value: String) -> QueryPredicateOperation { + func beginsWith(_ value: String) -> QueryPredicateOperation { return field(stringValue).beginsWith(value) } // MARK: - between - public func between(start: Persistable, end: Persistable) -> QueryPredicateOperation { + func between(start: Persistable, end: Persistable) -> QueryPredicateOperation { return field(stringValue).between(start: start, end: end) } // MARK: - contains - public func contains(_ value: String) -> QueryPredicateOperation { + func contains(_ value: String) -> QueryPredicateOperation { return field(stringValue).contains(value) } - public static func ~= (key: Self, value: String) -> QueryPredicateOperation { + static func ~= (key: Self, value: String) -> QueryPredicateOperation { return key.contains(value) } // MARK: - not contains - public func notContains(_ value: String) -> QueryPredicateOperation { + func notContains(_ value: String) -> QueryPredicateOperation { return field(stringValue).notContains(value) } // MARK: - eq - public func eq(_ value: Persistable?) -> QueryPredicateOperation { + func eq(_ value: Persistable?) -> QueryPredicateOperation { return field(stringValue).eq(value) } - public func eq(_ value: EnumPersistable) -> QueryPredicateOperation { + func eq(_ value: EnumPersistable) -> QueryPredicateOperation { return field(stringValue).eq(value) } - public static func == (key: Self, value: Persistable?) -> QueryPredicateOperation { + static func == (key: Self, value: Persistable?) -> QueryPredicateOperation { return key.eq(value) } - public static func == (key: Self, value: EnumPersistable) -> QueryPredicateOperation { + static func == (key: Self, value: EnumPersistable) -> QueryPredicateOperation { return key.eq(value) } // MARK: - ge - public func ge(_ value: Persistable) -> QueryPredicateOperation { + func ge(_ value: Persistable) -> QueryPredicateOperation { return field(stringValue).ge(value) } - public static func >= (key: Self, value: Persistable) -> QueryPredicateOperation { + static func >= (key: Self, value: Persistable) -> QueryPredicateOperation { return key.ge(value) } // MARK: - gt - public func gt(_ value: Persistable) -> QueryPredicateOperation { + func gt(_ value: Persistable) -> QueryPredicateOperation { return field(stringValue).gt(value) } - public static func > (key: Self, value: Persistable) -> QueryPredicateOperation { + static func > (key: Self, value: Persistable) -> QueryPredicateOperation { return key.gt(value) } // MARK: - le - public func le(_ value: Persistable) -> QueryPredicateOperation { + func le(_ value: Persistable) -> QueryPredicateOperation { return field(stringValue).le(value) } - public static func <= (key: Self, value: Persistable) -> QueryPredicateOperation { + static func <= (key: Self, value: Persistable) -> QueryPredicateOperation { return key.le(value) } // MARK: - lt - public func lt(_ value: Persistable) -> QueryPredicateOperation { + func lt(_ value: Persistable) -> QueryPredicateOperation { return field(stringValue).lt(value) } - public static func < (key: Self, value: Persistable) -> QueryPredicateOperation { + static func < (key: Self, value: Persistable) -> QueryPredicateOperation { return key.lt(value) } // MARK: - ne - public func ne(_ value: Persistable?) -> QueryPredicateOperation { + func ne(_ value: Persistable?) -> QueryPredicateOperation { return field(stringValue).ne(value) } - public func ne(_ value: EnumPersistable) -> QueryPredicateOperation { + func ne(_ value: EnumPersistable) -> QueryPredicateOperation { return field(stringValue).ne(value) } - public static func != (key: Self, value: Persistable?) -> QueryPredicateOperation { + static func != (key: Self, value: Persistable?) -> QueryPredicateOperation { return key.ne(value) } - public static func != (key: Self, value: EnumPersistable) -> QueryPredicateOperation { + static func != (key: Self, value: EnumPersistable) -> QueryPredicateOperation { return key.ne(value) } diff --git a/Amplify/Categories/DataStore/Query/QueryOperator.swift b/Amplify/Categories/DataStore/Query/QueryOperator.swift index e4897e5f0d..ce32d84f65 100644 --- a/Amplify/Categories/DataStore/Query/QueryOperator.swift +++ b/Amplify/Categories/DataStore/Query/QueryOperator.swift @@ -72,12 +72,12 @@ public enum QueryOperator: Encodable { switch self { case .notEqual(let value): try container.encode("notEqual", forKey: .type) - if let value = value { + if let value { try container.encode(value, forKey: .value) } case .equals(let value): try container.encode("equals", forKey: .type) - if let value = value { + if let value { try container.encode(value, forKey: .value) } case .lessOrEqual(let value): diff --git a/Amplify/Categories/DataStore/Query/QueryPaginationInput.swift b/Amplify/Categories/DataStore/Query/QueryPaginationInput.swift index 75b46ffbac..dd665aa475 100644 --- a/Amplify/Categories/DataStore/Query/QueryPaginationInput.swift +++ b/Amplify/Categories/DataStore/Query/QueryPaginationInput.swift @@ -21,7 +21,7 @@ public struct QueryPaginationInput { } -extension QueryPaginationInput { +public extension QueryPaginationInput { /// Creates a `QueryPaginationInput` in an expressive way, enabling a short /// and developer friendly access to an instance of `QueryPaginationInput`. @@ -30,18 +30,20 @@ extension QueryPaginationInput { /// - page: the page number (starting at 0) /// - limit: the page size (defaults to `QueryPaginationInput.defaultLimit`) /// - Returns: a new instance of `QueryPaginationInput` - public static func page(_ page: UInt, - limit: UInt = QueryPaginationInput.defaultLimit) -> QueryPaginationInput { + static func page( + _ page: UInt, + limit: UInt = QueryPaginationInput.defaultLimit + ) -> QueryPaginationInput { return QueryPaginationInput(page: page, limit: limit) } /// Utility that created a `QueryPaginationInput` with `page` 0 and `limit` 1 - public static var firstResult: QueryPaginationInput { + static var firstResult: QueryPaginationInput { .page(0, limit: 1) } /// Utility that created a `QueryPaginationInput` with `page` 0 and the default `limit` - public static var firstPage: QueryPaginationInput { + static var firstPage: QueryPaginationInput { .page(0) } diff --git a/Amplify/Categories/DataStore/Query/QueryPredicate.swift b/Amplify/Categories/DataStore/Query/QueryPredicate.swift index 222bd11c6e..2704f1b534 100644 --- a/Amplify/Categories/DataStore/Query/QueryPredicate.swift +++ b/Amplify/Categories/DataStore/Query/QueryPredicate.swift @@ -19,7 +19,7 @@ public enum QueryPredicateGroupType: String, Encodable { /// The `not` function is used to wrap a `QueryPredicate` in a `QueryPredicateGroup` of type `.not`. /// - Parameter predicate: the `QueryPredicate` (either operation or group) /// - Returns: `QueryPredicateGroup` of type `.not` -public func not(_ predicate: Predicate) -> QueryPredicateGroup { +public func not(_ predicate: some QueryPredicate) -> QueryPredicateGroup { return QueryPredicateGroup(type: .not, predicates: [predicate]) } @@ -37,8 +37,10 @@ public class QueryPredicateGroup: QueryPredicate, Encodable { public internal(set) var type: QueryPredicateGroupType public internal(set) var predicates: [QueryPredicate] - public init(type: QueryPredicateGroupType = .and, - predicates: [QueryPredicate] = []) { + public init( + type: QueryPredicateGroupType = .and, + predicates: [QueryPredicate] = [] + ) { self.type = type self.predicates = predicates } @@ -104,7 +106,7 @@ public class QueryPredicateGroup: QueryPredicate, Encodable { private let _encode: (Encoder) throws -> Void init(_ base: QueryPredicate) { - _encode = base.encode + self._encode = base.encode } func encode(to encoder: Encoder) throws { diff --git a/Amplify/Categories/DataStore/Subscribe/DataStoreCategory+Subscribe.swift b/Amplify/Categories/DataStore/Subscribe/DataStoreCategory+Subscribe.swift index ae669c73f9..2c59c95f17 100644 --- a/Amplify/Categories/DataStore/Subscribe/DataStoreCategory+Subscribe.swift +++ b/Amplify/Categories/DataStore/Subscribe/DataStoreCategory+Subscribe.swift @@ -8,13 +8,15 @@ import Combine extension DataStoreCategory: DataStoreSubscribeBehavior { - public func observe(_ modelType: M.Type) -> AmplifyAsyncThrowingSequence { + public func observe(_ modelType: (some Model).Type) -> AmplifyAsyncThrowingSequence { return plugin.observe(modelType) } - public func observeQuery(for modelType: M.Type, - where predicate: QueryPredicate? = nil, - sort sortInput: QuerySortInput? = nil) + public func observeQuery( + for modelType: M.Type, + where predicate: QueryPredicate? = nil, + sort sortInput: QuerySortInput? = nil + ) -> AmplifyAsyncThrowingSequence> { return plugin.observeQuery(for: modelType, where: predicate, sort: sortInput) } diff --git a/Amplify/Categories/DataStore/Subscribe/MutationEvent+Model.swift b/Amplify/Categories/DataStore/Subscribe/MutationEvent+Model.swift index 332376b096..8e5f29e973 100644 --- a/Amplify/Categories/DataStore/Subscribe/MutationEvent+Model.swift +++ b/Amplify/Categories/DataStore/Subscribe/MutationEvent+Model.swift @@ -5,35 +5,43 @@ // SPDX-License-Identifier: Apache-2.0 // -extension MutationEvent { +public extension MutationEvent { - public init(untypedModel model: Model, - mutationType: MutationType, - version: Int? = nil) throws { + init( + untypedModel model: Model, + mutationType: MutationType, + version: Int? = nil + ) throws { guard let modelType = ModelRegistry.modelType(from: model.modelName) else { let dataStoreError = DataStoreError.invalidModelName(model.modelName) throw dataStoreError } - try self.init(untypedModel: model, - modelName: modelType.schema.name, - mutationType: mutationType, - version: version) + try self.init( + untypedModel: model, + modelName: modelType.schema.name, + mutationType: mutationType, + version: version + ) } - public init(untypedModel model: Model, - modelName: ModelName, - mutationType: MutationType, - version: Int? = nil) throws { + init( + untypedModel model: Model, + modelName: ModelName, + mutationType: MutationType, + version: Int? = nil + ) throws { let json = try model.toJSON() guard let modelSchema = ModelRegistry.modelSchema(from: modelName) else { let dataStoreError = DataStoreError.invalidModelName(modelName) throw dataStoreError } - self.init(modelId: model.identifier(schema: modelSchema).stringValue, - modelName: modelName, - json: json, - mutationType: mutationType, - version: version) + self.init( + modelId: model.identifier(schema: modelSchema).stringValue, + modelName: modelName, + json: json, + mutationType: mutationType, + version: version + ) } } diff --git a/Amplify/Categories/DataStore/Subscribe/MutationEvent+Schema.swift b/Amplify/Categories/DataStore/Subscribe/MutationEvent+Schema.swift index 7f6f92af7a..88fa14a35f 100644 --- a/Amplify/Categories/DataStore/Subscribe/MutationEvent+Schema.swift +++ b/Amplify/Categories/DataStore/Subscribe/MutationEvent+Schema.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -extension MutationEvent { +public extension MutationEvent { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case modelId case modelName @@ -20,11 +20,11 @@ extension MutationEvent { case graphQLFilterJSON } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { definition in + static let schema = defineSchema { definition in let mutation = MutationEvent.keys definition.listPluralName = "MutationEvents" diff --git a/Amplify/Categories/DataStore/Subscribe/MutationEvent.swift b/Amplify/Categories/DataStore/Subscribe/MutationEvent.swift index 988ba31994..d9f82cba89 100644 --- a/Amplify/Categories/DataStore/Subscribe/MutationEvent.swift +++ b/Amplify/Categories/DataStore/Subscribe/MutationEvent.swift @@ -21,15 +21,17 @@ public struct MutationEvent: Model { public var inProcess: Bool public var graphQLFilterJSON: String? - public init(id: EventIdentifier = UUID().uuidString, - modelId: ModelId, - modelName: String, - json: String, - mutationType: MutationType, - createdAt: Temporal.DateTime = .now(), - version: Int? = nil, - inProcess: Bool = false, - graphQLFilterJSON: String? = nil) { + public init( + id: EventIdentifier = UUID().uuidString, + modelId: ModelId, + modelName: String, + json: String, + mutationType: MutationType, + createdAt: Temporal.DateTime = .now(), + version: Int? = nil, + inProcess: Bool = false, + graphQLFilterJSON: String? = nil + ) { self.id = id self.modelId = modelId self.modelName = modelName @@ -41,18 +43,22 @@ public struct MutationEvent: Model { self.graphQLFilterJSON = graphQLFilterJSON } - public init(model: M, - modelSchema: ModelSchema, - mutationType: MutationType, - version: Int? = nil, - graphQLFilterJSON: String? = nil) throws { + public init( + model: some Model, + modelSchema: ModelSchema, + mutationType: MutationType, + version: Int? = nil, + graphQLFilterJSON: String? = nil + ) throws { let json = try model.toJSON() - self.init(modelId: model.identifier(schema: modelSchema).stringValue, - modelName: modelSchema.name, - json: json, - mutationType: mutationType, - version: version, - graphQLFilterJSON: graphQLFilterJSON) + self.init( + modelId: model.identifier(schema: modelSchema).stringValue, + modelName: modelSchema.name, + json: json, + mutationType: mutationType, + version: version, + graphQLFilterJSON: graphQLFilterJSON + ) } @@ -60,15 +66,19 @@ public struct MutationEvent: Model { Initializing from a model without a ModelSchema is deprecated. Use init(model:modelSchema:mutationType:version:graphQLFilterJSON:) instead. """) - public init(model: M, - mutationType: MutationType, - version: Int? = nil, - graphQLFilterJSON: String? = nil) throws { - try self.init(model: model, - modelSchema: model.schema, - mutationType: mutationType, - version: version, - graphQLFilterJSON: graphQLFilterJSON) + public init( + model: M, + mutationType: MutationType, + version: Int? = nil, + graphQLFilterJSON: String? = nil + ) throws { + try self.init( + model: model, + modelSchema: model.schema, + mutationType: mutationType, + version: version, + graphQLFilterJSON: graphQLFilterJSON + ) } @@ -89,7 +99,8 @@ public struct MutationEvent: Model { it is a valid \(modelType.modelName) instance: \(json) - """) + """ + ) } return typedModel diff --git a/Amplify/Categories/Geo/GeoCategory+ClientBehavior.swift b/Amplify/Categories/Geo/GeoCategory+ClientBehavior.swift index b435e6931c..9427bf2cf1 100644 --- a/Amplify/Categories/Geo/GeoCategory+ClientBehavior.swift +++ b/Amplify/Categories/Geo/GeoCategory+ClientBehavior.swift @@ -22,8 +22,10 @@ extension GeoCategory: GeoCategoryBehavior { /// `Geo.Error.networkError` if request failed or network unavailable /// `Geo.Error.pluginError` if encapsulated error received by a dependent plugin /// `Geo.Error.unknown` if error is unknown - public func search(for text: String, - options: Geo.SearchForTextOptions? = nil) async throws -> [Geo.Place] { + public func search( + for text: String, + options: Geo.SearchForTextOptions? = nil + ) async throws -> [Geo.Place] { return try await plugin.search(for: text, options: options) } @@ -41,8 +43,10 @@ extension GeoCategory: GeoCategoryBehavior { /// `Geo.Error.networkError` if request failed or network unavailable /// `Geo.Error.pluginError` if encapsulated error received by a dependent plugin /// `Geo.Error.unknown` if error is unknown - public func search(for coordinates: Geo.Coordinates, - options: Geo.SearchForCoordinatesOptions? = nil) async throws -> [Geo.Place] { + public func search( + for coordinates: Geo.Coordinates, + options: Geo.SearchForCoordinatesOptions? = nil + ) async throws -> [Geo.Place] { return try await plugin.search(for: coordinates, options: options) } diff --git a/Amplify/Categories/Geo/GeoCategory.swift b/Amplify/Categories/Geo/GeoCategory.swift index aa9579a9bb..6059187ae4 100644 --- a/Amplify/Categories/Geo/GeoCategory.swift +++ b/Amplify/Categories/Geo/GeoCategory.swift @@ -6,7 +6,7 @@ // /// The Geo category enables you to interact with geospacial services. -final public class GeoCategory: Category { +public final class GeoCategory: Category { /// Geo category type public let categoryType = CategoryType.geo @@ -56,7 +56,8 @@ final public class GeoCategory: Category { let pluginDescription = String(describing: plugin) let error = Geo.Error.invalidConfiguration( "Plugin \(pluginDescription) has an empty `key`.", - "Set the `key` property for \(String(describing: plugin))") + "Set the `key` property for \(String(describing: plugin))" + ) throw error } @@ -81,7 +82,8 @@ final public class GeoCategory: Category { let keys = plugins.keys.joined(separator: ", ") let error = Geo.Error.invalidConfiguration( "No plugin has been added for '\(key)'.", - "Either add a plugin for '\(key)', or use one of the known keys: \(keys)") + "Either add a plugin for '\(key)', or use one of the known keys: \(keys)" + ) throw error } return plugin diff --git a/Amplify/Categories/Geo/GeoCategoryBehavior.swift b/Amplify/Categories/Geo/GeoCategoryBehavior.swift index 29fe16bf57..ee0a854ff8 100644 --- a/Amplify/Categories/Geo/GeoCategoryBehavior.swift +++ b/Amplify/Categories/Geo/GeoCategoryBehavior.swift @@ -25,8 +25,10 @@ public protocol GeoCategoryBehavior { /// `Geo.Error.networkError` if request failed or network unavailable /// `Geo.Error.pluginError` if encapsulated error received by a dependent plugin /// `Geo.Error.unknown` if error is unknown - func search(for text: String, - options: Geo.SearchForTextOptions?) async throws -> [Geo.Place] + func search( + for text: String, + options: Geo.SearchForTextOptions? + ) async throws -> [Geo.Place] /// Reverse geocodes a given pair of coordinates and returns a list of Places /// closest to the specified position. @@ -42,8 +44,10 @@ public protocol GeoCategoryBehavior { /// `Geo.Error.networkError` if request failed or network unavailable /// `Geo.Error.pluginError` if encapsulated error received by a dependent plugin /// `Geo.Error.unknown` if error is unknown - func search(for coordinates: Geo.Coordinates, - options: Geo.SearchForCoordinatesOptions?) async throws -> [Geo.Place] + func search( + for coordinates: Geo.Coordinates, + options: Geo.SearchForCoordinatesOptions? + ) async throws -> [Geo.Place] // MARK: - Maps diff --git a/Amplify/Categories/Geo/Types/CLocationCoordinate2D+Geo.Coordinates.swift b/Amplify/Categories/Geo/Types/CLocationCoordinate2D+Geo.Coordinates.swift index a67ce4c3a1..d016d5e25b 100644 --- a/Amplify/Categories/Geo/Types/CLocationCoordinate2D+Geo.Coordinates.swift +++ b/Amplify/Categories/Geo/Types/CLocationCoordinate2D+Geo.Coordinates.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CoreLocation +import Foundation public extension CLLocationCoordinate2D { /// Initialize a Location from a CLLocationCoordinate2D diff --git a/Amplify/Categories/Geo/Types/Geo+Coordinates.swift b/Amplify/Categories/Geo/Types/Geo+Coordinates.swift index b374b42e4f..0e30837097 100644 --- a/Amplify/Categories/Geo/Types/Geo+Coordinates.swift +++ b/Amplify/Categories/Geo/Types/Geo+Coordinates.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CoreLocation +import Foundation public extension Geo { /// A pair of coordinates to represent a location (point). diff --git a/Amplify/Categories/Geo/Types/Geo+Error.swift b/Amplify/Categories/Geo/Types/Geo+Error.swift index d7e6b81615..abd91e40d2 100644 --- a/Amplify/Categories/Geo/Types/Geo+Error.swift +++ b/Amplify/Categories/Geo/Types/Geo+Error.swift @@ -27,9 +27,11 @@ public extension Geo { extension Geo.Error: AmplifyError { /// Initializer - public init(errorDescription: ErrorDescription = "An unknown error occurred", - recoverySuggestion: RecoverySuggestion = "See `underlyingError` for more details", - error: Error) { + public init( + errorDescription: ErrorDescription = "An unknown error occurred", + recoverySuggestion: RecoverySuggestion = "See `underlyingError` for more details", + error: Error + ) { if let error = error as? Self { self = error } else if error.isOperationCancelledError { diff --git a/Amplify/Categories/Geo/Types/Geo+Place.swift b/Amplify/Categories/Geo/Types/Geo+Place.swift index 18d6e4c2dd..ebfedd6fc9 100644 --- a/Amplify/Categories/Geo/Types/Geo+Place.swift +++ b/Amplify/Categories/Geo/Types/Geo+Place.swift @@ -34,16 +34,18 @@ public extension Geo { public let country: String? /// Initializer - public init(coordinates: Coordinates, - label: String?, - addressNumber: String?, - street: String?, - municipality: String?, - neighborhood: String?, - region: String?, - subRegion: String?, - postalCode: String?, - country: String?) { + public init( + coordinates: Coordinates, + label: String?, + addressNumber: String?, + street: String?, + municipality: String?, + neighborhood: String?, + region: String?, + subRegion: String?, + postalCode: String?, + country: String? + ) { self.coordinates = coordinates self.label = label self.addressNumber = addressNumber diff --git a/Amplify/Categories/Geo/Types/Geo+SearchArea.swift b/Amplify/Categories/Geo/Types/Geo+SearchArea.swift index c0a3b3c124..13c5c7a816 100644 --- a/Amplify/Categories/Geo/Types/Geo+SearchArea.swift +++ b/Amplify/Categories/Geo/Types/Geo+SearchArea.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CoreLocation +import Foundation public extension Geo { /// The area to search. diff --git a/Amplify/Categories/Geo/Types/Geo+SearchOptions.swift b/Amplify/Categories/Geo/Types/Geo+SearchOptions.swift index 88f683c5b9..5353d90fef 100644 --- a/Amplify/Categories/Geo/Types/Geo+SearchOptions.swift +++ b/Amplify/Categories/Geo/Types/Geo+SearchOptions.swift @@ -21,10 +21,12 @@ public extension Geo { /// functionality. See plugin documentation for expected key/values. public var pluginOptions: Any? - public init(area: Geo.SearchArea? = nil, - countries: [Geo.Country]? = nil, - maxResults: Int? = nil, - pluginOptions: Any? = nil) { + public init( + area: Geo.SearchArea? = nil, + countries: [Geo.Country]? = nil, + maxResults: Int? = nil, + pluginOptions: Any? = nil + ) { self.area = area self.countries = countries self.maxResults = maxResults @@ -43,8 +45,10 @@ public extension Geo { /// functionality. See plugin documentation for expected key/values. public var pluginOptions: Any? - public init(maxResults: Int? = nil, - pluginOptions: Any? = nil) { + public init( + maxResults: Int? = nil, + pluginOptions: Any? = nil + ) { self.maxResults = maxResults self.pluginOptions = pluginOptions } diff --git a/Amplify/Categories/Hub/HubCategory+ClientBehavior.swift b/Amplify/Categories/Hub/HubCategory+ClientBehavior.swift index 14afd3581d..ced73c0d02 100644 --- a/Amplify/Categories/Hub/HubCategory+ClientBehavior.swift +++ b/Amplify/Categories/Hub/HubCategory+ClientBehavior.swift @@ -18,15 +18,19 @@ extension HubCategory: HubCategoryBehavior { plugin.dispatch(to: channel, payload: payload) } - public func listen(to channel: HubChannel, - eventName: HubPayloadEventName, - listener: @escaping HubListener) -> UnsubscribeToken { + public func listen( + to channel: HubChannel, + eventName: HubPayloadEventName, + listener: @escaping HubListener + ) -> UnsubscribeToken { plugin.listen(to: channel, eventName: eventName, listener: listener) } - public func listen(to channel: HubChannel, - isIncluded filter: HubFilter? = nil, - listener: @escaping HubListener) -> UnsubscribeToken { + public func listen( + to channel: HubChannel, + isIncluded filter: HubFilter? = nil, + listener: @escaping HubListener + ) -> UnsubscribeToken { plugin.listen(to: channel, isIncluded: filter, listener: listener) } diff --git a/Amplify/Categories/Hub/HubCategory.swift b/Amplify/Categories/Hub/HubCategory.swift index d12e45323a..e82135caae 100644 --- a/Amplify/Categories/Hub/HubCategory.swift +++ b/Amplify/Categories/Hub/HubCategory.swift @@ -10,7 +10,7 @@ /// between modules and components in your app. Hub enables different categories to /// communicate with one another when specific events occur, such as authentication /// events like a user sign-in or notification of a file download. -final public class HubCategory: Category { +public final class HubCategory: Category { enum ConfigurationState { /// Default configuration at initialization @@ -87,8 +87,10 @@ final public class HubCategory: Category { let key = plugin.key guard !key.isEmpty else { let pluginDescription = String(describing: plugin) - let error = HubError.configuration("Plugin \(pluginDescription) has an empty `key`.", - "Set the `key` property for \(String(describing: plugin))") + let error = HubError.configuration( + "Plugin \(pluginDescription) has an empty `key`.", + "Set the `key` property for \(String(describing: plugin))" + ) throw error } @@ -102,8 +104,10 @@ final public class HubCategory: Category { public func getPlugin(for key: PluginKey) throws -> HubCategoryPlugin { guard let plugin = plugins[key] else { let keys = plugins.keys.joined(separator: ", ") - let error = HubError.configuration("No plugin has been added for '\(key)'.", - "Either add a plugin for '\(key)', or use one of the known keys: \(keys)") + let error = HubError.configuration( + "No plugin has been added for '\(key)'.", + "Either add a plugin for '\(key)', or use one of the known keys: \(keys)" + ) throw error } return plugin diff --git a/Amplify/Categories/Hub/HubCategoryBehavior.swift b/Amplify/Categories/Hub/HubCategoryBehavior.swift index 45b577f670..d969bbface 100644 --- a/Amplify/Categories/Hub/HubCategoryBehavior.swift +++ b/Amplify/Categories/Hub/HubCategoryBehavior.swift @@ -23,9 +23,11 @@ public protocol HubCategoryBehavior { /// - Parameter channel: The channel to listen for messages on /// - Parameter eventName: Only hub payloads with this event name will be dispatched to the listener /// - Parameter listener: The closure to invoke with the received message - func listen(to channel: HubChannel, - eventName: HubPayloadEventName, - listener: @escaping HubListener) -> UnsubscribeToken + func listen( + to channel: HubChannel, + eventName: HubPayloadEventName, + listener: @escaping HubListener + ) -> UnsubscribeToken /// Listen to Hub messages on a particular channel, optionally filtering message prior to dispatching them /// @@ -33,9 +35,11 @@ public protocol HubCategoryBehavior { /// - Parameter filter: If specified, candidate messages will be passed to this closure prior to dispatching to /// the `listener`. Only messages for which the filter returns `true` will be dispatched. /// - Parameter listener: The closure to invoke with the received message - func listen(to channel: HubChannel, - isIncluded filter: HubFilter?, - listener: @escaping HubListener) -> UnsubscribeToken + func listen( + to channel: HubChannel, + isIncluded filter: HubFilter?, + listener: @escaping HubListener + ) -> UnsubscribeToken /// Removes the listener identified by `token` /// - Parameter token: The UnsubscribeToken returned by `listen` diff --git a/Amplify/Categories/Hub/HubChannel.swift b/Amplify/Categories/Hub/HubChannel.swift index 0979ac95c3..7315944c12 100644 --- a/Amplify/Categories/Hub/HubChannel.swift +++ b/Amplify/Categories/Hub/HubChannel.swift @@ -75,8 +75,8 @@ extension HubChannel: Equatable { } } -extension HubChannel { - public init(from categoryType: CategoryType) { +public extension HubChannel { + init(from categoryType: CategoryType) { switch categoryType { case .analytics: self = .analytics diff --git a/Amplify/Categories/Hub/HubFilter.swift b/Amplify/Categories/Hub/HubFilter.swift index afaff5ba77..85cf24c493 100644 --- a/Amplify/Categories/Hub/HubFilter.swift +++ b/Amplify/Categories/Hub/HubFilter.swift @@ -11,7 +11,7 @@ import Foundation public typealias HubFilter = (HubPayload) -> Bool /// Convenience filters for common filtering use cases -public struct HubFilters { +public enum HubFilters { /// True if all filters evaluate to true public static func all(filters: HubFilter...) -> HubFilter { @@ -31,8 +31,8 @@ public struct HubFilters { /// Returns a HubFilter that is `true` if the event's `context` property has a UUID that matches `operation.id` /// - Parameter operation: The operation to match - public static func forOperation - (_ operation: AmplifyOperation) -> HubFilter { + public static func forOperation + (_ operation: AmplifyOperation) -> HubFilter { let operationId = operation.id let filter: HubFilter = { payload in guard let context = payload.context as? AmplifyOperationContext else { diff --git a/Amplify/Categories/Hub/HubPayload.swift b/Amplify/Categories/Hub/HubPayload.swift index 3c89b0d73c..52b9746a42 100644 --- a/Amplify/Categories/Hub/HubPayload.swift +++ b/Amplify/Categories/Hub/HubPayload.swift @@ -24,9 +24,11 @@ public struct HubPayload { /// AmplifyOperations, this field will be the Operation's associated OperationResult. public let data: Any? - public init(eventName: String, - context: Any? = nil, - data: Any? = nil) { + public init( + eventName: String, + context: Any? = nil, + data: Any? = nil + ) { self.eventName = eventName self.context = context self.data = data diff --git a/Amplify/Categories/Logging/Internal/LoggingCategory+CategoryConfigurable.swift b/Amplify/Categories/Logging/Internal/LoggingCategory+CategoryConfigurable.swift index 67a9c69899..0d716cb3d2 100644 --- a/Amplify/Categories/Logging/Internal/LoggingCategory+CategoryConfigurable.swift +++ b/Amplify/Categories/Logging/Internal/LoggingCategory+CategoryConfigurable.swift @@ -26,9 +26,9 @@ extension LoggingCategory: CategoryConfigurable { } try plugin.configure(using: configuration?.plugins[plugin.key]) - self.plugins[plugin.key] = plugin + plugins[plugin.key] = plugin - if plugin.key != AWSUnifiedLoggingPlugin.key, let consolePlugin = try? self.getPlugin(for: AWSUnifiedLoggingPlugin.key) { + if plugin.key != AWSUnifiedLoggingPlugin.key, let consolePlugin = try? getPlugin(for: AWSUnifiedLoggingPlugin.key) { try consolePlugin.configure(using: configuration?.plugins[consolePlugin.key]) } @@ -57,9 +57,9 @@ extension LoggingCategory: CategoryConfigurable { } try plugin.configure(using: amplifyOutputs) - self.plugins[plugin.key] = plugin + plugins[plugin.key] = plugin - if plugin.key != AWSUnifiedLoggingPlugin.key, let consolePlugin = try? self.getPlugin(for: AWSUnifiedLoggingPlugin.key) { + if plugin.key != AWSUnifiedLoggingPlugin.key, let consolePlugin = try? getPlugin(for: AWSUnifiedLoggingPlugin.key) { try consolePlugin.configure(using: amplifyOutputs) } diff --git a/Amplify/Categories/Logging/LoggingCategory.swift b/Amplify/Categories/Logging/LoggingCategory.swift index b1dbd0e159..e23bba2c81 100644 --- a/Amplify/Categories/Logging/LoggingCategory.swift +++ b/Amplify/Categories/Logging/LoggingCategory.swift @@ -8,7 +8,7 @@ import Foundation /// AWS Amplify writes console logs through Logger. You can use Logger in your apps for the same purpose. -final public class LoggingCategory: Category { +public final class LoggingCategory: Category { enum ConfigurationState { /// Default configuration at initialization case `default` @@ -81,8 +81,10 @@ final public class LoggingCategory: Category { let key = plugin.key guard !key.isEmpty else { let pluginDescription = String(describing: plugin) - let error = LoggingError.configuration("Plugin \(pluginDescription) has an empty `key`.", - "Set the `key` property for \(String(describing: plugin))") + let error = LoggingError.configuration( + "Plugin \(pluginDescription) has an empty `key`.", + "Set the `key` property for \(String(describing: plugin))" + ) throw error } @@ -95,8 +97,10 @@ final public class LoggingCategory: Category { /// - Returns: The wrapped plugin public func getPlugin(for key: PluginKey) throws -> LoggingCategoryPlugin { guard let plugin = plugins.first(where: { $0.key == key})?.value else { - let error = LoggingError.configuration("No plugin has been added for '\(key)'.", - "Either add a plugin for '\(key)', or use the installed plugin, which has the key '\(key)'") + let error = LoggingError.configuration( + "No plugin has been added for '\(key)'.", + "Either add a plugin for '\(key)', or use the installed plugin, which has the key '\(key)'" + ) throw error } return plugin diff --git a/Amplify/Categories/Notifications/NotificationsCategory.swift b/Amplify/Categories/Notifications/NotificationsCategory.swift index 02c4122b6f..e0e6371fec 100644 --- a/Amplify/Categories/Notifications/NotificationsCategory.swift +++ b/Amplify/Categories/Notifications/NotificationsCategory.swift @@ -19,6 +19,6 @@ public final class NotificationsCategory { Push ] - return allSubcategories.filter { $0.isConfigured } + return allSubcategories.filter(\.isConfigured) } } diff --git a/Amplify/Categories/Notifications/PushNotifications/PushNotificationsCategory.swift b/Amplify/Categories/Notifications/PushNotifications/PushNotificationsCategory.swift index 2b81b046d7..7c675fdb10 100644 --- a/Amplify/Categories/Notifications/PushNotifications/PushNotificationsCategory.swift +++ b/Amplify/Categories/Notifications/PushNotifications/PushNotificationsCategory.swift @@ -55,7 +55,8 @@ public final class PushNotificationsCategory: Category { let pluginDescription = String(describing: plugin) let error = PushNotificationsError.configuration( "Plugin \(pluginDescription) has an empty `key`.", - "Set the `key` property for \(String(describing: plugin))") + "Set the `key` property for \(String(describing: plugin))" + ) throw error } @@ -80,7 +81,8 @@ public final class PushNotificationsCategory: Category { let keys = plugins.keys.joined(separator: ", ") let error = PushNotificationsError.configuration( "No plugin has been added for '\(key)'.", - "Either add a plugin for '\(key)', or use one of the known keys: \(keys)") + "Either add a plugin for '\(key)', or use one of the known keys: \(keys)" + ) throw error } return plugin diff --git a/Amplify/Categories/Notifications/PushNotifications/Types/PushNotificationsCategory+Types.swift b/Amplify/Categories/Notifications/PushNotifications/Types/PushNotificationsCategory+Types.swift index 5f2cf0966f..eaf7dc2f6e 100644 --- a/Amplify/Categories/Notifications/PushNotifications/Types/PushNotificationsCategory+Types.swift +++ b/Amplify/Categories/Notifications/PushNotifications/Types/PushNotificationsCategory+Types.swift @@ -7,6 +7,6 @@ import Foundation -extension Notifications { - public enum Push {} +public extension Notifications { + enum Push {} } diff --git a/Amplify/Categories/Notifications/PushNotifications/Types/PushNotificationsCategory+UserInfo.swift b/Amplify/Categories/Notifications/PushNotifications/Types/PushNotificationsCategory+UserInfo.swift index 4f513bdfbf..ccdfaab613 100644 --- a/Amplify/Categories/Notifications/PushNotifications/Types/PushNotificationsCategory+UserInfo.swift +++ b/Amplify/Categories/Notifications/PushNotifications/Types/PushNotificationsCategory+UserInfo.swift @@ -7,12 +7,12 @@ import Foundation -extension Notifications.Push { +public extension Notifications.Push { #if canImport(UIKit) /// A dictionary that contains information related to the remote notification - public typealias UserInfo = [AnyHashable: Any] + typealias UserInfo = [AnyHashable: Any] #elseif canImport(AppKit) /// A dictionary that contains information related to the remote notification - public typealias UserInfo = [String: Any] + typealias UserInfo = [String: Any] #endif } diff --git a/Amplify/Categories/Predictions/Error/PredictionsError+ClientError.swift b/Amplify/Categories/Predictions/Error/PredictionsError+ClientError.swift index d801ad26ff..23c390d934 100644 --- a/Amplify/Categories/Predictions/Error/PredictionsError+ClientError.swift +++ b/Amplify/Categories/Predictions/Error/PredictionsError+ClientError.swift @@ -7,8 +7,8 @@ import Foundation -extension PredictionsError { - public struct ClientError: Equatable { +public extension PredictionsError { + struct ClientError: Equatable { public static func == (lhs: PredictionsError.ClientError, rhs: PredictionsError.ClientError) -> Bool { lhs.description == rhs.description && lhs.recoverySuggestion == rhs.recoverySuggestion @@ -30,48 +30,48 @@ extension PredictionsError { } } -extension PredictionsError.ClientError { - public static let imageNotFound = Self( +public extension PredictionsError.ClientError { + static let imageNotFound = Self( description: "Something was wrong with the image file, make sure it exists.", recoverySuggestion: "Try choosing an image and sending it again." ) - public static let invalidRegion = Self( + static let invalidRegion = Self( description: "Invalid region", recoverySuggestion: "Ensure that you provide a valid region in your configuration" ) - public static let missingSourceLanguage = Self( + static let missingSourceLanguage = Self( description: "Source language is not provided", recoverySuggestion: "Provide a supported source language" ) - public static let missingTargetLanguage = Self( + static let missingTargetLanguage = Self( description: "Target language is not provided", recoverySuggestion: "Provide a supported target language" ) - public static let onlineIdentityServiceUnavailable = Self( + static let onlineIdentityServiceUnavailable = Self( description: "Online identify service is not available", recoverySuggestion: "Please check if the values are proprely initialized" ) - public static let offlineIdentityServiceUnavailable = Self( + static let offlineIdentityServiceUnavailable = Self( description: "Offline identify service is not available", recoverySuggestion: "Please check if the values are proprely initialized" ) - public static let onlineInterpretServiceUnavailable = Self( + static let onlineInterpretServiceUnavailable = Self( description: "Online interpret service is not available", recoverySuggestion: "Please check if the values are proprely initialized" ) - public static let offlineInterpretServiceUnavailable = Self( + static let offlineInterpretServiceUnavailable = Self( description: "Offline interpret service is not available", recoverySuggestion: "Please check if the values are proprely initialized" ) - public static let unableToInterpretText = Self( + static let unableToInterpretText = Self( description: "No result found for the text", recoverySuggestion: "Interpret text did not produce any result" ) diff --git a/Amplify/Categories/Predictions/Error/PredictionsError+ServiceError.swift b/Amplify/Categories/Predictions/Error/PredictionsError+ServiceError.swift index 173705b27d..34f694b322 100644 --- a/Amplify/Categories/Predictions/Error/PredictionsError+ServiceError.swift +++ b/Amplify/Categories/Predictions/Error/PredictionsError+ServiceError.swift @@ -7,8 +7,8 @@ import Foundation -extension PredictionsError { - public struct ServiceError: Equatable { +public extension PredictionsError { + struct ServiceError: Equatable { public static func == (lhs: PredictionsError.ServiceError, rhs: PredictionsError.ServiceError) -> Bool { lhs.description == rhs.description && lhs.recoverySuggestion == rhs.recoverySuggestion @@ -33,8 +33,8 @@ extension PredictionsError { } } -extension PredictionsError.ServiceError { - public static let translationFailed = Self( +public extension PredictionsError.ServiceError { + static let translationFailed = Self( description: "No result was found.", recoverySuggestion: """ Please make sure a text string was sent over and @@ -42,7 +42,7 @@ extension PredictionsError.ServiceError { """ ) - public static let internalServerError = Self( + static let internalServerError = Self( description: "An internal server error occurred.", recoverySuggestion: """ This shouldn't never happen. There is a possibility that there is a bug if this error persists. @@ -51,27 +51,27 @@ extension PredictionsError.ServiceError { """ ) - public static let detectedLanguageLowConfidence = Self( + static let detectedLanguageLowConfidence = Self( description: "A language was detected but with very low confidence.", recoverySuggestion: "Please make sure you use one of the available languages." ) - public static let invalidRequest = Self( + static let invalidRequest = Self( description: "An invalid request was sent.", recoverySuggestion: "Please check your request and try again." ) - public static let resourceNotFound = Self( + static let resourceNotFound = Self( description: "The specified resource doesn't exist.", recoverySuggestion: "Please make sure you configured the resource properly." ) - public static let textSizeLimitExceeded = Self( + static let textSizeLimitExceeded = Self( description: "The size of the text string exceeded the limit.", recoverySuggestion: "Please send a shorter text string." ) - public static let unsupportedLanguagePair = Self( + static let unsupportedLanguagePair = Self( description: "Your target language and source language are an unsupported language pair.", recoverySuggestion: """ Please ensure the service supports translating from the specified source @@ -79,22 +79,22 @@ extension PredictionsError.ServiceError { """ ) - public static let throttling = Self( + static let throttling = Self( description: "Your rate of request increase is too fast.", recoverySuggestion: "Slow down your request rate and gradually increase it." ) - public static let unsupportedLanguage = Self( + static let unsupportedLanguage = Self( description: "The language specified is not currently supported by the service.", recoverySuggestion: "Choose a new language that is supported." ) - public static let invalidSampleRate = Self( + static let invalidSampleRate = Self( description: "The specified sample rate is not valid.", recoverySuggestion: "" ) - public static let accessDenied = Self( + static let accessDenied = Self( description: "Access denied", recoverySuggestion: """ Please check that your Cognito IAM role has permissions diff --git a/Amplify/Categories/Predictions/Models/Attribute.swift b/Amplify/Categories/Predictions/Models/Attribute.swift index 0948c46ae5..d388cd6b56 100644 --- a/Amplify/Categories/Predictions/Models/Attribute.swift +++ b/Amplify/Categories/Predictions/Models/Attribute.swift @@ -7,9 +7,9 @@ import Foundation -extension Predictions { +public extension Predictions { /// Attribute of an entity identified as a result of identify() API - public struct Attribute { + struct Attribute { public let name: String public let value: Bool public let confidence: Double diff --git a/Amplify/Categories/Predictions/Models/BoundedKeyValue.swift b/Amplify/Categories/Predictions/Models/BoundedKeyValue.swift index 2bfc072ebb..b49bb59824 100644 --- a/Amplify/Categories/Predictions/Models/BoundedKeyValue.swift +++ b/Amplify/Categories/Predictions/Models/BoundedKeyValue.swift @@ -7,11 +7,11 @@ import CoreGraphics -extension Predictions { +public extension Predictions { /// Describes the data extracted as key-value pair in /// an image/document resulting from identify() API /// e.g The text "Name: John Doe" present in an image/document - public struct BoundedKeyValue { + struct BoundedKeyValue { public let key: String public let value: String public let isSelected: Bool diff --git a/Amplify/Categories/Predictions/Models/Celebrity+Metadata.swift b/Amplify/Categories/Predictions/Models/Celebrity+Metadata.swift index 9ec8bb99b4..2b30975a87 100644 --- a/Amplify/Categories/Predictions/Models/Celebrity+Metadata.swift +++ b/Amplify/Categories/Predictions/Models/Celebrity+Metadata.swift @@ -7,9 +7,9 @@ import Foundation -extension Predictions.Celebrity { +public extension Predictions.Celebrity { /// Celebrity metadata identified as a result of identify() API - public struct Metadata { + struct Metadata { public let name: String public let identifier: String public let urls: [URL] diff --git a/Amplify/Categories/Predictions/Models/Celebrity.swift b/Amplify/Categories/Predictions/Models/Celebrity.swift index 300955d199..2504a1f24a 100644 --- a/Amplify/Categories/Predictions/Models/Celebrity.swift +++ b/Amplify/Categories/Predictions/Models/Celebrity.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CoreGraphics +import Foundation -extension Predictions { +public extension Predictions { /// Describes a celebrity identified in an image /// with information about its location(bounding box) and /// facial features(landmarks) - public struct Celebrity { + struct Celebrity { public let metadata: Metadata public let boundingBox: CGRect public let landmarks: [Landmark] diff --git a/Amplify/Categories/Predictions/Models/Emotion+Kind.swift b/Amplify/Categories/Predictions/Models/Emotion+Kind.swift index 543d497456..64add5328a 100644 --- a/Amplify/Categories/Predictions/Models/Emotion+Kind.swift +++ b/Amplify/Categories/Predictions/Models/Emotion+Kind.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions.Emotion { +public extension Predictions.Emotion { /// Different emotion types returned as a result of /// identify() API call - public struct Kind: Equatable { + struct Kind: Equatable { let id: UInt8 public static let unknown = Self(id: 0) diff --git a/Amplify/Categories/Predictions/Models/Emotion.swift b/Amplify/Categories/Predictions/Models/Emotion.swift index 1f593ccbc4..367db2004e 100644 --- a/Amplify/Categories/Predictions/Models/Emotion.swift +++ b/Amplify/Categories/Predictions/Models/Emotion.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions { +public extension Predictions { /// Emotion identified in an entity(faces/celebrities) /// as a result of identify() API with associated `EmotionType` /// and confidence value - public struct Emotion { + struct Emotion { public let emotion: Kind public let confidence: Double diff --git a/Amplify/Categories/Predictions/Models/Entity+DetectionResult.swift b/Amplify/Categories/Predictions/Models/Entity+DetectionResult.swift index c61656c954..21a7032dbf 100644 --- a/Amplify/Categories/Predictions/Models/Entity+DetectionResult.swift +++ b/Amplify/Categories/Predictions/Models/Entity+DetectionResult.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions.Entity { +public extension Predictions.Entity { /// Describes the result of interpret() API when the analyzed text /// contains a person/place - public struct DetectionResult { + struct DetectionResult { public let type: Predictions.Entity.Kind public let targetText: String public let score: Float? diff --git a/Amplify/Categories/Predictions/Models/Entity+Kind.swift b/Amplify/Categories/Predictions/Models/Entity+Kind.swift index 1d66a50ac7..4bd6d98c61 100644 --- a/Amplify/Categories/Predictions/Models/Entity+Kind.swift +++ b/Amplify/Categories/Predictions/Models/Entity+Kind.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions.Entity { +public extension Predictions.Entity { /// Different entity types detected in a text as a result of /// interpret() API - public struct Kind: Equatable, Hashable { + struct Kind: Equatable, Hashable { let id: UInt8 public static let unknown = Self(id: 0) diff --git a/Amplify/Categories/Predictions/Models/Entity+Match.swift b/Amplify/Categories/Predictions/Models/Entity+Match.swift index c101004b9b..c1e6b3d0e5 100644 --- a/Amplify/Categories/Predictions/Models/Entity+Match.swift +++ b/Amplify/Categories/Predictions/Models/Entity+Match.swift @@ -7,10 +7,10 @@ import CoreGraphics -extension Predictions.Entity { +public extension Predictions.Entity { /// Describes the result for an entity matched in an entity collection /// created on AWS Rekogniton and detected from identify() API call - public struct Match { + struct Match { public let boundingBox: CGRect public let metadata: Metadata @@ -23,8 +23,8 @@ extension Predictions.Entity { } } } -extension Predictions.Entity.Match { - public struct Metadata { +public extension Predictions.Entity.Match { + struct Metadata { public let externalImageId: String? public let similarity: Double diff --git a/Amplify/Categories/Predictions/Models/Entity+Metadata.swift b/Amplify/Categories/Predictions/Models/Entity+Metadata.swift index 6c91db35b8..b81eccf7b3 100644 --- a/Amplify/Categories/Predictions/Models/Entity+Metadata.swift +++ b/Amplify/Categories/Predictions/Models/Entity+Metadata.swift @@ -7,8 +7,8 @@ import Foundation -extension Predictions.Entity { - public struct Metadata { +public extension Predictions.Entity { + struct Metadata { public let confidence: Double public let pose: Predictions.Pose diff --git a/Amplify/Categories/Predictions/Models/Entity.swift b/Amplify/Categories/Predictions/Models/Entity.swift index 273ec38fbf..b5dc15902a 100644 --- a/Amplify/Categories/Predictions/Models/Entity.swift +++ b/Amplify/Categories/Predictions/Models/Entity.swift @@ -7,10 +7,10 @@ import CoreGraphics -extension Predictions { +public extension Predictions { /// Result returned as part of identify() API call with /// `IdentifyAction.detectEntities` type parameter - public struct Entity { + struct Entity { public let boundingBox: CGRect public let landmarks: [Landmark] public let ageRange: ClosedRange? diff --git a/Amplify/Categories/Predictions/Models/Gender.swift b/Amplify/Categories/Predictions/Models/Gender.swift index 0889c9b767..7007246777 100644 --- a/Amplify/Categories/Predictions/Models/Gender.swift +++ b/Amplify/Categories/Predictions/Models/Gender.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions { +public extension Predictions { /// Describes gender of an entity identified as a result of /// identify() API - public struct Gender { + struct Gender { let id: UInt8 public static let unknown = Self(id: 0) diff --git a/Amplify/Categories/Predictions/Models/GenderAttribute.swift b/Amplify/Categories/Predictions/Models/GenderAttribute.swift index c7c6849efb..4c658b9b98 100644 --- a/Amplify/Categories/Predictions/Models/GenderAttribute.swift +++ b/Amplify/Categories/Predictions/Models/GenderAttribute.swift @@ -7,10 +7,10 @@ import Foundation -extension Predictions { +public extension Predictions { /// Gender of an entity(face/celebrity) identified with /// associated confidence value - public struct GenderAttribute { + struct GenderAttribute { public var gender: Gender public var confidence: Double diff --git a/Amplify/Categories/Predictions/Models/IdentifiedLine.swift b/Amplify/Categories/Predictions/Models/IdentifiedLine.swift index eaabadcd72..854f231b9a 100644 --- a/Amplify/Categories/Predictions/Models/IdentifiedLine.swift +++ b/Amplify/Categories/Predictions/Models/IdentifiedLine.swift @@ -7,10 +7,10 @@ import CoreGraphics -extension Predictions { +public extension Predictions { /// Describes a line of text identified in an image as a result of /// identify() API call - public struct IdentifiedLine: IdentifiedText { + struct IdentifiedLine: IdentifiedText { public let text: String public let boundingBox: CGRect public let polygon: Polygon? diff --git a/Amplify/Categories/Predictions/Models/IdentifiedWord.swift b/Amplify/Categories/Predictions/Models/IdentifiedWord.swift index 12a3b9d5ef..12e9fccce6 100644 --- a/Amplify/Categories/Predictions/Models/IdentifiedWord.swift +++ b/Amplify/Categories/Predictions/Models/IdentifiedWord.swift @@ -7,10 +7,10 @@ import CoreGraphics -extension Predictions { +public extension Predictions { /// Describes a word identified in an image as a result of /// identify() API call - public struct IdentifiedWord: IdentifiedText { + struct IdentifiedWord: IdentifiedText { public let text: String public let boundingBox: CGRect public let polygon: Polygon? diff --git a/Amplify/Categories/Predictions/Models/KeyPhrase.swift b/Amplify/Categories/Predictions/Models/KeyPhrase.swift index 656125ddb4..332983d2c1 100644 --- a/Amplify/Categories/Predictions/Models/KeyPhrase.swift +++ b/Amplify/Categories/Predictions/Models/KeyPhrase.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions { +public extension Predictions { /// Describes a key phrase identified in a text as /// a result of interpret() API call - public struct KeyPhrase { + struct KeyPhrase { public let score: Float? public let text: String public let range: Range diff --git a/Amplify/Categories/Predictions/Models/LabelType.swift b/Amplify/Categories/Predictions/Models/LabelType.swift index 0aff10defa..6223654af4 100644 --- a/Amplify/Categories/Predictions/Models/LabelType.swift +++ b/Amplify/Categories/Predictions/Models/LabelType.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions { - public struct LabelType: Equatable { +public extension Predictions { + struct LabelType: Equatable { let id: UInt8 public static let all = Self(id: 0) diff --git a/Amplify/Categories/Predictions/Models/Landmark.swift b/Amplify/Categories/Predictions/Models/Landmark.swift index 4a00fdeba6..8376bb1a5a 100644 --- a/Amplify/Categories/Predictions/Models/Landmark.swift +++ b/Amplify/Categories/Predictions/Models/Landmark.swift @@ -7,10 +7,10 @@ import CoreGraphics -extension Predictions { +public extension Predictions { /// Describes the facial feature in a celebrity/entity /// identified as a result of identify() API - public struct Landmark { + struct Landmark { public let kind: Kind public let points: [CGPoint] @@ -24,9 +24,9 @@ extension Predictions { } } -extension Predictions.Landmark { +public extension Predictions.Landmark { /// different types of facial features - public struct Kind { + struct Kind { let id: UInt8 public static let allPoints = Self(id: 0) diff --git a/Amplify/Categories/Predictions/Models/Language+DetectionResult.swift b/Amplify/Categories/Predictions/Models/Language+DetectionResult.swift index d31598288e..79635f7434 100644 --- a/Amplify/Categories/Predictions/Models/Language+DetectionResult.swift +++ b/Amplify/Categories/Predictions/Models/Language+DetectionResult.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions.Language { +public extension Predictions.Language { /// Result describing language identified in a text /// from interpret() API call - public struct DetectionResult { + struct DetectionResult { public let languageCode: Predictions.Language public let score: Double? diff --git a/Amplify/Categories/Predictions/Models/Language.swift b/Amplify/Categories/Predictions/Models/Language.swift index 484ef1ac1e..83073d49fa 100644 --- a/Amplify/Categories/Predictions/Models/Language.swift +++ b/Amplify/Categories/Predictions/Models/Language.swift @@ -7,9 +7,9 @@ import Foundation -extension Predictions { +public extension Predictions { // swiftlint:disable file_length type_body_length - public struct Language: Equatable, Decodable { + struct Language: Equatable, Decodable { public let code: String public init(code: String) { @@ -2396,8 +2396,8 @@ extension Predictions { } } -extension Predictions.Language { - public init(locale: Locale) { +public extension Predictions.Language { + init(locale: Locale) { guard let languageCode = locale.languageCode else { self = .undetermined return diff --git a/Amplify/Categories/Predictions/Models/PartOfSpeech+DetectionResult.swift b/Amplify/Categories/Predictions/Models/PartOfSpeech+DetectionResult.swift index 4104e9db10..a1e23aa397 100644 --- a/Amplify/Categories/Predictions/Models/PartOfSpeech+DetectionResult.swift +++ b/Amplify/Categories/Predictions/Models/PartOfSpeech+DetectionResult.swift @@ -7,9 +7,9 @@ import Foundation -extension Predictions.PartOfSpeech { +public extension Predictions.PartOfSpeech { /// Part of speech identified in a text from interpret() API - public struct DetectionResult { + struct DetectionResult { public let partOfSpeech: Predictions.PartOfSpeech public let score: Float? diff --git a/Amplify/Categories/Predictions/Models/PartOfSpeech.swift b/Amplify/Categories/Predictions/Models/PartOfSpeech.swift index a7db69909c..66849b9143 100644 --- a/Amplify/Categories/Predictions/Models/PartOfSpeech.swift +++ b/Amplify/Categories/Predictions/Models/PartOfSpeech.swift @@ -7,9 +7,9 @@ import Foundation -extension Predictions { +public extension Predictions { /// Part of speech identified in a text from interpret() API - public struct PartOfSpeech: Equatable { + struct PartOfSpeech: Equatable { let description: String public static let adjective = Self(description: "adjective") diff --git a/Amplify/Categories/Predictions/Models/Polygon.swift b/Amplify/Categories/Predictions/Models/Polygon.swift index bb38da8f64..f84ac8fd95 100644 --- a/Amplify/Categories/Predictions/Models/Polygon.swift +++ b/Amplify/Categories/Predictions/Models/Polygon.swift @@ -7,8 +7,8 @@ import CoreGraphics -extension Predictions { - public struct Polygon { +public extension Predictions { + struct Polygon { public let points: [CGPoint] public init(points: [CGPoint]) { diff --git a/Amplify/Categories/Predictions/Models/Pose.swift b/Amplify/Categories/Predictions/Models/Pose.swift index 8aa116ba7b..57a0ecdb76 100644 --- a/Amplify/Categories/Predictions/Models/Pose.swift +++ b/Amplify/Categories/Predictions/Models/Pose.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions { +public extension Predictions { /// Describes the pose of a person identified in an image from identify() API - public struct Pose { + struct Pose { public let pitch: Double public let roll: Double public let yaw: Double diff --git a/Amplify/Categories/Predictions/Models/Selection.swift b/Amplify/Categories/Predictions/Models/Selection.swift index d80fe53343..849104d849 100644 --- a/Amplify/Categories/Predictions/Models/Selection.swift +++ b/Amplify/Categories/Predictions/Models/Selection.swift @@ -7,8 +7,8 @@ import CoreGraphics -extension Predictions { - public struct Selection { +public extension Predictions { + struct Selection { public let boundingBox: CGRect public let polygon: Polygon public let isSelected: Bool diff --git a/Amplify/Categories/Predictions/Models/Sentiment+Kind.swift b/Amplify/Categories/Predictions/Models/Sentiment+Kind.swift index dbe46443db..d7e62b3282 100644 --- a/Amplify/Categories/Predictions/Models/Sentiment+Kind.swift +++ b/Amplify/Categories/Predictions/Models/Sentiment+Kind.swift @@ -7,8 +7,8 @@ import Foundation -extension Predictions.Sentiment { - public struct Kind: Equatable, Hashable { +public extension Predictions.Sentiment { + struct Kind: Equatable, Hashable { let id: UInt8 public static let unknown = Self(id: 0) diff --git a/Amplify/Categories/Predictions/Models/Sentiment.swift b/Amplify/Categories/Predictions/Models/Sentiment.swift index 58a6e2dc70..5869e22aba 100644 --- a/Amplify/Categories/Predictions/Models/Sentiment.swift +++ b/Amplify/Categories/Predictions/Models/Sentiment.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions { +public extension Predictions { /// Sentiment Analysis result for Predictions category - public struct Sentiment { + struct Sentiment { public let predominantSentiment: Kind public let sentimentScores: [Kind: Double]? diff --git a/Amplify/Categories/Predictions/Models/SyntaxToken.swift b/Amplify/Categories/Predictions/Models/SyntaxToken.swift index 56163d7960..b1048766d4 100644 --- a/Amplify/Categories/Predictions/Models/SyntaxToken.swift +++ b/Amplify/Categories/Predictions/Models/SyntaxToken.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions { +public extension Predictions { /// Describes syntactical information resulting from text interpretation as /// a result of interpret() API - public struct SyntaxToken { + struct SyntaxToken { public let tokenId: Int public let text: String public let range: Range diff --git a/Amplify/Categories/Predictions/Models/Table.swift b/Amplify/Categories/Predictions/Models/Table.swift index 82e9a812dd..06f2bb8acc 100644 --- a/Amplify/Categories/Predictions/Models/Table.swift +++ b/Amplify/Categories/Predictions/Models/Table.swift @@ -7,8 +7,8 @@ import CoreGraphics -extension Predictions { - public struct Table { +public extension Predictions { + struct Table { public var rows: Int public var columns: Int public var cells: [Cell] @@ -21,8 +21,8 @@ extension Predictions { } } -extension Predictions.Table { - public struct Cell { +public extension Predictions.Table { + struct Cell { public let text: String /// The location of the recognized text on the image. It includes an axis-aligned, diff --git a/Amplify/Categories/Predictions/Models/TextFormatType.swift b/Amplify/Categories/Predictions/Models/TextFormatType.swift index 7fa380acf9..4b6ea00915 100644 --- a/Amplify/Categories/Predictions/Models/TextFormatType.swift +++ b/Amplify/Categories/Predictions/Models/TextFormatType.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions { +public extension Predictions { /// Describes different text formats passed a type parameter /// to identify(). - public struct TextFormatType: Equatable { + struct TextFormatType: Equatable { let id: UInt8 public static let all = Self(id: 0) diff --git a/Amplify/Categories/Predictions/Models/Voice.swift b/Amplify/Categories/Predictions/Models/Voice.swift index 5cc73e87f4..ab72988572 100644 --- a/Amplify/Categories/Predictions/Models/Voice.swift +++ b/Amplify/Categories/Predictions/Models/Voice.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions { - public struct Voice { +public extension Predictions { + struct Voice { public let id: String public init(id: String) { diff --git a/Amplify/Categories/Predictions/PredictionsCategory+ClientBehavior.swift b/Amplify/Categories/Predictions/PredictionsCategory+ClientBehavior.swift index f9628e0b7d..1b0c2c2830 100644 --- a/Amplify/Categories/Predictions/PredictionsCategory+ClientBehavior.swift +++ b/Amplify/Categories/Predictions/PredictionsCategory+ClientBehavior.swift @@ -16,8 +16,8 @@ extension PredictionsCategory: PredictionsCategoryBehavior { try await plugin.identify(request, in: image, options: options) } - public func convert( - _ request: Predictions.Convert.Request, + public func convert( + _ request: Predictions.Convert.Request, options: Options? = nil ) async throws -> Output { try await plugin.convert(request, options: options) diff --git a/Amplify/Categories/Predictions/PredictionsCategory.swift b/Amplify/Categories/Predictions/PredictionsCategory.swift index 7a47cdfd82..2964626bfd 100644 --- a/Amplify/Categories/Predictions/PredictionsCategory.swift +++ b/Amplify/Categories/Predictions/PredictionsCategory.swift @@ -7,7 +7,7 @@ public enum Predictions {} -final public class PredictionsCategory: Category { +public final class PredictionsCategory: Category { public let categoryType = CategoryType.predictions diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+Lift.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+Lift.swift index 9f450dc17c..38bd3e3d18 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+Lift.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+Lift.swift @@ -7,9 +7,9 @@ import Foundation -extension Predictions.Convert.Request.Kind { +public extension Predictions.Convert.Request.Kind { @_spi(PredictionsConvertRequestKind) - public struct Lift< + struct Lift< SpecificInput, GenericInput, SpecificOptions, diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText+Options.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText+Options.swift index b1a6f3a526..34d69c4aeb 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText+Options.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText+Options.swift @@ -7,8 +7,8 @@ import Foundation -extension Predictions.Convert.SpeechToText { - public struct Options { +public extension Predictions.Convert.SpeechToText { + struct Options { /// The default NetworkPolicy for the operation. The default value will be `auto`. public let defaultNetworkPolicy: DefaultNetworkPolicy diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText+Request.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText+Request.swift index d20625afc6..e7e15606a2 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText+Request.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText+Request.swift @@ -7,8 +7,8 @@ import Foundation -extension Predictions.Convert.SpeechToText { - public struct Request { +public extension Predictions.Convert.SpeechToText { + struct Request { /// The text to synthesize to speech public let speechToText: URL diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText+Result.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText+Result.swift index bc597ec3ba..fdcbdc5c62 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText+Result.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText+Result.swift @@ -7,10 +7,10 @@ import Foundation -extension Predictions.Convert.SpeechToText { +public extension Predictions.Convert.SpeechToText { /// Results are mapped to SpeechToTextResult when convert() API is /// called to convert a text to audio - public struct Result { + struct Result { /// Resulting string from speech to text conversion public let transcription: String diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText.swift index c60d368d9c..d73222aa2c 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+SpeechToText.swift @@ -7,16 +7,16 @@ import Foundation -extension Predictions.Convert { - public enum SpeechToText {} +public extension Predictions.Convert { + enum SpeechToText {} } -extension Predictions.Convert.Request where +public extension Predictions.Convert.Request where Input == URL, Options == Predictions.Convert.SpeechToText.Options, Output == AsyncThrowingStream { - public static func speechToText(url: URL) -> Self { + static func speechToText(url: URL) -> Self { .init(input: url, kind: .speechToText(.lift)) } } diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech+Options.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech+Options.swift index 59d0ea93f1..e05c3e594f 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech+Options.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech+Options.swift @@ -7,8 +7,8 @@ import Foundation -extension Predictions.Convert.TextToSpeech { - public struct Options { +public extension Predictions.Convert.TextToSpeech { + struct Options { /// The default NetworkPolicy for the operation. The default value will be `auto`. public let defaultNetworkPolicy: DefaultNetworkPolicy diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech+Request.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech+Request.swift index fa38c3fd28..6b5f61ae2d 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech+Request.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech+Request.swift @@ -7,8 +7,8 @@ import Foundation -extension Predictions.Convert.TextToSpeech { - public struct Request { +public extension Predictions.Convert.TextToSpeech { + struct Request { /// The text to synthesize to speech public let textToSpeech: String diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech+Result.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech+Result.swift index d1ee3019d5..91fec245dc 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech+Result.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech+Result.swift @@ -7,10 +7,10 @@ import Foundation -extension Predictions.Convert.TextToSpeech { +public extension Predictions.Convert.TextToSpeech { /// Results are mapped to TextToSpeechResult when convert() API is /// called to convert a text to audio - public struct Result { + struct Result { /// Resulting audio from text to speech conversion public let audioData: Data diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech.swift index d15b83fa4b..a76d055201 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+TextToSpeech.swift @@ -7,16 +7,16 @@ import Foundation -extension Predictions.Convert { - public enum TextToSpeech {} +public extension Predictions.Convert { + enum TextToSpeech {} } -extension Predictions.Convert.Request where +public extension Predictions.Convert.Request where Input == String, Options == Predictions.Convert.TextToSpeech.Options, Output == Predictions.Convert.TextToSpeech.Result { - public static func textToSpeech(_ text: String) -> Self { + static func textToSpeech(_ text: String) -> Self { .init(input: text, kind: .textToSpeech(.lift)) } } diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText+Options.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText+Options.swift index b26b75d33e..a8f28ed6c2 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText+Options.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText+Options.swift @@ -7,8 +7,8 @@ import Foundation -extension Predictions.Convert.TranslateText { - public struct Options { +public extension Predictions.Convert.TranslateText { + struct Options { /// The default NetworkPolicy for the operation. The default value will be `auto`. public let defaultNetworkPolicy: DefaultNetworkPolicy diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText+Request.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText+Request.swift index e8832751e5..2f8080ef27 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText+Request.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText+Request.swift @@ -7,8 +7,8 @@ import Foundation -extension Predictions.Convert.TranslateText { - public struct Request { +public extension Predictions.Convert.TranslateText { + struct Request { /// The text to translate. public let textToTranslate: String diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText+Result.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText+Result.swift index 920eff83ba..ed49a4fb06 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText+Result.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText+Result.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions.Convert.TranslateText { +public extension Predictions.Convert.TranslateText { /// Results are mapped to TranslateTextResult when convert() API is /// called to translate a text into another language - public struct Result { + struct Result { /// Translated text public let text: String diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText.swift b/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText.swift index 572bb3c46c..22554b8e42 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert+TranslateText.swift @@ -7,16 +7,16 @@ import Foundation -extension Predictions.Convert { - public enum TranslateText {} +public extension Predictions.Convert { + enum TranslateText {} } -extension Predictions.Convert.Request where +public extension Predictions.Convert.Request where Input == (String, Predictions.Language?, Predictions.Language?), Options == Predictions.Convert.TranslateText.Options, Output == Predictions.Convert.TranslateText.Result { - public static func translateText( + static func translateText( _ text: String, from: Predictions.Language? = nil, to: Predictions.Language? = nil diff --git a/Amplify/Categories/Predictions/Request/Convert/Convert.swift b/Amplify/Categories/Predictions/Request/Convert/Convert.swift index 019bf95255..4f69f8682a 100644 --- a/Amplify/Categories/Predictions/Request/Convert/Convert.swift +++ b/Amplify/Categories/Predictions/Request/Convert/Convert.swift @@ -7,8 +7,8 @@ import Foundation -extension Predictions { - public enum Convert { +public extension Predictions { + enum Convert { public struct Request { public let input: Input @_spi(PredictionsConvertRequestKind) @@ -17,32 +17,32 @@ extension Predictions { } } -extension Predictions.Convert.Request { +public extension Predictions.Convert.Request { @_spi(PredictionsConvertRequestKind) - public enum Kind { + enum Kind { public typealias BidirectionalLift = ((T) -> U, (U) -> T) case textToSpeech( Lift< - String, Input, - Predictions.Convert.TextToSpeech.Options?, Options?, - Predictions.Convert.TextToSpeech.Result, Output + String, Input, + Predictions.Convert.TextToSpeech.Options?, Options?, + Predictions.Convert.TextToSpeech.Result, Output > ) case speechToText( Lift< - URL, Input, - Predictions.Convert.SpeechToText.Options?, Options?, - AsyncThrowingStream, Output + URL, Input, + Predictions.Convert.SpeechToText.Options?, Options?, + AsyncThrowingStream, Output > ) case textToTranslate( Lift< - (String, Predictions.Language?, Predictions.Language?), Input, - Predictions.Convert.TranslateText.Options?, Options?, - Predictions.Convert.TranslateText.Result, Output + (String, Predictions.Language?, Predictions.Language?), Input, + Predictions.Convert.TranslateText.Options?, Options?, + Predictions.Convert.TranslateText.Result, Output > ) } diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+Celebrities+Result.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+Celebrities+Result.swift index 8da0888ba6..77d3a23747 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+Celebrities+Result.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+Celebrities+Result.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions.Identify.Celebrities { +public extension Predictions.Identify.Celebrities { /// Results are mapped to IdentifyCelebritiesResult when .detectCelebrity in passed in the type: field /// in identify() API - public struct Result { + struct Result { public let celebrities: [Predictions.Celebrity] public init(celebrities: [Predictions.Celebrity]) { diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+Celebrities.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+Celebrities.swift index 05cf69b606..375c2333b4 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+Celebrities.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+Celebrities.swift @@ -7,12 +7,12 @@ import Foundation -extension Predictions.Identify { - public enum Celebrities {} +public extension Predictions.Identify { + enum Celebrities {} } -extension Predictions.Identify.Request where Output == Predictions.Identify.Celebrities.Result { - public static let celebrities = Self( +public extension Predictions.Identify.Request where Output == Predictions.Identify.Celebrities.Result { + static let celebrities = Self( kind: .detectCelebrities(.lift) ) } diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+Document.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+Document.swift index d8217fdc6a..8137ab7693 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+Document.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+Document.swift @@ -7,12 +7,12 @@ import Foundation -extension Predictions.Identify { - public enum DocumentText {} +public extension Predictions.Identify { + enum DocumentText {} } -extension Predictions.Identify.Request where Output == Predictions.Identify.DocumentText.Result { - public static func textInDocument(textFormatType: Predictions.TextFormatType) -> Self { +public extension Predictions.Identify.Request where Output == Predictions.Identify.DocumentText.Result { + static func textInDocument(textFormatType: Predictions.TextFormatType) -> Self { .init(kind: .detectTextInDocument(textFormatType, .lift)) } } diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+DocumentText+Result.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+DocumentText+Result.swift index 430667429a..bc7a4b6686 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+DocumentText+Result.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+DocumentText+Result.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions.Identify.DocumentText { +public extension Predictions.Identify.DocumentText { /// Results are mapped to IdentifyDocumentTextResult when .form, .table /// or .all is passed for .detectText in the type: field /// in identify() API - public struct Result { + struct Result { public let fullText: String public let words: [Predictions.IdentifiedWord] public let rawLineText: [String] diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+Entities+Result.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+Entities+Result.swift index ba7d2041ea..e90d6d26a3 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+Entities+Result.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+Entities+Result.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions.Identify.Entities { +public extension Predictions.Identify.Entities { /// Results are mapped to IdentifyEntitiesResult when .detectEntities is /// passed to type: field in identify() API and general entities like facial features, landmarks etc. /// are needed to be detected - public struct Result { + struct Result { /// List of 'Entity' as a result of Identify query public let entities: [Predictions.Entity] diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+Entities.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+Entities.swift index ad2fe77840..86f9e22e03 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+Entities.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+Entities.swift @@ -7,12 +7,12 @@ import Foundation -extension Predictions.Identify { - public enum Entities {} +public extension Predictions.Identify { + enum Entities {} } -extension Predictions.Identify.Request where Output == Predictions.Identify.Entities.Result { - public static let entities = Self( +public extension Predictions.Identify.Request where Output == Predictions.Identify.Entities.Result { + static let entities = Self( kind: .detectEntities(.lift) ) } diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+EntityMatches+Result.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+EntityMatches+Result.swift index 57878acea0..d2e19ff011 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+EntityMatches+Result.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+EntityMatches+Result.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions.Identify.EntityMatches { +public extension Predictions.Identify.EntityMatches { /// Results are mapped to IdentifyEntityMatchesResult when .detectEntities is /// passed to type: field in identify() API and matches from your Rekognition Collection /// need to be identified - public struct Result { + struct Result { /// List of matched `Entity.Match` public let entities: [Predictions.Entity.Match] diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+EntityMatches.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+EntityMatches.swift index c31b8f1ed8..4f03705d68 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+EntityMatches.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+EntityMatches.swift @@ -7,12 +7,12 @@ import Foundation -extension Predictions.Identify { - public enum EntityMatches {} +public extension Predictions.Identify { + enum EntityMatches {} } -extension Predictions.Identify.Request where Output == Predictions.Identify.EntityMatches.Result { - public static func entitiesFromCollection(withID collectionID: String) -> Self { +public extension Predictions.Identify.Request where Output == Predictions.Identify.EntityMatches.Result { + static func entitiesFromCollection(withID collectionID: String) -> Self { .init(kind: .detectEntitiesCollection(collectionID, .lift)) } } diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+Labels+Result.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+Labels+Result.swift index 245a2f14da..b5eb9e4e8d 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+Labels+Result.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+Labels+Result.swift @@ -7,10 +7,10 @@ import CoreGraphics -extension Predictions.Identify.Labels { +public extension Predictions.Identify.Labels { /// Results are mapped to IdentifyLabelsResult when .labels in passed to .detectLabels /// in the type: field in identify() API - public struct Result { + struct Result { public let labels: [Predictions.Label] public let unsafeContent: Bool? @@ -21,9 +21,9 @@ extension Predictions.Identify.Labels { } } -extension Predictions { +public extension Predictions { /// Describes a real world object (e.g., chair, desk) identified in an image - public struct Label { + struct Label { public let name: String public let metadata: Metadata? public let boundingBoxes: [CGRect]? @@ -39,7 +39,7 @@ extension Predictions { } } - public struct Parent { + struct Parent { public let name: String public init(name: String) { @@ -48,8 +48,8 @@ extension Predictions { } } -extension Predictions.Label { - public struct Metadata { +public extension Predictions.Label { + struct Metadata { public let confidence: Double public let parents: [Predictions.Parent]? diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+Labels.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+Labels.swift index 51698b50b9..a3724c9a27 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+Labels.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+Labels.swift @@ -7,12 +7,12 @@ import Foundation -extension Predictions.Identify { - public enum Labels {} +public extension Predictions.Identify { + enum Labels {} } -extension Predictions.Identify.Request where Output == Predictions.Identify.Labels.Result { - public static func labels(type: Predictions.LabelType = .labels) -> Self { +public extension Predictions.Identify.Request where Output == Predictions.Identify.Labels.Result { + static func labels(type: Predictions.LabelType = .labels) -> Self { .init(kind: .detectLabels(type, .lift)) } } diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+Lift.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+Lift.swift index 09654ba367..a6cb98736f 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+Lift.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+Lift.swift @@ -7,8 +7,8 @@ import Foundation -extension Predictions.Identify.Request.Kind { - public struct Lift< +public extension Predictions.Identify.Request.Kind { + struct Lift< SpecificOutput, GenericOutput > { diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+Text+Result.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+Text+Result.swift index 39f66964a0..1bfb2858e5 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+Text+Result.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+Text+Result.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions.Identify.Text { +public extension Predictions.Identify.Text { /// Results are mapped to IdentifyTextResult when .plain is passed for .detectText in the type: field /// in identify() API - public struct Result { + struct Result { public let fullText: String? public let words: [Predictions.IdentifiedWord]? public let rawLineText: [String]? diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+Text.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+Text.swift index 4db181e3bf..c0f5d4e0ee 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+Text.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+Text.swift @@ -7,12 +7,12 @@ import Foundation -extension Predictions.Identify { - public enum Text {} +public extension Predictions.Identify { + enum Text {} } -extension Predictions.Identify.Request where Output == Predictions.Identify.Text.Result { - public static let text = Self( +public extension Predictions.Identify.Request where Output == Predictions.Identify.Text.Result { + static let text = Self( kind: .detectText(.lift) ) } diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify.swift b/Amplify/Categories/Predictions/Request/Identify/Identify.swift index d033b26965..cacd204ae5 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify.swift @@ -9,8 +9,8 @@ import Foundation /// Identification criteria provided to /// type parameter in identify() API -extension Predictions { - public enum Identify { +public extension Predictions { + enum Identify { public struct Request { @_spi(PredictionsIdentifyRequestKind) public let kind: Kind @@ -37,9 +37,9 @@ extension Predictions { } } -extension Predictions.Identify.Request { +public extension Predictions.Identify.Request { @_spi(PredictionsIdentifyRequestKind) - public enum Kind { + enum Kind { public typealias Lifting = ((T) -> Output, (Output) -> T) case detectCelebrities( diff --git a/Amplify/Categories/Predictions/Request/Interpret/Interpret+Result.swift b/Amplify/Categories/Predictions/Request/Interpret/Interpret+Result.swift index 127cdc41a5..9da7d8b2a1 100644 --- a/Amplify/Categories/Predictions/Request/Interpret/Interpret+Result.swift +++ b/Amplify/Categories/Predictions/Request/Interpret/Interpret+Result.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Predictions.Interpret { - public struct Result { +public extension Predictions.Interpret { + struct Result { public let keyPhrases: [Predictions.KeyPhrase]? public let sentiment: Predictions.Sentiment? public let entities: [Predictions.Entity.DetectionResult]? diff --git a/Amplify/Categories/Predictions/Request/Interpret/Interpret.swift b/Amplify/Categories/Predictions/Request/Interpret/Interpret.swift index fddb1095d6..0973f21c6d 100644 --- a/Amplify/Categories/Predictions/Request/Interpret/Interpret.swift +++ b/Amplify/Categories/Predictions/Request/Interpret/Interpret.swift @@ -7,8 +7,8 @@ import Foundation -extension Predictions { - public enum Interpret {} +public extension Predictions { + enum Interpret {} } public extension Predictions.Interpret { @@ -21,8 +21,10 @@ public extension Predictions.Interpret { /// key/values public let pluginOptions: Any? - public init(defaultNetworkPolicy: DefaultNetworkPolicy = .auto, - pluginOptions: Any? = nil) { + public init( + defaultNetworkPolicy: DefaultNetworkPolicy = .auto, + pluginOptions: Any? = nil + ) { self.defaultNetworkPolicy = defaultNetworkPolicy self.pluginOptions = pluginOptions } diff --git a/Amplify/Categories/Storage/Operation/Request/StorageDownloadDataRequest.swift b/Amplify/Categories/Storage/Operation/Request/StorageDownloadDataRequest.swift index 73cf9f57fc..a9d4e73cad 100644 --- a/Amplify/Categories/Storage/Operation/Request/StorageDownloadDataRequest.swift +++ b/Amplify/Categories/Storage/Operation/Request/StorageDownloadDataRequest.swift @@ -17,7 +17,7 @@ public struct StorageDownloadDataRequest: AmplifyOperationRequest { /// /// - Tag: StorageDownloadFileRequest.path public let path: (any StoragePath)? - + /// The unique identifier for the object in storage /// /// - Tag: StorageDownloadDataRequest.key diff --git a/Amplify/Categories/Storage/Operation/Request/StorageListRequest.swift b/Amplify/Categories/Storage/Operation/Request/StorageListRequest.swift index 0c66976aeb..f5e83dab2e 100644 --- a/Amplify/Categories/Storage/Operation/Request/StorageListRequest.swift +++ b/Amplify/Categories/Storage/Operation/Request/StorageListRequest.swift @@ -106,7 +106,7 @@ public extension StorageListRequest { targetIdentityId: String? = nil, path: String? = nil, subpathStrategy: SubpathStrategy = .include, - pageSize: UInt = 1000, + pageSize: UInt = 1_000, nextToken: String? = nil, pluginOptions: Any? = nil ) { @@ -123,7 +123,7 @@ public extension StorageListRequest { /// - Tag: StorageListRequestOptions.init public init( subpathStrategy: SubpathStrategy = .include, - pageSize: UInt = 1000, + pageSize: UInt = 1_000, bucket: some StorageBucket, nextToken: String? = nil, pluginOptions: Any? = nil diff --git a/Amplify/Categories/Storage/Operation/StorageDownloadDataOperation.swift b/Amplify/Categories/Storage/Operation/StorageDownloadDataOperation.swift index ed608da6de..a6d0880936 100644 --- a/Amplify/Categories/Storage/Operation/StorageDownloadDataOperation.swift +++ b/Amplify/Categories/Storage/Operation/StorageDownloadDataOperation.swift @@ -21,7 +21,9 @@ public extension HubPayload.EventName.Storage { } /// - Tag: StorageDownloadDataTask -public typealias StorageDownloadDataTask = AmplifyInProcessReportingOperationTaskAdapter +public typealias StorageDownloadDataTask = AmplifyInProcessReportingOperationTaskAdapter< + StorageDownloadDataRequest, + Progress, + Data, + StorageError +> diff --git a/Amplify/Categories/Storage/Operation/StorageDownloadFileOperation.swift b/Amplify/Categories/Storage/Operation/StorageDownloadFileOperation.swift index 7d896219dc..8dcfd719ed 100644 --- a/Amplify/Categories/Storage/Operation/StorageDownloadFileOperation.swift +++ b/Amplify/Categories/Storage/Operation/StorageDownloadFileOperation.swift @@ -31,7 +31,9 @@ public extension HubPayload.EventName.Storage { } /// - Tag: StorageDownloadFileTask -public typealias StorageDownloadFileTask = AmplifyInProcessReportingOperationTaskAdapter +public typealias StorageDownloadFileTask = AmplifyInProcessReportingOperationTaskAdapter< + StorageDownloadFileRequest, + Progress, + Void, + StorageError +> diff --git a/Amplify/Categories/Storage/Operation/StorageUploadDataOperation.swift b/Amplify/Categories/Storage/Operation/StorageUploadDataOperation.swift index 5f9fed049f..2bd1de2baf 100644 --- a/Amplify/Categories/Storage/Operation/StorageUploadDataOperation.swift +++ b/Amplify/Categories/Storage/Operation/StorageUploadDataOperation.swift @@ -21,7 +21,9 @@ public extension HubPayload.EventName.Storage { } /// - Tag: StorageUploadDataTask -public typealias StorageUploadDataTask = AmplifyInProcessReportingOperationTaskAdapter +public typealias StorageUploadDataTask = AmplifyInProcessReportingOperationTaskAdapter< + StorageUploadDataRequest, + Progress, + String, + StorageError +> diff --git a/Amplify/Categories/Storage/Operation/StorageUploadFileOperation.swift b/Amplify/Categories/Storage/Operation/StorageUploadFileOperation.swift index 35d62df864..1fb07189cc 100644 --- a/Amplify/Categories/Storage/Operation/StorageUploadFileOperation.swift +++ b/Amplify/Categories/Storage/Operation/StorageUploadFileOperation.swift @@ -21,7 +21,9 @@ public extension HubPayload.EventName.Storage { } /// - Tag: StorageUploadFileTask -public typealias StorageUploadFileTask = AmplifyInProcessReportingOperationTaskAdapter +public typealias StorageUploadFileTask = AmplifyInProcessReportingOperationTaskAdapter< + StorageUploadFileRequest, + Progress, + String, + StorageError +> diff --git a/Amplify/Categories/Storage/Result/StorageListResult.swift b/Amplify/Categories/Storage/Result/StorageListResult.swift index 1adee4ea08..2425bba4d6 100644 --- a/Amplify/Categories/Storage/Result/StorageListResult.swift +++ b/Amplify/Categories/Storage/Result/StorageListResult.swift @@ -33,7 +33,7 @@ public struct StorageListResult { public var items: [Item] - /// Array of excluded subpaths in the Result. + /// Array of excluded subpaths in the Result. /// This field is only populated when [`StorageListRequest.Options.subpathStrategy`](x-source-tag://StorageListRequestOptions.subpathStragegy) is set to [`.exclude()`](x-source-tag://SubpathStrategy.exclude). /// /// - Tag: StorageListResult.excludedSubpaths @@ -49,10 +49,10 @@ public struct StorageListResult { public let nextToken: String? } -extension StorageListResult { +public extension StorageListResult { /// - Tag: StorageListResultItem - public struct Item { + struct Item { /// The path of the object in storage. /// diff --git a/Amplify/Categories/Storage/StorageCategory.swift b/Amplify/Categories/Storage/StorageCategory.swift index 919b127a0c..d8f45d56e6 100644 --- a/Amplify/Categories/Storage/StorageCategory.swift +++ b/Amplify/Categories/Storage/StorageCategory.swift @@ -7,9 +7,9 @@ /// AWS Amplify Storage module provides a simple mechanism for managing user content for your app in public, protected /// or private storage buckets. -/// +/// /// - Tag: StorageCategory -final public class StorageCategory: Category { +public final class StorageCategory: Category { public let categoryType = CategoryType.storage var plugins = [PluginKey: StorageCategoryPlugin]() @@ -54,8 +54,10 @@ final public class StorageCategory: Category { let key = plugin.key guard !key.isEmpty else { let pluginDescription = String(describing: plugin) - let error = StorageError.configuration("Plugin \(pluginDescription) has an empty `key`.", - "Set the `key` property for \(String(describing: plugin))") + let error = StorageError.configuration( + "Plugin \(pluginDescription) has an empty `key`.", + "Set the `key` property for \(String(describing: plugin))" + ) throw error } @@ -78,8 +80,10 @@ final public class StorageCategory: Category { public func getPlugin(for key: PluginKey) throws -> StorageCategoryPlugin { guard let plugin = plugins[key] else { let keys = plugins.keys.joined(separator: ", ") - let error = StorageError.configuration("No plugin has been added for '\(key)'.", - "Either add a plugin for '\(key)', or use one of the known keys: \(keys)") + let error = StorageError.configuration( + "No plugin has been added for '\(key)'.", + "Either add a plugin for '\(key)', or use one of the known keys: \(keys)" + ) throw error } return plugin diff --git a/Amplify/Categories/Storage/StorageCategoryBehavior.swift b/Amplify/Categories/Storage/StorageCategoryBehavior.swift index 0b933d4dfc..125a5baff4 100644 --- a/Amplify/Categories/Storage/StorageCategoryBehavior.swift +++ b/Amplify/Categories/Storage/StorageCategoryBehavior.swift @@ -53,8 +53,10 @@ public protocol StorageCategoryBehavior { /// - Tag: StorageCategoryBehavior.downloadData @available(*, deprecated, message: "Use downloadData(path:options:)") @discardableResult - func downloadData(key: String, - options: StorageDownloadDataOperation.Request.Options?) -> StorageDownloadDataTask + func downloadData( + key: String, + options: StorageDownloadDataOperation.Request.Options? + ) -> StorageDownloadDataTask /// Retrieve the object from storage into memory. /// diff --git a/Amplify/Core/Configuration/AmplifyConfiguration.swift b/Amplify/Core/Configuration/AmplifyConfiguration.swift index 2cb769f981..aacfea1483 100644 --- a/Amplify/Core/Configuration/AmplifyConfiguration.swift +++ b/Amplify/Core/Configuration/AmplifyConfiguration.swift @@ -57,16 +57,18 @@ public struct AmplifyConfiguration: Codable { let storage: StorageCategoryConfiguration? /// - Tag: Amplify.init - public init(analytics: AnalyticsCategoryConfiguration? = nil, - api: APICategoryConfiguration? = nil, - auth: AuthCategoryConfiguration? = nil, - dataStore: DataStoreCategoryConfiguration? = nil, - geo: GeoCategoryConfiguration? = nil, - hub: HubCategoryConfiguration? = nil, - logging: LoggingCategoryConfiguration? = nil, - notifications: NotificationsCategoryConfiguration? = nil, - predictions: PredictionsCategoryConfiguration? = nil, - storage: StorageCategoryConfiguration? = nil) { + public init( + analytics: AnalyticsCategoryConfiguration? = nil, + api: APICategoryConfiguration? = nil, + auth: AuthCategoryConfiguration? = nil, + dataStore: DataStoreCategoryConfiguration? = nil, + geo: GeoCategoryConfiguration? = nil, + hub: HubCategoryConfiguration? = nil, + logging: LoggingCategoryConfiguration? = nil, + notifications: NotificationsCategoryConfiguration? = nil, + predictions: PredictionsCategoryConfiguration? = nil, + storage: StorageCategoryConfiguration? = nil + ) { self.analytics = analytics self.api = api self.auth = auth diff --git a/Amplify/Core/Configuration/AmplifyOutputsData.swift b/Amplify/Core/Configuration/AmplifyOutputsData.swift index 8362306eda..f47b36e0b3 100644 --- a/Amplify/Core/Configuration/AmplifyOutputsData.swift +++ b/Amplify/Core/Configuration/AmplifyOutputsData.swift @@ -75,28 +75,30 @@ public struct AmplifyOutputsData: Codable { @_spi(InternalAmplifyConfiguration) public enum UsernameAttributes: String, Codable { - case email = "email" + case email case phoneNumber = "phone_number" } @_spi(InternalAmplifyConfiguration) public enum UserVerificationType: String, Codable { - case email = "email" + case email case phoneNumber = "phone_number" } - init(awsRegion: AWSRegion, - userPoolId: String, - userPoolClientId: String, - identityPoolId: String? = nil, - passwordPolicy: PasswordPolicy? = nil, - oauth: OAuth? = nil, - standardRequiredAttributes: [AmazonCognitoStandardAttributes]? = nil, - usernameAttributes: [UsernameAttributes]? = nil, - userVerificationTypes: [UserVerificationType]? = nil, - unauthenticatedIdentitiesEnabled: Bool? = nil, - mfaConfiguration: String? = nil, - mfaMethods: [String]? = nil) { + init( + awsRegion: AWSRegion, + userPoolId: String, + userPoolClientId: String, + identityPoolId: String? = nil, + passwordPolicy: PasswordPolicy? = nil, + oauth: OAuth? = nil, + standardRequiredAttributes: [AmazonCognitoStandardAttributes]? = nil, + usernameAttributes: [UsernameAttributes]? = nil, + userVerificationTypes: [UserVerificationType]? = nil, + unauthenticatedIdentitiesEnabled: Bool? = nil, + mfaConfiguration: String? = nil, + mfaMethods: [String]? = nil + ) { self.awsRegion = awsRegion self.userPoolId = userPoolId self.userPoolClientId = userPoolClientId @@ -154,10 +156,12 @@ public struct AmplifyOutputsData: Codable { } // Internal init used for testing - init(awsRegion: AWSRegion, - maps: Maps? = nil, - searchIndices: SearchIndices? = nil, - geofenceCollections: GeofenceCollections? = nil) { + init( + awsRegion: AWSRegion, + maps: Maps? = nil, + searchIndices: SearchIndices? = nil, + geofenceCollections: GeofenceCollections? = nil + ) { self.awsRegion = awsRegion self.maps = maps self.searchIndices = searchIndices @@ -244,14 +248,16 @@ public struct AmplifyOutputsData: Codable { } // Internal init used for testing - init(version: String = "", - analytics: Analytics? = nil, - auth: Auth? = nil, - data: DataCategory? = nil, - geo: Geo? = nil, - notifications: Notifications? = nil, - storage: Storage? = nil, - custom: CustomOutput? = nil) { + init( + version: String = "", + analytics: Analytics? = nil, + auth: Auth? = nil, + data: DataCategory? = nil, + geo: Geo? = nil, + notifications: Notifications? = nil, + storage: Storage? = nil, + custom: CustomOutput? = nil + ) { self.version = version self.analytics = analytics self.auth = auth @@ -274,11 +280,9 @@ public struct AmplifyOutputs { public let resolveConfiguration: () throws -> AmplifyOutputsData /// Resolves configuration with `amplify_outputs.json` in the main bundle. - public static let amplifyOutputs: AmplifyOutputs = { - .init { + public static let amplifyOutputs: AmplifyOutputs = .init { try AmplifyOutputsData(bundle: Bundle.main, resource: "amplify_outputs") } - }() /// Resolves configuration with a data object, from the contents of an `amplify_outputs.json` file. public static func data(_ data: Data) -> AmplifyOutputs { @@ -295,12 +299,12 @@ public struct AmplifyOutputs { } } -extension Amplify { +public extension Amplify { /// API to configure with Amplify CLI Gen2's configuration. /// /// - Parameter with: `AmplifyOutputs` configuration resolver - public static func configure(with amplifyOutputs: AmplifyOutputs) throws { + static func configure(with amplifyOutputs: AmplifyOutputs) throws { do { let resolvedConfiguration = try amplifyOutputs.resolveConfiguration() try configure(resolvedConfiguration) @@ -333,7 +337,7 @@ extension Amplify { /// /// - Tag: Amplify.configure @_spi(InternalAmplifyConfiguration) - public static func configure(_ configuration: AmplifyOutputsData) throws { + static func configure(_ configuration: AmplifyOutputsData) throws { // Always configure logging first since Auth dependings on logging try configure(CategoryType.logging.category, using: configuration) diff --git a/Amplify/Core/Configuration/ConfigurationError.swift b/Amplify/Core/Configuration/ConfigurationError.swift index 36d7d7abab..52ccf00ad9 100644 --- a/Amplify/Core/Configuration/ConfigurationError.swift +++ b/Amplify/Core/Configuration/ConfigurationError.swift @@ -8,7 +8,7 @@ /// Errors associated with configuring and inspecting Amplify Categories /// /// See: [Amplify.configure](x-source-tag://Amplify.configure) -/// +/// /// - Tag: ConfigurationError public enum ConfigurationError { /// The client issued a subsequent call to `Amplify.configure` after the first had already succeeded diff --git a/Amplify/Core/Configuration/Internal/Amplify+Reset.swift b/Amplify/Core/Configuration/Internal/Amplify+Reset.swift index 1748482c6e..278e7e28a9 100644 --- a/Amplify/Core/Configuration/Internal/Amplify+Reset.swift +++ b/Amplify/Core/Configuration/Internal/Amplify+Reset.swift @@ -51,7 +51,7 @@ extension Amplify { ModelListDecoderRegistry.reset() ModelProviderRegistry.reset() log.verbose("Resetting ModelRegistry, ModelListDecoderRegistry, ModelProviderRegistry finished") - + #if os(iOS) && !os(visionOS) await MainActor.run { devMenu = nil diff --git a/Amplify/Core/Configuration/Internal/Amplify+Resolve.swift b/Amplify/Core/Configuration/Internal/Amplify+Resolve.swift index 43e2f7cc4b..021ddd963a 100644 --- a/Amplify/Core/Configuration/Internal/Amplify+Resolve.swift +++ b/Amplify/Core/Configuration/Internal/Amplify+Resolve.swift @@ -10,7 +10,7 @@ import Foundation extension Amplify { static func resolve(configuration: AmplifyConfiguration? = nil) throws -> AmplifyConfiguration { - if let configuration = configuration { + if let configuration { return configuration } diff --git a/Amplify/Core/Model/BasicUserProfile.swift b/Amplify/Core/Model/BasicUserProfile.swift index 5d6227c122..9b841429a0 100644 --- a/Amplify/Core/Model/BasicUserProfile.swift +++ b/Amplify/Core/Model/BasicUserProfile.swift @@ -26,11 +26,13 @@ public struct BasicUserProfile: UserProfile { /// - plan: The plan for the user /// - location: Location data about the user /// - customProperties: Properties of the user profile - public init(name: String? = nil, - email: String? = nil, - plan: String? = nil, - location: UserProfileLocation? = nil, - customProperties: [String: UserProfilePropertyValue]? = nil) { + public init( + name: String? = nil, + email: String? = nil, + plan: String? = nil, + location: UserProfileLocation? = nil, + customProperties: [String: UserProfilePropertyValue]? = nil + ) { self.name = name self.email = email self.plan = plan diff --git a/Amplify/Core/Model/UserProfile.swift b/Amplify/Core/Model/UserProfile.swift index 307f045d82..476737369b 100644 --- a/Amplify/Core/Model/UserProfile.swift +++ b/Amplify/Core/Model/UserProfile.swift @@ -54,12 +54,14 @@ public struct UserProfileLocation { /// - city: The user's city /// - region: The user's region /// - country: The user's country - public init(latitude: Double? = nil, - longitude: Double? = nil, - postalCode: String? = nil, - city: String? = nil, - region: String? = nil, - country: String? = nil) { + public init( + latitude: Double? = nil, + longitude: Double? = nil, + postalCode: String? = nil, + city: String? = nil, + region: String? = nil, + country: String? = nil + ) { self.latitude = latitude self.longitude = longitude self.postalCode = postalCode diff --git a/Amplify/Core/Model/UserProfilePropertyValue.swift b/Amplify/Core/Model/UserProfilePropertyValue.swift index 0a992a12eb..f3a4dbe77d 100644 --- a/Amplify/Core/Model/UserProfilePropertyValue.swift +++ b/Amplify/Core/Model/UserProfilePropertyValue.swift @@ -20,4 +20,4 @@ extension String: UserProfilePropertyValue {} extension Int: UserProfilePropertyValue {} extension Double: UserProfilePropertyValue {} extension Bool: UserProfilePropertyValue {} -extension Array: UserProfilePropertyValue where Element == String {} +extension [String]: UserProfilePropertyValue {} diff --git a/Amplify/Core/Support/AccessLevel.swift b/Amplify/Core/Support/AccessLevel.swift index 8e2123e350..0e8d33ce9d 100644 --- a/Amplify/Core/Support/AccessLevel.swift +++ b/Amplify/Core/Support/AccessLevel.swift @@ -6,6 +6,7 @@ // import Foundation + public enum AccessLevel: String { case `public` case protected diff --git a/Amplify/Core/Support/AmplifyAsyncSequence.swift b/Amplify/Core/Support/AmplifyAsyncSequence.swift index 0320b6c9a3..bdc1330b3f 100644 --- a/Amplify/Core/Support/AmplifyAsyncSequence.swift +++ b/Amplify/Core/Support/AmplifyAsyncSequence.swift @@ -17,10 +17,12 @@ public class AmplifyAsyncSequence: AsyncSequence, Cancellable public private(set) var isCancelled: Bool = false - public init(parent: Cancellable? = nil, - bufferingPolicy: AsyncStream.Continuation.BufferingPolicy = .unbounded) { + public init( + parent: Cancellable? = nil, + bufferingPolicy: AsyncStream.Continuation.BufferingPolicy = .unbounded + ) { self.parent = parent - (asyncStream, continuation) = AsyncStream.makeStream(of: Element.self, bufferingPolicy: bufferingPolicy) + (self.asyncStream, self.continuation) = AsyncStream.makeStream(of: Element.self, bufferingPolicy: bufferingPolicy) } public func makeAsyncIterator() -> Iterator { diff --git a/Amplify/Core/Support/AmplifyAsyncThrowingSequence.swift b/Amplify/Core/Support/AmplifyAsyncThrowingSequence.swift index 5ff7d388eb..0f6c166bee 100644 --- a/Amplify/Core/Support/AmplifyAsyncThrowingSequence.swift +++ b/Amplify/Core/Support/AmplifyAsyncThrowingSequence.swift @@ -17,10 +17,12 @@ public class AmplifyAsyncThrowingSequence: AsyncSequence, Can public private(set) var isCancelled: Bool = false - public init(parent: Cancellable? = nil, - bufferingPolicy: AsyncThrowingStream.Continuation.BufferingPolicy = .unbounded) { + public init( + parent: Cancellable? = nil, + bufferingPolicy: AsyncThrowingStream.Continuation.BufferingPolicy = .unbounded + ) { self.parent = parent - (asyncStream, continuation) = AsyncThrowingStream.makeStream(of: Element.self, bufferingPolicy: bufferingPolicy) + (self.asyncStream, self.continuation) = AsyncThrowingStream.makeStream(of: Element.self, bufferingPolicy: bufferingPolicy) } public func makeAsyncIterator() -> Iterator { diff --git a/Amplify/Core/Support/AmplifyError.swift b/Amplify/Core/Support/AmplifyError.swift index 207dbb1835..64be69825b 100644 --- a/Amplify/Core/Support/AmplifyError.swift +++ b/Amplify/Core/Support/AmplifyError.swift @@ -72,7 +72,7 @@ public extension AmplifyError { components.append("Recovery suggestion: \(recoverySuggestion)") } - if let underlyingError = underlyingError { + if let underlyingError { if let underlyingAmplifyError = underlyingError as? AmplifyError { components.append("Caused by:\n\(underlyingAmplifyError.debugDescription)") } else { diff --git a/Amplify/Core/Support/AmplifyErrorMessages.swift b/Amplify/Core/Support/AmplifyErrorMessages.swift index f6632450b8..7c3ec2cab0 100644 --- a/Amplify/Core/Support/AmplifyErrorMessages.swift +++ b/Amplify/Core/Support/AmplifyErrorMessages.swift @@ -8,11 +8,13 @@ /// Commonly used cross-category error messages. /// /// - Tag: AmplifyErrorMessages -public struct AmplifyErrorMessages { +public enum AmplifyErrorMessages { /// - Tag: AmplifyErrorMessages.reportBugToAWS - public static func reportBugToAWS(file: StaticString = #file, - function: StaticString = #function, - line: UInt = #line) -> String { + public static func reportBugToAWS( + file: StaticString = #file, + function: StaticString = #function, + line: UInt = #line + ) -> String { """ There is a possibility that there is a bug if this error persists. Please take a look at \ https://github.com/aws-amplify/amplify-ios/issues to see if there are any existing issues that \ @@ -25,9 +27,11 @@ public struct AmplifyErrorMessages { } /// - Tag: AmplifyErrorMessages.shouldNotHappenReportBugToAWS - public static func shouldNotHappenReportBugToAWS(file: StaticString = #file, - function: StaticString = #function, - line: UInt = #line) -> String { + public static func shouldNotHappenReportBugToAWS( + file: StaticString = #file, + function: StaticString = #function, + line: UInt = #line + ) -> String { "This should not happen. \(reportBugToAWS(file: file, function: function, line: line))" } diff --git a/Amplify/Core/Support/AmplifyInProcessReportingOperation+Combine.swift b/Amplify/Core/Support/AmplifyInProcessReportingOperation+Combine.swift index d2e0b44160..541369c1fe 100644 --- a/Amplify/Core/Support/AmplifyInProcessReportingOperation+Combine.swift +++ b/Amplify/Core/Support/AmplifyInProcessReportingOperation+Combine.swift @@ -6,8 +6,8 @@ // #if canImport(Combine) -import Foundation import Combine +import Foundation extension AmplifyInProcessReportingOperation { /// A Publisher that emits in-process values for an operation, or the associated diff --git a/Amplify/Core/Support/AmplifyInProcessReportingOperation.swift b/Amplify/Core/Support/AmplifyInProcessReportingOperation.swift index f77e99d932..4e218bd3f4 100644 --- a/Amplify/Core/Support/AmplifyInProcessReportingOperation.swift +++ b/Amplify/Core/Support/AmplifyInProcessReportingOperation.swift @@ -34,21 +34,23 @@ open class AmplifyInProcessReportingOperation< var inProcessSubject: PassthroughSubject! #endif - public init(categoryType: CategoryType, - eventName: HubPayloadEventName, - request: Request, - inProcessListener: InProcessListener? = nil, - resultListener: ResultListener? = nil) { + public init( + categoryType: CategoryType, + eventName: HubPayloadEventName, + request: Request, + inProcessListener: InProcessListener? = nil, + resultListener: ResultListener? = nil + ) { super.init(categoryType: categoryType, eventName: eventName, request: request, resultListener: resultListener) #if canImport(Combine) - inProcessSubject = PassthroughSubject() + self.inProcessSubject = PassthroughSubject() #endif // If the inProcessListener is present, we need to register a hub event listener for it, and ensure we // automatically unsubscribe when we receive a completion event for the operation - if let inProcessListener = inProcessListener { + if let inProcessListener { self.inProcessListenerUnsubscribeToken = subscribe(inProcessListener: inProcessListener) } } @@ -74,15 +76,17 @@ open class AmplifyInProcessReportingOperation< } } - inProcessListenerToken = Amplify.Hub.listen(to: channel, - isIncluded: filterById, - listener: inProcessHubListener) + inProcessListenerToken = Amplify.Hub.listen( + to: channel, + isIncluded: filterById, + listener: inProcessHubListener + ) return inProcessListenerToken } /// Classes that override this method must emit a completion to the `inProcessPublisher` upon cancellation - open override func cancel() { + override open func cancel() { super.cancel() #if canImport(Combine) publish(completion: .finished) @@ -94,7 +98,7 @@ open class AmplifyInProcessReportingOperation< /// /// - Parameter result: The OperationResult to dispatch to the hub as part of the /// HubPayload - public override func dispatch(result: OperationResult) { + override public func dispatch(result: OperationResult) { #if canImport(Combine) publish(completion: .finished) #endif @@ -123,7 +127,7 @@ public extension AmplifyInProcessReportingOperation { /// Removes the listener that was registered during operation instantiation func removeInProcessResultListener() { - if let inProcessListenerUnsubscribeToken = inProcessListenerUnsubscribeToken { + if let inProcessListenerUnsubscribeToken { Amplify.Hub.removeListener(inProcessListenerUnsubscribeToken) } } diff --git a/Amplify/Core/Support/AmplifyOperation+Combine.swift b/Amplify/Core/Support/AmplifyOperation+Combine.swift index 5643a32ecd..e6daa89262 100644 --- a/Amplify/Core/Support/AmplifyOperation+Combine.swift +++ b/Amplify/Core/Support/AmplifyOperation+Combine.swift @@ -6,8 +6,8 @@ // #if canImport(Combine) -import Foundation import Combine +import Foundation // Most APIs will return an operation that exposes a `resultPublisher`. The // Storage and API category methods that expose both a result and an in-process diff --git a/Amplify/Core/Support/AmplifyOperation+Hub.swift b/Amplify/Core/Support/AmplifyOperation+Hub.swift index 97636a786e..771b418052 100644 --- a/Amplify/Core/Support/AmplifyOperation+Hub.swift +++ b/Amplify/Core/Support/AmplifyOperation+Hub.swift @@ -33,7 +33,8 @@ public extension HubCategory { func listenForInProcess( to operation: AmplifyInProcessReportingOperation, inProcessListener: @escaping AmplifyInProcessReportingOperation< - Request, InProcess, Success, Failure>.InProcessListener + Request, InProcess, Success, Failure + >.InProcessListener ) -> UnsubscribeToken { return operation.subscribe(inProcessListener: inProcessListener) } diff --git a/Amplify/Core/Support/AmplifyOperation.swift b/Amplify/Core/Support/AmplifyOperation.swift index 07d122d68c..3ae670ab1a 100644 --- a/Amplify/Core/Support/AmplifyOperation.swift +++ b/Amplify/Core/Support/AmplifyOperation.swift @@ -97,10 +97,12 @@ open class AmplifyOperation { self.resultPromise = $0 } + self.resultFuture = Future { self.resultPromise = $0 } #endif - if let resultListener = resultListener { + if let resultListener { self.resultListenerUnsubscribeToken = subscribe(resultListener: resultListener) } } @@ -130,7 +132,7 @@ open class AmplifyOperation: AmplifyTask { +public class AmplifyOperationTaskAdapter< + Request: AmplifyOperationRequest, + Success, + Failure: AmplifyError +>: AmplifyTask { let operation: AmplifyOperation let childTask: ChildTask var resultToken: UnsubscribeToken? @@ -20,13 +22,13 @@ public class AmplifyOperationTaskAdapter) { self.operation = operation self.childTask = ChildTask(parent: operation) - resultToken = operation.subscribe { [weak self] in + self.resultToken = operation.subscribe { [weak self] in self?.resultListener($0) } } deinit { - if let resultToken = resultToken { + if let resultToken { Amplify.Hub.removeListener(resultToken) } } @@ -64,10 +66,12 @@ public class AmplifyOperationTaskAdapter: AmplifyTask, AmplifyInProcessReportingTask { +public class AmplifyInProcessReportingOperationTaskAdapter< + Request: AmplifyOperationRequest, + InProcess, + Success, + Failure: AmplifyError +>: AmplifyTask, AmplifyInProcessReportingTask { let operation: AmplifyInProcessReportingOperation let childTask: ChildTask var resultToken: UnsubscribeToken? @@ -76,21 +80,21 @@ public class AmplifyInProcessReportingOperationTaskAdapter) { self.operation = operation self.childTask = ChildTask(parent: operation) - resultToken = operation.subscribe(resultListener: { [weak self] result in - guard let self = self else { return } - self.resultListener(result) + self.resultToken = operation.subscribe(resultListener: { [weak self] result in + guard let self else { return } + resultListener(result) }) - inProcessToken = operation.subscribe(inProcessListener: { [weak self] inProcess in - guard let self = self else { return } - self.inProcessListener(inProcess) + self.inProcessToken = operation.subscribe(inProcessListener: { [weak self] inProcess in + guard let self else { return } + inProcessListener(inProcess) }) } deinit { - if let resultToken = resultToken { + if let resultToken { Amplify.Hub.removeListener(resultToken) } - if let inProcessToken = inProcessToken { + if let inProcessToken { Amplify.Hub.removeListener(inProcessToken) } } diff --git a/Amplify/Core/Support/AmplifyTaskExecution.swift b/Amplify/Core/Support/AmplifyTaskExecution.swift index ff73c60f26..53cadf9e12 100644 --- a/Amplify/Core/Support/AmplifyTaskExecution.swift +++ b/Amplify/Core/Support/AmplifyTaskExecution.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Foundation /// Task that supports hub with execution of a single unit of work. . diff --git a/Amplify/Core/Support/AmplifyTaskGateway.swift b/Amplify/Core/Support/AmplifyTaskGateway.swift index cca0a94fbc..9e7c48f714 100644 --- a/Amplify/Core/Support/AmplifyTaskGateway.swift +++ b/Amplify/Core/Support/AmplifyTaskGateway.swift @@ -74,9 +74,11 @@ extension AmplifyTaskGateway { // Automatically unsubscribe when event is received unsubscribe?() } - let token = Amplify.Hub.listen(to: channel, - isIncluded: filterById, - listener: resultHubListener) + let token = Amplify.Hub.listen( + to: channel, + isIncluded: filterById, + listener: resultHubListener + ) unsubscribe = { Amplify.Hub.removeListener(token) } @@ -99,9 +101,11 @@ extension AmplifyTaskGateway { unsubscribe?() } } - let token = Amplify.Hub.listen(to: channel, - isIncluded: filterById, - listener: inProcessHubListener) + let token = Amplify.Hub.listen( + to: channel, + isIncluded: filterById, + listener: inProcessHubListener + ) unsubscribe = { Amplify.Hub.removeListener(token) } diff --git a/Amplify/Core/Support/Array+Extensions.swift b/Amplify/Core/Support/Array+Extensions.swift index fbf50b0dbd..36e7999eec 100644 --- a/Amplify/Core/Support/Array+Extensions.swift +++ b/Amplify/Core/Support/Array+Extensions.swift @@ -8,8 +8,8 @@ import Foundation // Inspired from: https://www.hackingwithswift.com/example-code/language/how-to-split-an-array-into-chunks -extension Array { - public func chunked(into size: Int) -> [[Element]] { +public extension Array { + func chunked(into size: Int) -> [[Element]] { return stride(from: 0, to: count, by: size).map { Array(self[$0 ..< Swift.min($0 + size, count)]) } diff --git a/Amplify/Core/Support/AsychronousOperation.swift b/Amplify/Core/Support/AsychronousOperation.swift index 762b336e39..8d2e2cd2c3 100644 --- a/Amplify/Core/Support/AsychronousOperation.swift +++ b/Amplify/Core/Support/AsychronousOperation.swift @@ -22,8 +22,10 @@ open class AsynchronousOperation: Operation { } /// Synchronizes access to `state`. - private let stateQueue = DispatchQueue(label: "com.amazonaws.amplify.AsynchronousOperation.state", - target: DispatchQueue.global()) + private let stateQueue = DispatchQueue( + label: "com.amazonaws.amplify.AsynchronousOperation.state", + target: DispatchQueue.global() + ) /// Private backing stored property for `state`. private var _state: OperationState = .notExecuting @@ -37,22 +39,22 @@ open class AsynchronousOperation: Operation { // MARK: - Various `Operation` properties /// `true` if the operation is ready to be executed - open override var isReady: Bool { + override open var isReady: Bool { return state == .notExecuting && super.isReady } /// `true` if the operation is currently executing - public final override var isExecuting: Bool { + override public final var isExecuting: Bool { return state == .executing } /// `true` if the operation has completed executing, either successfully or with an error - public final override var isFinished: Bool { + override public final var isFinished: Bool { return state == .finished } /// KVN for dependent properties - open override class func keyPathsForValuesAffectingValue(forKey key: String) -> Set { + override open class func keyPathsForValuesAffectingValue(forKey key: String) -> Set { if ["isReady", "isFinished", "isExecuting"].contains(key) { return [#keyPath(state)] } @@ -61,7 +63,7 @@ open class AsynchronousOperation: Operation { } /// Starts the operation - public final override func start() { + override public final func start() { if isCancelled { state = .finished return @@ -73,7 +75,7 @@ open class AsynchronousOperation: Operation { /// Subclasses must implement this to perform their work and they must not call `super`. /// The default implementation of this function throws an exception. - open override func main() { + override open func main() { fatalError("Subclasses must implement `main`.") } diff --git a/Amplify/Core/Support/AtomicDictionary.swift b/Amplify/Core/Support/AtomicDictionary.swift index fee9411e87..5bafdf4807 100644 --- a/Amplify/Core/Support/AtomicDictionary.swift +++ b/Amplify/Core/Support/AtomicDictionary.swift @@ -52,7 +52,7 @@ public final class AtomicDictionary { getValue(forKey: key) } set { - if let newValue = newValue { + if let newValue { set(value: newValue, forKey: key) } else { removeValue(forKey: key) diff --git a/Amplify/Core/Support/AtomicValue+Bool.swift b/Amplify/Core/Support/AtomicValue+Bool.swift index c8a60002c4..c80e53f175 100644 --- a/Amplify/Core/Support/AtomicValue+Bool.swift +++ b/Amplify/Core/Support/AtomicValue+Bool.swift @@ -5,7 +5,7 @@ // SPDX-License-Identifier: Apache-2.0 // -extension AtomicValue where Value == Bool { +public extension AtomicValue where Value == Bool { /// Toggles the boolean's value, and returns the **old** value. /// @@ -15,7 +15,7 @@ extension AtomicValue where Value == Bool { /// print(atomicBool.getAndToggle()) // prints "true" /// print(atomicBool.get()) // prints "false" /// ``` - public func getAndToggle() -> Value { + func getAndToggle() -> Value { lock.execute { let oldValue = value value.toggle() diff --git a/Amplify/Core/Support/AtomicValue+Numeric.swift b/Amplify/Core/Support/AtomicValue+Numeric.swift index a84dfc64a2..d83886aa9f 100644 --- a/Amplify/Core/Support/AtomicValue+Numeric.swift +++ b/Amplify/Core/Support/AtomicValue+Numeric.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -extension AtomicValue where Value: Numeric { +public extension AtomicValue where Value: Numeric { /// Increments the current value by `amount` and returns the incremented value - public func increment(by amount: Value = 1) -> Value { + func increment(by amount: Value = 1) -> Value { lock.execute { value += amount return value @@ -15,7 +15,7 @@ extension AtomicValue where Value: Numeric { } /// Decrements the current value by `amount` and returns the decremented value - public func decrement(by amount: Value = 1) -> Value { + func decrement(by amount: Value = 1) -> Value { lock.execute { value -= amount return value diff --git a/Amplify/Core/Support/AtomicValue+RangeReplaceableCollection.swift b/Amplify/Core/Support/AtomicValue+RangeReplaceableCollection.swift index 84396d9c96..6425cc8cfb 100644 --- a/Amplify/Core/Support/AtomicValue+RangeReplaceableCollection.swift +++ b/Amplify/Core/Support/AtomicValue+RangeReplaceableCollection.swift @@ -5,26 +5,26 @@ // SPDX-License-Identifier: Apache-2.0 // -extension AtomicValue where Value: RangeReplaceableCollection { - public func append(_ newElement: Value.Element) { +public extension AtomicValue where Value: RangeReplaceableCollection { + func append(_ newElement: Value.Element) { lock.execute { value.append(newElement) } } - public func append(contentsOf sequence: S) where S: Sequence, S.Element == Value.Element { + func append(contentsOf sequence: some Sequence) { lock.execute { value.append(contentsOf: sequence) } } - public func removeFirst() -> Value.Element { + func removeFirst() -> Value.Element { lock.execute { value.removeFirst() } } - public subscript(_ key: Value.Index) -> Value.Element { + subscript(_ key: Value.Index) -> Value.Element { lock.execute { value[key] } diff --git a/Amplify/Core/Support/Cancellable.swift b/Amplify/Core/Support/Cancellable.swift index 15f5db5b6a..8a6a0d9fae 100644 --- a/Amplify/Core/Support/Cancellable.swift +++ b/Amplify/Core/Support/Cancellable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import _Concurrency +import Foundation /// The conforming type supports cancelling an in-process operation. The exact semantics of "canceling" are not defined /// in the protocol. Specifically, there is no guarantee that a `cancel` results in immediate cessation of activity. diff --git a/Amplify/Core/Support/ChildTask.swift b/Amplify/Core/Support/ChildTask.swift index b9fa73adad..e83022094c 100644 --- a/Amplify/Core/Support/ChildTask.swift +++ b/Amplify/Core/Support/ChildTask.swift @@ -19,7 +19,7 @@ actor ChildTask: BufferingSequence { var inProcess: AmplifyAsyncSequence { let channel: AmplifyAsyncSequence - if let inProcessChannel = inProcessChannel { + if let inProcessChannel { channel = inProcessChannel } else { channel = AmplifyAsyncSequence(bufferingPolicy: bufferingPolicy) @@ -63,7 +63,7 @@ actor ChildTask: BufferingSequence { func report(_ inProcess: InProcess?) async throws { if let channel = inProcessChannel { - if let inProcess = inProcess { + if let inProcess { channel.send(inProcess) } else { // nil indicates the sequence is done @@ -77,7 +77,7 @@ actor ChildTask: BufferingSequence { send(result) } // store result for when the value property is used - self.storedResult = result + storedResult = result if let channel = inProcessChannel { channel.finish() } diff --git a/Amplify/Core/Support/DeviceInfo.swift b/Amplify/Core/Support/DeviceInfo.swift index 63a892303c..650dc694eb 100644 --- a/Amplify/Core/Support/DeviceInfo.swift +++ b/Amplify/Core/Support/DeviceInfo.swift @@ -6,6 +6,7 @@ // import Foundation + // Note: It's important to check for WatchKit first because a stripped-down version of UIKit is also // available on watchOS #if canImport(WatchKit) @@ -34,7 +35,7 @@ public struct DeviceInfo { private init() {} /// - Tag: DeviceInfo.current - public static var current: DeviceInfo = DeviceInfo() + public static var current: DeviceInfo = .init() /// Returns the name of the host or device /// @@ -96,8 +97,10 @@ public struct DeviceInfo { let device = UIDevice.current return (name: device.systemName, version: device.systemVersion) #else - return (name: "macOS", - version: ProcessInfo.processInfo.operatingSystemVersionString) + return ( + name: "macOS", + version: ProcessInfo.processInfo.operatingSystemVersionString + ) #endif } @@ -131,8 +134,10 @@ public struct DeviceInfo { #if canImport(IOKit) private func value(forKey key: String) -> String? { - let service = IOServiceGetMatchingService(kIOMasterPortDefault, - IOServiceMatching("IOPlatformExpertDevice")) + let service = IOServiceGetMatchingService( + kIOMasterPortDefault, + IOServiceMatching("IOPlatformExpertDevice") + ) var modelIdentifier: String? if let modelData = IORegistryEntryCreateCFProperty(service, key as CFString, kCFAllocatorDefault, 0).takeRetainedValue() as? Data { modelIdentifier = String(data: modelData, encoding: .utf8)?.trimmingCharacters(in: .controlCharacters) diff --git a/Amplify/Core/Support/DispatchSource+MakeOneOff.swift b/Amplify/Core/Support/DispatchSource+MakeOneOff.swift index 0bf038b33b..1e77624d69 100644 --- a/Amplify/Core/Support/DispatchSource+MakeOneOff.swift +++ b/Amplify/Core/Support/DispatchSource+MakeOneOff.swift @@ -7,7 +7,7 @@ import Foundation -extension DispatchSource { +public extension DispatchSource { /// Convenience function to encapsulate creation of a one-off DispatchSourceTimer for different versions of Swift /// /// - Parameters: @@ -15,9 +15,11 @@ extension DispatchSource { /// - queue: The queue on which the timer should perform its block /// - block: The block to invoke when the timer is fired /// - Returns: The unstarted timer - public static func makeOneOffDispatchSourceTimer(interval: DispatchTimeInterval, - queue: DispatchQueue, - block: @escaping () -> Void ) -> DispatchSourceTimer { + static func makeOneOffDispatchSourceTimer( + interval: DispatchTimeInterval, + queue: DispatchQueue, + block: @escaping () -> Void + ) -> DispatchSourceTimer { let deadline = DispatchTime.now() + interval return makeOneOffDispatchSourceTimer(deadline: deadline, queue: queue, block: block) } @@ -27,9 +29,11 @@ extension DispatchSource { /// - deadline: The time to fire the timer /// - queue: The queue on which the timer should perform its block /// - block: The block to invoke when the timer is fired - public static func makeOneOffDispatchSourceTimer(deadline: DispatchTime, - queue: DispatchQueue, - block: @escaping () -> Void ) -> DispatchSourceTimer { + static func makeOneOffDispatchSourceTimer( + deadline: DispatchTime, + queue: DispatchQueue, + block: @escaping () -> Void + ) -> DispatchSourceTimer { let timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: 0), queue: queue) #if swift(>=4) timer.schedule(deadline: deadline) diff --git a/Amplify/Core/Support/Encodable+AnyEncodable.swift b/Amplify/Core/Support/Encodable+AnyEncodable.swift index 17baadd403..3919a0c36b 100644 --- a/Amplify/Core/Support/Encodable+AnyEncodable.swift +++ b/Amplify/Core/Support/Encodable+AnyEncodable.swift @@ -20,9 +20,9 @@ public struct AnyEncodable: Encodable { } } -extension Encodable { +public extension Encodable { - public func eraseToAnyEncodable() -> AnyEncodable { + func eraseToAnyEncodable() -> AnyEncodable { return AnyEncodable(self) } diff --git a/Amplify/Core/Support/Fatal.swift b/Amplify/Core/Support/Fatal.swift index fa1600351d..1cddd7435a 100644 --- a/Amplify/Core/Support/Fatal.swift +++ b/Amplify/Core/Support/Fatal.swift @@ -15,9 +15,11 @@ import Foundation public enum Fatal { @discardableResult - public static func preconditionFailure(_ message: @autoclosure () -> String = String(), - file: StaticString = #file, - line: UInt = #line) -> T { + public static func preconditionFailure( + _ message: @autoclosure () -> String = String(), + file: StaticString = #file, + line: UInt = #line + ) -> T { guard let instanceFactory = AmplifyTesting.getInstanceFactory() else { Swift.preconditionFailure(message(), file: file, line: line) } @@ -30,9 +32,11 @@ public enum Fatal { /// Die because a default method must be overriden by a /// subtype or extension. - public static func mustOverride(function: StaticString = #function, - file: StaticString = #file, - line: UInt = #line) -> Never { + public static func mustOverride( + function: StaticString = #function, + file: StaticString = #file, + line: UInt = #line + ) -> Never { die(reason: "Must be overridden", extra: String(describing: function), file: file, line: line) } @@ -71,7 +75,7 @@ public enum Fatal { /// context information. private static func die(reason: String, extra: String? = nil, file: StaticString, line: UInt) -> Never { var message = reason - if let extra = extra { + if let extra { message += ": \(extra)" } fatalError(message, file: file, line: line) diff --git a/Amplify/Core/Support/Internal/InternalTask+AsyncSequence.swift b/Amplify/Core/Support/Internal/InternalTask+AsyncSequence.swift index ad66b30b94..fb13416abc 100644 --- a/Amplify/Core/Support/Internal/InternalTask+AsyncSequence.swift +++ b/Amplify/Core/Support/Internal/InternalTask+AsyncSequence.swift @@ -12,12 +12,12 @@ public extension InternalTaskAsyncSequence where Self: InternalTaskRunner { var sequence: AmplifyAsyncSequence { guard let sequence = context.sequence else { let task = Task { [weak self] in - guard let self = self else { return } - try await self.run() + guard let self else { return } + try await run() } let sequence = AmplifyAsyncSequence(parent: self, bufferingPolicy: context.bufferingPolicy) - self.context.task = task + context.task = task context.sequence = sequence return sequence } @@ -42,10 +42,10 @@ public extension InternalTaskAsyncThrowingSequence where Self: InternalTaskRunne context.sequence = sequence let task = Task { [weak self] in - guard let self = self else { return } - try await self.run() + guard let self else { return } + try await run() } - self.context.task = task + context.task = task return sequence } diff --git a/Amplify/Core/Support/Internal/InternalTask+Hub.swift b/Amplify/Core/Support/Internal/InternalTask+Hub.swift index 71bdb20ecb..9ef031e402 100644 --- a/Amplify/Core/Support/Internal/InternalTask+Hub.swift +++ b/Amplify/Core/Support/Internal/InternalTask+Hub.swift @@ -60,9 +60,11 @@ public extension InternalTaskHubResult where Self: InternalTaskIdentifiable & In // Automatically unsubscribe when event is received unsubscribe?() } - let token = Amplify.Hub.listen(to: channel, - isIncluded: idFilter, - listener: resultHubListener) + let token = Amplify.Hub.listen( + to: channel, + isIncluded: idFilter, + listener: resultHubListener + ) unsubscribe = { Amplify.Hub.removeListener(token) } @@ -94,9 +96,11 @@ public extension InternalTaskHubInProcess where Self: InternalTaskIdentifiable & return } } - let token = Amplify.Hub.listen(to: channel, - isIncluded: idFilter, - listener: inProcessHubListener) + let token = Amplify.Hub.listen( + to: channel, + isIncluded: idFilter, + listener: inProcessHubListener + ) return token } @@ -131,9 +135,11 @@ public extension InternalTaskHubInProcess where Self: InternalTaskIdentifiable & unsubscribe?() } } - let token = Amplify.Hub.listen(to: channel, - isIncluded: idFilter, - listener: inProcessHubListener) + let token = Amplify.Hub.listen( + to: channel, + isIncluded: idFilter, + listener: inProcessHubListener + ) unsubscribe = { Amplify.Hub.removeListener(token) } @@ -157,9 +163,11 @@ public extension InternalTaskHubInProcess where Self: InternalTaskIdentifiable { return } } - let token = Amplify.Hub.listen(to: channel, - isIncluded: filterById, - listener: inProcessHubListener) + let token = Amplify.Hub.listen( + to: channel, + isIncluded: filterById, + listener: inProcessHubListener + ) return token } @@ -194,9 +202,11 @@ public extension InternalTaskHubInProcess where Self: InternalTaskIdentifiable & unsubscribe?() } } - let token = Amplify.Hub.listen(to: channel, - isIncluded: filterById, - listener: inProcessHubListener) + let token = Amplify.Hub.listen( + to: channel, + isIncluded: filterById, + listener: inProcessHubListener + ) unsubscribe = { Amplify.Hub.removeListener(token) } diff --git a/Amplify/Core/Support/Internal/NSLocking+Execute.swift b/Amplify/Core/Support/Internal/NSLocking+Execute.swift index 87de3b3aba..f29de68a3e 100644 --- a/Amplify/Core/Support/Internal/NSLocking+Execute.swift +++ b/Amplify/Core/Support/Internal/NSLocking+Execute.swift @@ -10,7 +10,7 @@ import Foundation /// - Warning: Although this has `public` access, it is intended for internal use /// and should not be used directly by host applications. The behaviors and names of /// this type may change without warning. -extension NSLocking { +public extension NSLocking { /// Execute `block` after obtaining a lock on `lock`. /// /// - Warning: Although this has `public` access, it is intended for internal use @@ -18,7 +18,7 @@ extension NSLocking { /// this type may change without warning. /// - Parameters: /// - block: The block to execute - public func execute( + func execute( _ block: BasicThrowableClosure ) rethrows { try execute(input: (), block: block) @@ -32,7 +32,7 @@ extension NSLocking { /// this type may change without warning. /// - Parameters: /// - block: The block to execute - public func execute( + func execute( _ block: () throws -> Output ) rethrows -> Output { try execute(input: (), block: block) diff --git a/Amplify/Core/Support/JSONValue+KeyPath.swift b/Amplify/Core/Support/JSONValue+KeyPath.swift index 7e805fb09b..956441fe77 100644 --- a/Amplify/Core/Support/JSONValue+KeyPath.swift +++ b/Amplify/Core/Support/JSONValue+KeyPath.swift @@ -12,8 +12,10 @@ public extension JSONValue { value(at: keyPath, separatedBy: ".") } - func value(at keyPath: String, - separatedBy separator: T) -> JSONValue? { + func value( + at keyPath: String, + separatedBy separator: some StringProtocol + ) -> JSONValue? { let pathComponents = keyPath.components(separatedBy: separator) let value = pathComponents.reduce(self) { currVal, nextVal in currVal?[nextVal] } return value diff --git a/Amplify/Core/Support/JSONValue.swift b/Amplify/Core/Support/JSONValue.swift index afb1a243ad..8c477a78af 100644 --- a/Amplify/Core/Support/JSONValue.swift +++ b/Amplify/Core/Support/JSONValue.swift @@ -107,9 +107,9 @@ extension JSONValue: ExpressibleByStringLiteral { } } -extension JSONValue { +public extension JSONValue { - public var asObject: [String: JSONValue]? { + var asObject: [String: JSONValue]? { if case .object(let object) = self { return object } @@ -117,7 +117,7 @@ extension JSONValue { return nil } - public var asArray: [JSONValue]? { + var asArray: [JSONValue]? { if case .array(let array) = self { return array } @@ -125,7 +125,7 @@ extension JSONValue { return nil } - public var stringValue: String? { + var stringValue: String? { if case .string(let string) = self { return string } @@ -133,7 +133,7 @@ extension JSONValue { return nil } - public var intValue: Int? { + var intValue: Int? { if case .number(let double) = self, double < Double(Int.max) && double >= Double(Int.min) { return Int(double) @@ -141,7 +141,7 @@ extension JSONValue { return nil } - public var doubleValue: Double? { + var doubleValue: Double? { if case .number(let double) = self { return double } @@ -149,7 +149,7 @@ extension JSONValue { return nil } - public var booleanValue: Bool? { + var booleanValue: Bool? { if case .boolean(let bool) = self { return bool } @@ -157,7 +157,7 @@ extension JSONValue { return nil } - public var isNull: Bool { + var isNull: Bool { if case .null = self { return true } diff --git a/Amplify/Core/Support/OperationCancelledError.swift b/Amplify/Core/Support/OperationCancelledError.swift index 6ce876b9a0..113306efad 100644 --- a/Amplify/Core/Support/OperationCancelledError.swift +++ b/Amplify/Core/Support/OperationCancelledError.swift @@ -21,7 +21,7 @@ public struct OperationCancelledError: Error { /// change without warning. public extension AmplifyError { var isOperationCancelledError: Bool { - guard let underlyingError = underlyingError else { + guard let underlyingError else { return false } return underlyingError.isOperationCancelledError diff --git a/Amplify/Core/Support/Operations+Combine.swift b/Amplify/Core/Support/Operations+Combine.swift index f1cf40d789..6b25029018 100644 --- a/Amplify/Core/Support/Operations+Combine.swift +++ b/Amplify/Core/Support/Operations+Combine.swift @@ -6,8 +6,8 @@ // #if canImport(Combine) -import Foundation import Combine +import Foundation public extension AmplifyOperation { /// Publishes the final result of the operation diff --git a/Amplify/Core/Support/Optional+Extension.swift b/Amplify/Core/Support/Optional+Extension.swift index 4efb0d736f..1e064bf32a 100644 --- a/Amplify/Core/Support/Optional+Extension.swift +++ b/Amplify/Core/Support/Optional+Extension.swift @@ -7,13 +7,13 @@ import Foundation -extension Optional { +public extension Optional { /// /// Performing side effect function when data is exist /// - parameters: /// - then: a closure that takes wrapped data as a parameter @_spi(OptionalExtension) - public func ifSome(_ then: (Wrapped) throws -> Void) rethrows { + func ifSome(_ then: (Wrapped) throws -> Void) rethrows { if case .some(let wrapped) = self { try then(wrapped) } diff --git a/Amplify/Core/Support/Result+Void.swift b/Amplify/Core/Support/Result+Void.swift index 5c6060d230..6420112be8 100644 --- a/Amplify/Core/Support/Result+Void.swift +++ b/Amplify/Core/Support/Result+Void.swift @@ -5,6 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // -extension Result where Success == Void { - public static var successfulVoid: Result { .success(()) } +public extension Result where Success == Void { + static var successfulVoid: Result { .success(()) } } diff --git a/Amplify/Core/Support/String+Extensions.swift b/Amplify/Core/Support/String+Extensions.swift index 995ddcac9d..f95755725d 100644 --- a/Amplify/Core/Support/String+Extensions.swift +++ b/Amplify/Core/Support/String+Extensions.swift @@ -5,7 +5,7 @@ // SPDX-License-Identifier: Apache-2.0 // -extension String { +public extension String { /// Converts a "camelCase" value to "PascalCase". This is a very simple /// and naive implementation that assumes the input as a "camelCase" value @@ -15,7 +15,7 @@ extension String { /// - Note: this method simply transforms the first character to uppercase. /// /// - Returns: a string in "PascalCase" converted from "camelCase" - public func pascalCased() -> String { + func pascalCased() -> String { return prefix(1).uppercased() + dropFirst() } @@ -27,12 +27,12 @@ extension String { /// - Note: this method simply transforms the first character to lowercase. /// /// - Returns: a string in "pascalCase" converted from "CamelCase" - public func camelCased() -> String { + func camelCased() -> String { return prefix(1).lowercased() + dropFirst() } /// Appends "s" to the end of the string to represent the pluralized form. - public func pluralize() -> String { + func pluralize() -> String { return self + "s" } } diff --git a/Amplify/Core/Support/TaskQueue.swift b/Amplify/Core/Support/TaskQueue.swift index b7ba5c0553..eef0a6f0d9 100644 --- a/Amplify/Core/Support/TaskQueue.swift +++ b/Amplify/Core/Support/TaskQueue.swift @@ -62,8 +62,8 @@ public class TaskQueue { } } -extension TaskQueue { - public static var log: Logger { +public extension TaskQueue { + static var log: Logger { Amplify.Logging.logger(forNamespace: String(describing: self)) } } diff --git a/Amplify/Core/Support/TimeInterval+Helper.swift b/Amplify/Core/Support/TimeInterval+Helper.swift index b8baf2a3ef..179991e884 100644 --- a/Amplify/Core/Support/TimeInterval+Helper.swift +++ b/Amplify/Core/Support/TimeInterval+Helper.swift @@ -7,25 +7,25 @@ import Foundation -extension TimeInterval { +public extension TimeInterval { - public static func milliseconds(_ value: Double) -> TimeInterval { + static func milliseconds(_ value: Double) -> TimeInterval { return value / 1_000 } - public static func seconds(_ value: Double) -> TimeInterval { + static func seconds(_ value: Double) -> TimeInterval { return value } - public static func minutes(_ value: Double) -> TimeInterval { + static func minutes(_ value: Double) -> TimeInterval { return value * 60 } - public static func hours(_ value: Double) -> TimeInterval { + static func hours(_ value: Double) -> TimeInterval { return value * 60 * 60 } - public static func days(_ value: Double) -> TimeInterval { + static func days(_ value: Double) -> TimeInterval { return value * 60 * 60 * 24 } diff --git a/Amplify/DefaultPlugins/AWSHubPlugin/AWSHubPlugin.swift b/Amplify/DefaultPlugins/AWSHubPlugin/AWSHubPlugin.swift index 33100b2ed8..ad1a688273 100644 --- a/Amplify/DefaultPlugins/AWSHubPlugin/AWSHubPlugin.swift +++ b/Amplify/DefaultPlugins/AWSHubPlugin/AWSHubPlugin.swift @@ -21,7 +21,7 @@ import Foundation /// /// Instead, messages and listener states are guaranteed to be independently self-consistent. Callers can use /// `hasListener(withToken:)` to check that a listener has been registered. -final public class AWSHubPlugin: HubCategoryPlugin { +public final class AWSHubPlugin: HubCategoryPlugin { /// Convenience property. Each instance of `AWSHubPlugin` has the same key public static var key: String { return "awsHubPlugin" @@ -49,16 +49,20 @@ final public class AWSHubPlugin: HubCategoryPlugin { dispatcher.dispatch(to: channel, payload: payload) } - public func listen(to channel: HubChannel, - eventName: HubPayloadEventName, - listener: @escaping HubListener) -> UnsubscribeToken { + public func listen( + to channel: HubChannel, + eventName: HubPayloadEventName, + listener: @escaping HubListener + ) -> UnsubscribeToken { let filter = HubFilters.forEventName(eventName) return listen(to: channel, isIncluded: filter, listener: listener) } - public func listen(to channel: HubChannel, - isIncluded filter: HubFilter? = nil, - listener: @escaping HubListener) -> UnsubscribeToken { + public func listen( + to channel: HubChannel, + isIncluded filter: HubFilter? = nil, + listener: @escaping HubListener + ) -> UnsubscribeToken { let filteredListener = FilteredListener(for: channel, filter: filter, listener: listener) dispatcher.insert(filteredListener) diff --git a/Amplify/DefaultPlugins/AWSHubPlugin/Internal/ConcurrentDispatcher.swift b/Amplify/DefaultPlugins/AWSHubPlugin/Internal/ConcurrentDispatcher.swift index 59dcc97cea..37f278d6b2 100644 --- a/Amplify/DefaultPlugins/AWSHubPlugin/Internal/ConcurrentDispatcher.swift +++ b/Amplify/DefaultPlugins/AWSHubPlugin/Internal/ConcurrentDispatcher.swift @@ -39,7 +39,7 @@ struct ConcurrentDispatcher: Dispatcher { return } - listener.listener(self.payload) + listener.listener(payload) } } } diff --git a/Amplify/DefaultPlugins/AWSHubPlugin/Internal/SerialDispatcher.swift b/Amplify/DefaultPlugins/AWSHubPlugin/Internal/SerialDispatcher.swift index 62a7a16aa2..74d753bd45 100644 --- a/Amplify/DefaultPlugins/AWSHubPlugin/Internal/SerialDispatcher.swift +++ b/Amplify/DefaultPlugins/AWSHubPlugin/Internal/SerialDispatcher.swift @@ -32,17 +32,17 @@ struct SerialDispatcher: Dispatcher { } DispatchQueue.global().async { - guard !self.isCancelled else { + guard !isCancelled else { return } if let filter = filteredListener.filter { - guard filter(self.payload) else { + guard filter(payload) else { return } } - filteredListener.listener(self.payload) + filteredListener.listener(payload) } } } diff --git a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/AWSUnifiedLoggingPlugin.swift b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/AWSUnifiedLoggingPlugin.swift index 50f8c484ff..bbf90eed96 100644 --- a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/AWSUnifiedLoggingPlugin.swift +++ b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/AWSUnifiedLoggingPlugin.swift @@ -9,7 +9,7 @@ import Foundation import os.log /// A Logging category plugin that forwards calls to the OS's Unified Logging system -final public class AWSUnifiedLoggingPlugin: LoggingCategoryPlugin { +public final class AWSUnifiedLoggingPlugin: LoggingCategoryPlugin { /// Convenience property. Each instance of `AWSUnifiedLoggingPlugin` has the same key public static var key: String { @@ -35,8 +35,10 @@ final public class AWSUnifiedLoggingPlugin: LoggingCategoryPlugin { self.subsystem = Bundle.main.bundleIdentifier ?? "com.amazonaws.amplify.AWSUnifiedLoggingPlugin" let defaultOSLog = OSLog(subsystem: subsystem, category: AWSUnifiedLoggingPlugin.defaultCategory) - let wrapper = OSLogWrapper(osLog: defaultOSLog, - getLogLevel: { Amplify.Logging.logLevel }) + let wrapper = OSLogWrapper( + osLog: defaultOSLog, + getLogLevel: { Amplify.Logging.logLevel } + ) registeredLogs["default"] = wrapper } @@ -49,7 +51,7 @@ final public class AWSUnifiedLoggingPlugin: LoggingCategoryPlugin { /// Look for optional configuration to disable logging, console logging is enabled by default unless configured otherwise public func configure(using configuration: Any?) throws { if let consoleConfiguration = ConsoleLoggingConfiguration(bundle: Bundle.main), consoleConfiguration.enable == false { - self.disable() + disable() } } @@ -72,8 +74,10 @@ final public class AWSUnifiedLoggingPlugin: LoggingCategoryPlugin { } let osLog = OSLog(subsystem: subsystem, category: category) - let wrapper = OSLogWrapper(osLog: osLog, - getLogLevel: { Amplify.Logging.logLevel }) + let wrapper = OSLogWrapper( + osLog: osLog, + getLogLevel: { Amplify.Logging.logLevel } + ) wrapper.enabled = enabled registeredLogs[key] = wrapper return wrapper @@ -85,25 +89,25 @@ final public class AWSUnifiedLoggingPlugin: LoggingCategoryPlugin { } } -extension AWSUnifiedLoggingPlugin { - public var `default`: Logger { +public extension AWSUnifiedLoggingPlugin { + var `default`: Logger { // We register the default logger at initialization, and protect access via a setter method, so this is safe // to force-unwrap registeredLogs["default"]! } - public func logger(forCategory category: String) -> Logger { + func logger(forCategory category: String) -> Logger { let wrapper = logWrapper(for: category) return wrapper } - public func logger(forCategory category: String, logLevel: LogLevel) -> Logger { + func logger(forCategory category: String, logLevel: LogLevel) -> Logger { let wrapper = logWrapper(for: category) wrapper.logLevel = logLevel return wrapper } - public func enable() { + func enable() { enabled = true lock.execute { for (_, logger) in registeredLogs { @@ -112,7 +116,7 @@ extension AWSUnifiedLoggingPlugin { } } - public func disable() { + func disable() { enabled = false lock.execute { for (_, logger) in registeredLogs { @@ -121,12 +125,12 @@ extension AWSUnifiedLoggingPlugin { } } - public func logger(forNamespace namespace: String) -> Logger { + func logger(forNamespace namespace: String) -> Logger { let wrapper = logWrapper(for: namespace) return wrapper } - public func logger(forCategory category: String, forNamespace namespace: String) -> Logger { + func logger(forCategory category: String, forNamespace namespace: String) -> Logger { let wrapper = logWrapper(for: category + namespace) return wrapper } diff --git a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/OSLogWrapper.swift b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/OSLogWrapper.swift index 66529cc64d..8fd1277ed3 100644 --- a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/OSLogWrapper.swift +++ b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/OSLogWrapper.swift @@ -30,18 +30,22 @@ final class OSLogWrapper: Logger { public func error(_ message: @autoclosure () -> String) { guard enabled, logLevel.rawValue >= LogLevel.error.rawValue else { return } - os_log("%@", - log: osLog, - type: OSLogType.error, - message()) + os_log( + "%@", + log: osLog, + type: OSLogType.error, + message() + ) } public func error(error: Error) { guard enabled, logLevel.rawValue >= LogLevel.error.rawValue else { return } - os_log("%@", - log: osLog, - type: OSLogType.error, - error.localizedDescription) + os_log( + "%@", + log: osLog, + type: OSLogType.error, + error.localizedDescription + ) } public func warn(_ message: @autoclosure () -> String) { @@ -49,10 +53,12 @@ final class OSLogWrapper: Logger { return } - os_log("%@", - log: osLog, - type: OSLogType.info, - message()) + os_log( + "%@", + log: osLog, + type: OSLogType.info, + message() + ) } public func info(_ message: @autoclosure () -> String) { @@ -60,10 +66,12 @@ final class OSLogWrapper: Logger { return } - os_log("%@", - log: osLog, - type: OSLogType.info, - message()) + os_log( + "%@", + log: osLog, + type: OSLogType.info, + message() + ) } public func debug(_ message: @autoclosure () -> String) { @@ -71,10 +79,12 @@ final class OSLogWrapper: Logger { return } - os_log("%@", - log: osLog, - type: OSLogType.debug, - message()) + os_log( + "%@", + log: osLog, + type: OSLogType.debug, + message() + ) } public func verbose(_ message: @autoclosure () -> String) { @@ -82,9 +92,11 @@ final class OSLogWrapper: Logger { return } - os_log("%@", - log: osLog, - type: OSLogType.debug, - message()) + os_log( + "%@", + log: osLog, + type: OSLogType.debug, + message() + ) } } diff --git a/Amplify/DevMenu/AmplifyDevMenu.swift b/Amplify/DevMenu/AmplifyDevMenu.swift index 6a9a98955b..82888367e4 100644 --- a/Amplify/DevMenu/AmplifyDevMenu.swift +++ b/Amplify/DevMenu/AmplifyDevMenu.swift @@ -31,7 +31,8 @@ public final class AmplifyDevMenu: DevMenuBehavior, TriggerDelegate { public func showMenu() { guard let rootViewController = - devMenuPresentationContextProvider?.devMenuPresentationContext().rootViewController else { + devMenuPresentationContextProvider?.devMenuPresentationContext().rootViewController + else { Amplify.Logging.warn(DevMenuStringConstants.logTag + "RootViewController of the UIWindow is nil") return diff --git a/Amplify/DevMenu/AmplifyVersionable.swift b/Amplify/DevMenu/AmplifyVersionable.swift index afaf4cbe59..0e589bf806 100644 --- a/Amplify/DevMenu/AmplifyVersionable.swift +++ b/Amplify/DevMenu/AmplifyVersionable.swift @@ -12,8 +12,8 @@ public protocol AmplifyVersionable { var version: String { get } } -extension AmplifyVersionable where Self: AnyObject { - public var version: String { +public extension AmplifyVersionable where Self: AnyObject { + var version: String { let bundle = Bundle(for: type(of: self)) let version = bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String return version ?? "Not Available" diff --git a/Amplify/DevMenu/Data/DeviceInfoHelper.swift b/Amplify/DevMenu/Data/DeviceInfoHelper.swift index 5c938c5d51..a991ee3f3d 100644 --- a/Amplify/DevMenu/Data/DeviceInfoHelper.swift +++ b/Amplify/DevMenu/Data/DeviceInfoHelper.swift @@ -19,13 +19,13 @@ struct DeviceInfoHelper { isSimulator = true #endif return [ - DeviceInfoItem(type: .deviceName(UIDevice.current.name)), - DeviceInfoItem(type: .systemName(UIDevice.current.systemName)), - DeviceInfoItem(type: .systemVersion(UIDevice.current.systemVersion)), - DeviceInfoItem(type: .modelName(UIDevice.current.model)), - DeviceInfoItem(type: .localizedModelName(UIDevice.current.localizedModel)), - DeviceInfoItem(type: .isSimulator(isSimulator)) - ] + DeviceInfoItem(type: .deviceName(UIDevice.current.name)), + DeviceInfoItem(type: .systemName(UIDevice.current.systemName)), + DeviceInfoItem(type: .systemVersion(UIDevice.current.systemVersion)), + DeviceInfoItem(type: .modelName(UIDevice.current.model)), + DeviceInfoItem(type: .localizedModelName(UIDevice.current.localizedModel)), + DeviceInfoItem(type: .isSimulator(isSimulator)) + ] } } #endif diff --git a/Amplify/DevMenu/Data/DeviceInfoItem.swift b/Amplify/DevMenu/Data/DeviceInfoItem.swift index cd73bd233a..3228611d47 100644 --- a/Amplify/DevMenu/Data/DeviceInfoItem.swift +++ b/Amplify/DevMenu/Data/DeviceInfoItem.swift @@ -43,7 +43,7 @@ struct DeviceInfoItem: Identifiable, InfoItemProvider { case .localizedModelName(let value): return value ?? DevMenuStringConstants.notAvailable case .isSimulator(let value): - guard let value = value else { + guard let value else { return DevMenuStringConstants.notAvailable } return value ? "Yes" : "No" diff --git a/Amplify/DevMenu/Data/EnvironmentInfoHelper.swift b/Amplify/DevMenu/Data/EnvironmentInfoHelper.swift index cc99f63a79..cb139d033f 100644 --- a/Amplify/DevMenu/Data/EnvironmentInfoHelper.swift +++ b/Amplify/DevMenu/Data/EnvironmentInfoHelper.swift @@ -10,7 +10,7 @@ import Foundation import UIKit /// Helper class to fetch Developer Environment Information -struct EnvironmentInfoHelper { +enum EnvironmentInfoHelper { static let environmentInfoSourceFileName = "local-env-info" diff --git a/Amplify/DevMenu/Data/IssueInfo.swift b/Amplify/DevMenu/Data/IssueInfo.swift index 7cdc59d9ee..2511b33df7 100644 --- a/Amplify/DevMenu/Data/IssueInfo.swift +++ b/Amplify/DevMenu/Data/IssueInfo.swift @@ -76,8 +76,8 @@ struct IssueInfo { return infoNotAvailable } - return items.reduce("") {(description, item) -> String in - return ("\(description)\(item.displayName) - \(item.information) \n") + return items.reduce("") {description, item -> String in + return "\(description)\(item.displayName) - \(item.information) \n" } } } diff --git a/Amplify/DevMenu/Data/LogEntryHelper.swift b/Amplify/DevMenu/Data/LogEntryHelper.swift index bcc8058c58..05fb3769ad 100644 --- a/Amplify/DevMenu/Data/LogEntryHelper.swift +++ b/Amplify/DevMenu/Data/LogEntryHelper.swift @@ -9,7 +9,7 @@ import Foundation /// Helper class to fetch log entry related information -struct LogEntryHelper { +enum LogEntryHelper { /// Date formatter instance for date formatting private static let dateFormatter: DateFormatter = { @@ -26,7 +26,8 @@ struct LogEntryHelper { /// Helper function to fetch logs from `PersistentLoggingPlugin` static func getLogHistory() -> [LogEntryItem] { if let loggingPlugin: PersistentLoggingPlugin = Amplify.Logging.plugins.first(where: { - $0.key == DevMenuStringConstants.persistentLoggingPluginKey})?.value as? PersistentLoggingPlugin { + $0.key == DevMenuStringConstants.persistentLoggingPluginKey + })?.value as? PersistentLoggingPlugin { if let logger: PersistentLogWrapper = loggingPlugin.default as? PersistentLogWrapper { return logger.getLogHistory() } diff --git a/Amplify/DevMenu/Data/PluginInfoHelper.swift b/Amplify/DevMenu/Data/PluginInfoHelper.swift index 47ef76947b..45a66f7e51 100644 --- a/Amplify/DevMenu/Data/PluginInfoHelper.swift +++ b/Amplify/DevMenu/Data/PluginInfoHelper.swift @@ -9,7 +9,7 @@ import Foundation /// Helper class to fetch Amplify plugin information -struct PluginInfoHelper { +enum PluginInfoHelper { static func getPluginInformation() -> [PluginInfoItem] { var pluginList = [PluginInfoItem]() diff --git a/Amplify/DevMenu/DevMenuStringConstants.swift b/Amplify/DevMenu/DevMenuStringConstants.swift index 1ca4c7ed6a..ecdf903d23 100644 --- a/Amplify/DevMenu/DevMenuStringConstants.swift +++ b/Amplify/DevMenu/DevMenuStringConstants.swift @@ -9,7 +9,7 @@ import Foundation /// String constants used in the developer menu -struct DevMenuStringConstants { +enum DevMenuStringConstants { static let notAvailable = "Not available" static let unknownPlugin = "Unknown Plugin" static let versionNotAvailable = "Version not available" diff --git a/Amplify/DevMenu/Trigger/LongPressGestureRecognizer.swift b/Amplify/DevMenu/Trigger/LongPressGestureRecognizer.swift index d08ac4b08d..f7995be191 100644 --- a/Amplify/DevMenu/Trigger/LongPressGestureRecognizer.swift +++ b/Amplify/DevMenu/Trigger/LongPressGestureRecognizer.swift @@ -24,8 +24,10 @@ class LongPressGestureRecognizer: NSObject, TriggerRecognizer, UIGestureRecogniz registerLongPressRecognizer() } - public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, - shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) + public func gestureRecognizer( + _ gestureRecognizer: UIGestureRecognizer, + shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer + ) -> Bool { return true } diff --git a/Amplify/DevMenu/View/DevMenuList.swift b/Amplify/DevMenu/View/DevMenuList.swift index a564792af8..7660ef0b6d 100644 --- a/Amplify/DevMenu/View/DevMenuList.swift +++ b/Amplify/DevMenu/View/DevMenuList.swift @@ -29,7 +29,8 @@ struct DevMenuList: View { } .navigationBarTitle( Text(screenTitle), - displayMode: .inline) + displayMode: .inline + ) }.navigationViewStyle(StackNavigationViewStyle()) } } diff --git a/Amplify/DevMenu/View/InfoRow.swift b/Amplify/DevMenu/View/InfoRow.swift index 77a2fb6c14..0374215d54 100644 --- a/Amplify/DevMenu/View/InfoRow.swift +++ b/Amplify/DevMenu/View/InfoRow.swift @@ -14,8 +14,8 @@ struct InfoRow: View { var body: some View { VStack(alignment: .leading) { - Text(self.infoItem.displayName).bold() - Text(self.infoItem.information) + Text(infoItem.displayName).bold() + Text(infoItem.information) } } } diff --git a/Amplify/DevMenu/View/IssueReporter.swift b/Amplify/DevMenu/View/IssueReporter.swift index bcec472e1a..f231d49129 100644 --- a/Amplify/DevMenu/View/IssueReporter.swift +++ b/Amplify/DevMenu/View/IssueReporter.swift @@ -66,9 +66,11 @@ struct IssueReporter: View { .border(Color.blue) .padding(.bottom) .alert(isPresented: $showAlertIfInvalidURL) { - Alert(title: Text(githubURLErrorTitle), - message: Text(githubURLErrorMessage), - dismissButton: .default(Text("OK"))) + Alert( + title: Text(githubURLErrorTitle), + message: Text(githubURLErrorMessage), + dismissButton: .default(Text("OK")) + ) } .disabled(shouldDisableReporting()) @@ -97,9 +99,11 @@ struct IssueReporter: View { /// Open Amplify iOS issue logging screen on Github private func reportToGithub() { Task { - let issue = await IssueInfo(issueDescription: issueDescription, - includeEnvInfo: includeEnvInfo, - includeDeviceInfo: includeDeviceInfo) + let issue = await IssueInfo( + issueDescription: issueDescription, + includeEnvInfo: includeEnvInfo, + includeDeviceInfo: includeDeviceInfo + ) let issueDescriptionMarkdown = await IssueInfoHelper.generateMarkdownForIssue( issue: issue) @@ -122,9 +126,11 @@ struct IssueReporter: View { /// Copy issue as a markdown string to clipboard private func copyToClipboard() { Task { - let issue = await IssueInfo(issueDescription: issueDescription, - includeEnvInfo: includeEnvInfo, - includeDeviceInfo: includeDeviceInfo) + let issue = await IssueInfo( + issueDescription: issueDescription, + includeEnvInfo: includeEnvInfo, + includeDeviceInfo: includeDeviceInfo + ) let value = await IssueInfoHelper.generateMarkdownForIssue(issue: issue) #if os(iOS) UIPasteboard.general.string = value @@ -164,8 +170,12 @@ final class MultilineTextField: UIViewRepresentable { /// add a dismiss button in UIToolbar for keyboard let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 35)) let emptySpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) - let dismissButton = UIBarButtonItem(title: "Dismiss", style: .done, - target: self, action: #selector(dismissKeyboard)) + let dismissButton = UIBarButtonItem( + title: "Dismiss", + style: .done, + target: self, + action: #selector(dismissKeyboard) + ) toolbar.setItems([emptySpace, dismissButton], animated: false) toolbar.sizeToFit() @@ -175,8 +185,12 @@ final class MultilineTextField: UIViewRepresentable { @MainActor @objc func dismissKeyboard() { - UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), - to: nil, from: nil, for: nil) + UIApplication.shared.sendAction( + #selector(UIResponder.resignFirstResponder), + to: nil, + from: nil, + for: nil + ) } func updateUIView(_ uiView: UITextView, context: Context) { diff --git a/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncExpectation.swift b/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncExpectation.swift index 2746528644..45bb2a9ab6 100644 --- a/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncExpectation.swift +++ b/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncExpectation.swift @@ -35,17 +35,18 @@ public actor AsyncExpectation { } public func setShouldTrigger(_ shouldTrigger: Bool) { - self.isInverted = !shouldTrigger + isInverted = !shouldTrigger } public func setExpectedFulfillmentCount(_ count: Int) { - self.expectedFulfillmentCount = count + expectedFulfillmentCount = count } public init(description: String, isInverted: Bool = false, - expectedFulfillmentCount: Int = 1) { - expectationDescription = description + expectedFulfillmentCount: Int = 1) + { + self.expectationDescription = description self.isInverted = isInverted self.expectedFulfillmentCount = expectedFulfillmentCount } @@ -73,7 +74,7 @@ public actor AsyncExpectation { } } - internal nonisolated func wait() async throws { + nonisolated func wait() async throws { try await withTaskCancellationHandler { try await handleWait() } onCancel: { @@ -83,8 +84,9 @@ public actor AsyncExpectation { } } - internal func timeOut(file: StaticString = #filePath, - line: UInt = #line) async { + func timeOut(file: StaticString = #filePath, + line: UInt = #line) async + { if isInverted { state = .timedOut } else if state != .fulfilled { diff --git a/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncTesting.swift b/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncTesting.swift index 84ca0cbc7d..f557bae458 100644 --- a/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncTesting.swift +++ b/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncTesting.swift @@ -12,7 +12,8 @@ public enum AsyncTesting { public static func expectation(description: String, isInverted: Bool = false, - expectedFulfillmentCount: Int = 1) -> AsyncExpectation { + expectedFulfillmentCount: Int = 1) -> AsyncExpectation + { AsyncExpectation(description: description, isInverted: isInverted, expectedFulfillmentCount: expectedFulfillmentCount) @@ -22,7 +23,8 @@ public enum AsyncTesting { public static func waitForExpectations(_ expectations: [AsyncExpectation], timeout: Double = 1.0, file: StaticString = #filePath, - line: UInt = #line) async { + line: UInt = #line) async + { guard !expectations.isEmpty else { return } // check if all expectations are already satisfied and skip sleeping diff --git a/AmplifyAsyncTesting/Sources/AsyncTesting/XCTestCase+AsyncTesting.swift b/AmplifyAsyncTesting/Sources/AsyncTesting/XCTestCase+AsyncTesting.swift index cce82a21d6..521b0f0382 100644 --- a/AmplifyAsyncTesting/Sources/AsyncTesting/XCTestCase+AsyncTesting.swift +++ b/AmplifyAsyncTesting/Sources/AsyncTesting/XCTestCase+AsyncTesting.swift @@ -8,9 +8,9 @@ import Foundation import XCTest -extension XCTestCase { - public static let defaultTimeoutForAsyncExpectations = TimeInterval(60) - public static let defaultNetworkTimeoutForAsyncExpectations = TimeInterval(600) +public extension XCTestCase { + static let defaultTimeoutForAsyncExpectations = TimeInterval(60) + static let defaultNetworkTimeoutForAsyncExpectations = TimeInterval(600) /// Creates a new async expectation with an associated description. /// @@ -25,9 +25,10 @@ extension XCTestCase { /// - description: A string to display in the test log for this expectation, to help diagnose failures. /// - isInverted: Indicates that the expectation is not intended to happen. /// - expectedFulfillmentCount: The number of times fulfill() must be called before the expectation is completely fulfilled. (default = 1) - public func asyncExpectation(description: String, + func asyncExpectation(description: String, isInverted: Bool = false, - expectedFulfillmentCount: Int = 1) -> AsyncExpectation { + expectedFulfillmentCount: Int = 1) -> AsyncExpectation + { AsyncExpectation(description: description, isInverted: isInverted, expectedFulfillmentCount: expectedFulfillmentCount) @@ -38,10 +39,11 @@ extension XCTestCase { /// - expectations: An array of async expectations that must be fulfilled. /// - timeout: The number of seconds within which all expectations must be fulfilled. @MainActor - public func waitForExpectations(_ expectations: [AsyncExpectation], + func waitForExpectations(_ expectations: [AsyncExpectation], timeout: Double = 1.0, file: StaticString = #filePath, - line: UInt = #line) async { + line: UInt = #line) async + { await AsyncTesting.waitForExpectations(expectations, timeout: timeout, file: file, @@ -54,10 +56,11 @@ extension XCTestCase { /// - operation: operation to run /// - Returns: result of closure @discardableResult - public func testTask(timeout: Double = defaultTimeoutForAsyncExpectations, + func testTask(timeout: Double = defaultTimeoutForAsyncExpectations, file: StaticString = #filePath, line: UInt = #line, - @_implicitSelfCapture operation: @escaping @Sendable () async throws -> Success) async throws -> Success { + @_implicitSelfCapture operation: @escaping @Sendable () async throws -> Success) async throws -> Success + { let done = asyncExpectation(description: "done") let task = Task { () -> Success in @@ -84,9 +87,10 @@ extension XCTestCase { /// /// - Returns:The result of successfuly running `action`, or `nil` if it threw an error. @discardableResult - func wait(with expectation: AsyncExpectation, + internal func wait(with expectation: AsyncExpectation, timeout: TimeInterval = defaultNetworkTimeoutForAsyncExpectations, - action: @escaping () async throws -> T) async -> T? { + action: @escaping () async throws -> T) async -> T? + { let task = Task { () -> T? in defer { Task { @@ -116,9 +120,10 @@ extension XCTestCase { /// /// - Returns:The result of successfuly running `action`, or `nil` if it threw an error. @discardableResult - func wait(name: String, + internal func wait(name: String, timeout: TimeInterval = defaultNetworkTimeoutForAsyncExpectations, - action: @escaping () async throws -> T) async -> T? { + action: @escaping () async throws -> T) async -> T? + { let expectation = asyncExpectation(description: name) return await wait(with: expectation, timeout: timeout, action: action) } @@ -136,9 +141,10 @@ extension XCTestCase { /// /// - Returns:The error thrown during the execution of `action`, or `nil` if it run successfully. @discardableResult - func waitError(with expectation: AsyncExpectation, + internal func waitError(with expectation: AsyncExpectation, timeout: TimeInterval = defaultNetworkTimeoutForAsyncExpectations, - action: @escaping () async throws -> T) async -> Error? { + action: @escaping () async throws -> T) async -> Error? + { let task = Task { () -> Error? in defer { Task { await expectation.fulfill() } @@ -170,9 +176,10 @@ extension XCTestCase { /// /// - Returns:The error thrown during the execution of `action`, or `nil` if it run successfully. @discardableResult - func waitError(name: String, + internal func waitError(name: String, timeout: TimeInterval = defaultNetworkTimeoutForAsyncExpectations, - action: @escaping () async throws -> T) async -> Error? { + action: @escaping () async throws -> T) async -> Error? + { let expectation = asyncExpectation(description: name) return await waitError(with: expectation, timeout: timeout, action: action) } diff --git a/AmplifyFunctionalTests/AmplifyConfigurationInitFromFileTests.swift b/AmplifyFunctionalTests/AmplifyConfigurationInitFromFileTests.swift index dfa4039a44..808aec3d14 100644 --- a/AmplifyFunctionalTests/AmplifyConfigurationInitFromFileTests.swift +++ b/AmplifyFunctionalTests/AmplifyConfigurationInitFromFileTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest /// Test the public AmplifyConfiguration initializer. Note that this means we must not import /// Amplify as `@testable`. That means we cannot `await Amplify.reset()`, which means we can only have diff --git a/AmplifyFunctionalTests/Hub/DefaultHubPluginPerformanceTestHelpers.swift b/AmplifyFunctionalTests/Hub/DefaultHubPluginPerformanceTestHelpers.swift index f112b834eb..edd87f2bf5 100644 --- a/AmplifyFunctionalTests/Hub/DefaultHubPluginPerformanceTestHelpers.swift +++ b/AmplifyFunctionalTests/Hub/DefaultHubPluginPerformanceTestHelpers.swift @@ -9,11 +9,12 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon -struct DefaultHubPluginPerformanceTestHelpers { +enum DefaultHubPluginPerformanceTestHelpers { - static func makeTestObjectsForSingleChannel(listenerCount: Int, - dispatcherType: T.Type, - testCase: XCTestCase) -> PerformanceTestObjects { + static func makeTestObjectsForSingleChannel(listenerCount: Int, + dispatcherType: (some Dispatcher).Type, + testCase: XCTestCase) -> PerformanceTestObjects + { let dispatcherChannels = [HubChannel.storage] let listenerChannels = [HubChannel.storage] @@ -28,9 +29,10 @@ struct DefaultHubPluginPerformanceTestHelpers { testCase: testCase) } - static func makeTestObjectsForSingleDispatcher(listenerCount: Int, - dispatcherType: T.Type, - testCase: XCTestCase) -> PerformanceTestObjects { + static func makeTestObjectsForSingleDispatcher(listenerCount: Int, + dispatcherType: (some Dispatcher).Type, + testCase: XCTestCase) -> PerformanceTestObjects + { let dispatcherChannels = [HubChannel.storage] let listenerChannels = [HubChannel.storage, @@ -49,9 +51,10 @@ struct DefaultHubPluginPerformanceTestHelpers { testCase: testCase) } - static func makeTestObjectsForMultipleDispatchers(listenerCount: Int, - dispatcherType: T.Type, - testCase: XCTestCase) -> PerformanceTestObjects { + static func makeTestObjectsForMultipleDispatchers(listenerCount: Int, + dispatcherType: (some Dispatcher).Type, + testCase: XCTestCase) -> PerformanceTestObjects + { let dispatcherChannels = [HubChannel.storage, .custom("CustomChannel1")] let listenerChannels = [HubChannel.storage, @@ -71,12 +74,13 @@ struct DefaultHubPluginPerformanceTestHelpers { } // swiftlint:disable:next function_parameter_count - static func makeTestObjectsForDispatcherTypes(listenerCount: Int, + static func makeTestObjectsForDispatcherTypes(listenerCount: Int, listenerChannels: [HubChannel], - dispatcherType: T.Type, + dispatcherType: (some Dispatcher).Type, dispatcherChannels: [HubChannel], expectedChannels: [HubChannel], - testCase: XCTestCase) -> PerformanceTestObjects { + testCase: XCTestCase) -> PerformanceTestObjects + { var dispatchers = [Dispatcher]() for channel in dispatcherChannels { @@ -115,7 +119,8 @@ struct DefaultHubPluginPerformanceTestHelpers { static func makeListeners(count: Int, for channels: [HubChannel], expectedChannels: [HubChannel], - testCase: XCTestCase) -> ([FilteredListener], [XCTestExpectation]) { + testCase: XCTestCase) -> ([FilteredListener], [XCTestExpectation]) + { var listeners = [FilteredListener]() var expectations = [XCTestExpectation]() diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+APIAuthProviderFactoryBehavior.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+APIAuthProviderFactoryBehavior.swift index d4b8f1a683..2349059fb7 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+APIAuthProviderFactoryBehavior.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+APIAuthProviderFactoryBehavior.swift @@ -8,8 +8,8 @@ import Amplify import Foundation -extension AWSAPIPlugin { - public func apiAuthProviderFactory() -> APIAuthProviderFactory { +public extension AWSAPIPlugin { + func apiAuthProviderFactory() -> APIAuthProviderFactory { return authProviderFactory } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+AuthInformation.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+AuthInformation.swift index 8def8d268a..f2e2c5dfa1 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+AuthInformation.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+AuthInformation.swift @@ -9,12 +9,12 @@ import Amplify import AWSPluginsCore import Foundation -extension AWSAPIPlugin { - public func defaultAuthType() throws -> AWSAuthorizationType { +public extension AWSAPIPlugin { + func defaultAuthType() throws -> AWSAuthorizationType { try defaultAuthType(for: nil) } - public func defaultAuthType(for apiName: String?) throws -> AWSAuthorizationType { + func defaultAuthType(for apiName: String?) throws -> AWSAuthorizationType { try pluginConfig.endpoints.getConfig(for: apiName).authorizationType } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+Configure.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+Configure.swift index e63ed08dcb..31f85afb79 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+Configure.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+Configure.swift @@ -6,9 +6,9 @@ // @_spi(InternalAmplifyConfiguration) import Amplify +import AwsCommonRuntimeKit import AWSPluginsCore import InternalAmplifyCredentials -import AwsCommonRuntimeKit public extension AWSAPIPlugin { @@ -22,11 +22,15 @@ public extension AWSAPIPlugin { func configure(using configuration: Any?) throws { let dependencies: ConfigurationDependencies if let configuration = configuration as? AmplifyOutputsData { - dependencies = try ConfigurationDependencies(configuration: configuration, - apiAuthProviderFactory: authProviderFactory) + dependencies = try ConfigurationDependencies( + configuration: configuration, + apiAuthProviderFactory: authProviderFactory + ) } else if let jsonValue = configuration as? JSONValue { - dependencies = try ConfigurationDependencies(configurationValues: jsonValue, - apiAuthProviderFactory: authProviderFactory) + dependencies = try ConfigurationDependencies( + configurationValues: jsonValue, + apiAuthProviderFactory: authProviderFactory + ) } else { throw PluginError.pluginConfigurationError( diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+GraphQLBehavior.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+GraphQLBehavior.swift index ae2d999245..78f25677c6 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+GraphQLBehavior.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+GraphQLBehavior.swift @@ -9,45 +9,57 @@ import Amplify public extension AWSAPIPlugin { - func query(request: GraphQLRequest, - listener: GraphQLOperation.ResultListener?) -> GraphQLOperation { - let operation = AWSGraphQLOperation(request: request.toOperationRequest(operationType: .query), - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: listener) + func query( + request: GraphQLRequest, + listener: GraphQLOperation.ResultListener? + ) -> GraphQLOperation { + let operation = AWSGraphQLOperation( + request: request.toOperationRequest(operationType: .query), + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: listener + ) queue.addOperation(operation) return operation } func query(request: GraphQLRequest) async throws -> GraphQLTask.Success { - let operation = AWSGraphQLOperation(request: request.toOperationRequest(operationType: .query), - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: nil) + let operation = AWSGraphQLOperation( + request: request.toOperationRequest(operationType: .query), + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: nil + ) let task = AmplifyOperationTaskAdapter(operation: operation) queue.addOperation(operation) return try await task.value } - func mutate(request: GraphQLRequest, - listener: GraphQLOperation.ResultListener?) -> GraphQLOperation { - let operation = AWSGraphQLOperation(request: request.toOperationRequest(operationType: .mutation), - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: listener) + func mutate( + request: GraphQLRequest, + listener: GraphQLOperation.ResultListener? + ) -> GraphQLOperation { + let operation = AWSGraphQLOperation( + request: request.toOperationRequest(operationType: .mutation), + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: listener + ) queue.addOperation(operation) return operation } func mutate(request: GraphQLRequest) async throws -> GraphQLTask.Success { - let operation = AWSGraphQLOperation(request: request.toOperationRequest(operationType: .mutation), - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: nil) + let operation = AWSGraphQLOperation( + request: request.toOperationRequest(operationType: .mutation), + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: nil + ) let task = AmplifyOperationTaskAdapter(operation: operation) queue.addOperation(operation) return try await task.value @@ -65,18 +77,21 @@ public extension AWSAPIPlugin { authService: authService, apiAuthProviderFactory: authProviderFactory, inProcessListener: valueListener, - resultListener: completionListener) + resultListener: completionListener + ) queue.addOperation(operation) return operation } func subscribe(request: GraphQLRequest) -> AmplifyAsyncThrowingSequence> { let request = request.toOperationRequest(operationType: .subscription) - let runner = AWSGraphQLSubscriptionTaskRunner(request: request, - pluginConfig: pluginConfig, - appSyncClientFactory: appSyncRealTimeClientFactory, - authService: authService, - apiAuthProviderFactory: authProviderFactory) + let runner = AWSGraphQLSubscriptionTaskRunner( + request: request, + pluginConfig: pluginConfig, + appSyncClientFactory: appSyncRealTimeClientFactory, + authService: authService, + apiAuthProviderFactory: authProviderFactory + ) return runner.sequence } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+InterceptorBehavior.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+InterceptorBehavior.swift index 98c8b6df96..46f10d5216 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+InterceptorBehavior.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+InterceptorBehavior.swift @@ -10,8 +10,10 @@ import Amplify public extension AWSAPIPlugin { func add(interceptor: URLRequestInterceptor, for apiName: String) throws { guard pluginConfig.endpoints[apiName] != nil else { - throw PluginError.pluginConfigurationError("Failed to get endpoint configuration for apiName: \(apiName)", - "") + throw PluginError.pluginConfigurationError( + "Failed to get endpoint configuration for apiName: \(apiName)", + "" + ) } pluginConfig.addInterceptor(interceptor, toEndpoint: apiName) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+RESTBehavior.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+RESTBehavior.swift index 59642d79c0..ab5ce8980a 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+RESTBehavior.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+RESTBehavior.swift @@ -11,28 +11,36 @@ import Foundation public extension AWSAPIPlugin { func get(request: RESTRequest, listener: RESTOperation.ResultListener?) -> RESTOperation { - let operationRequest = RESTOperationRequest(request: request, - operationType: .get) - - let operation = AWSRESTOperation(request: operationRequest, - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: listener) + let operationRequest = RESTOperationRequest( + request: request, + operationType: .get + ) + + let operation = AWSRESTOperation( + request: operationRequest, + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: listener + ) queue.addOperation(operation) return operation } func get(request: RESTRequest) async throws -> RESTTask.Success { - let operationRequest = RESTOperationRequest(request: request, - operationType: .get) - - let operation = AWSRESTOperation(request: operationRequest, - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: nil) + let operationRequest = RESTOperationRequest( + request: request, + operationType: .get + ) + + let operation = AWSRESTOperation( + request: operationRequest, + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: nil + ) let task = AmplifyOperationTaskAdapter(operation: operation) queue.addOperation(operation) @@ -40,28 +48,36 @@ public extension AWSAPIPlugin { } func put(request: RESTRequest, listener: RESTOperation.ResultListener?) -> RESTOperation { - let operationRequest = RESTOperationRequest(request: request, - operationType: .put) - - let operation = AWSRESTOperation(request: operationRequest, - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: listener) + let operationRequest = RESTOperationRequest( + request: request, + operationType: .put + ) + + let operation = AWSRESTOperation( + request: operationRequest, + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: listener + ) queue.addOperation(operation) return operation } func put(request: RESTRequest) async throws -> RESTTask.Success { - let operationRequest = RESTOperationRequest(request: request, - operationType: .put) - - let operation = AWSRESTOperation(request: operationRequest, - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: nil) + let operationRequest = RESTOperationRequest( + request: request, + operationType: .put + ) + + let operation = AWSRESTOperation( + request: operationRequest, + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: nil + ) let task = AmplifyOperationTaskAdapter(operation: operation) queue.addOperation(operation) @@ -69,28 +85,36 @@ public extension AWSAPIPlugin { } func post(request: RESTRequest, listener: RESTOperation.ResultListener?) -> RESTOperation { - let operationRequest = RESTOperationRequest(request: request, - operationType: .post) - - let operation = AWSRESTOperation(request: operationRequest, - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: listener) + let operationRequest = RESTOperationRequest( + request: request, + operationType: .post + ) + + let operation = AWSRESTOperation( + request: operationRequest, + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: listener + ) queue.addOperation(operation) return operation } func post(request: RESTRequest) async throws -> RESTTask.Success { - let operationRequest = RESTOperationRequest(request: request, - operationType: .post) - - let operation = AWSRESTOperation(request: operationRequest, - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: nil) + let operationRequest = RESTOperationRequest( + request: request, + operationType: .post + ) + + let operation = AWSRESTOperation( + request: operationRequest, + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: nil + ) let task = AmplifyOperationTaskAdapter(operation: operation) queue.addOperation(operation) @@ -100,11 +124,13 @@ public extension AWSAPIPlugin { func patch(request: RESTRequest, listener: RESTOperation.ResultListener?) -> RESTOperation { let operationRequest = RESTOperationRequest(request: request, operationType: .patch) - let operation = AWSRESTOperation(request: operationRequest, - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: listener) + let operation = AWSRESTOperation( + request: operationRequest, + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: listener + ) queue.addOperation(operation) return operation @@ -113,11 +139,13 @@ public extension AWSAPIPlugin { func patch(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .patch) - let operation = AWSRESTOperation(request: operationRequest, - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: nil) + let operation = AWSRESTOperation( + request: operationRequest, + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: nil + ) let task = AmplifyOperationTaskAdapter(operation: operation) queue.addOperation(operation) @@ -125,28 +153,36 @@ public extension AWSAPIPlugin { } func delete(request: RESTRequest, listener: RESTOperation.ResultListener?) -> RESTOperation { - let operationRequest = RESTOperationRequest(request: request, - operationType: .delete) - - let operation = AWSRESTOperation(request: operationRequest, - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: listener) + let operationRequest = RESTOperationRequest( + request: request, + operationType: .delete + ) + + let operation = AWSRESTOperation( + request: operationRequest, + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: listener + ) queue.addOperation(operation) return operation } func delete(request: RESTRequest) async throws -> RESTTask.Success { - let operationRequest = RESTOperationRequest(request: request, - operationType: .delete) - - let operation = AWSRESTOperation(request: operationRequest, - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: nil) + let operationRequest = RESTOperationRequest( + request: request, + operationType: .delete + ) + + let operation = AWSRESTOperation( + request: operationRequest, + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: nil + ) let task = AmplifyOperationTaskAdapter(operation: operation) queue.addOperation(operation) @@ -154,28 +190,36 @@ public extension AWSAPIPlugin { } func head(request: RESTRequest, listener: RESTOperation.ResultListener?) -> RESTOperation { - let operationRequest = RESTOperationRequest(request: request, - operationType: .head) - - let operation = AWSRESTOperation(request: operationRequest, - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: listener) + let operationRequest = RESTOperationRequest( + request: request, + operationType: .head + ) + + let operation = AWSRESTOperation( + request: operationRequest, + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: listener + ) queue.addOperation(operation) return operation } func head(request: RESTRequest) async throws -> RESTTask.Success { - let operationRequest = RESTOperationRequest(request: request, - operationType: .head) - - let operation = AWSRESTOperation(request: operationRequest, - session: session, - mapper: mapper, - pluginConfig: pluginConfig, - resultListener: nil) + let operationRequest = RESTOperationRequest( + request: request, + operationType: .head + ) + + let operation = AWSRESTOperation( + request: operationRequest, + session: session, + mapper: mapper, + pluginConfig: pluginConfig, + resultListener: nil + ) let task = AmplifyOperationTaskAdapter(operation: operation) queue.addOperation(operation) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+Reachability.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+Reachability.swift index 777d6a0767..19acb2d3b1 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+Reachability.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+Reachability.swift @@ -6,18 +6,19 @@ // import Amplify -import Foundation import Combine +import Foundation -extension AWSAPIPlugin { - public func reachabilityPublisher() throws -> AnyPublisher? { +public extension AWSAPIPlugin { + func reachabilityPublisher() throws -> AnyPublisher? { return try reachabilityPublisher(for: nil) } - public func reachabilityPublisher(for apiName: String?) throws -> AnyPublisher? { + func reachabilityPublisher(for apiName: String?) throws -> AnyPublisher? { let endpoint = try pluginConfig.endpoints.getConfig(for: apiName) guard let hostName = endpoint.baseURL.host else { - let error = APIError.invalidConfiguration("Invalid endpoint configuration", + let error = APIError.invalidConfiguration( + "Invalid endpoint configuration", """ baseURL does not contain a valid hostname """ @@ -30,9 +31,11 @@ extension AWSAPIPlugin { return networkReachability.publisher } do { - let networkReachability = try NetworkReachabilityNotifier(host: hostName, - allowsCellularAccess: true, - reachabilityFactory: AmplifyReachability.self) + let networkReachability = try NetworkReachabilityNotifier( + host: hostName, + allowsCellularAccess: true, + reachabilityFactory: AmplifyReachability.self + ) reachabilityMap[hostName] = networkReachability return networkReachability.publisher } catch { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+URLSessionBehaviorDelegate.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+URLSessionBehaviorDelegate.swift index 7833a5ce9a..9bcb3f8fbb 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+URLSessionBehaviorDelegate.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+URLSessionBehaviorDelegate.swift @@ -8,15 +8,19 @@ import Foundation extension AWSAPIPlugin: URLSessionBehaviorDelegate { - public func urlSessionBehavior(_ session: URLSessionBehavior, - dataTaskBehavior: URLSessionDataTaskBehavior, - didCompleteWithError error: Error?) { + public func urlSessionBehavior( + _ session: URLSessionBehavior, + dataTaskBehavior: URLSessionDataTaskBehavior, + didCompleteWithError error: Error? + ) { mapper.operation(for: dataTaskBehavior)?.complete(with: error, response: dataTaskBehavior.taskBehaviorResponse) } - public func urlSessionBehavior(_ session: URLSessionBehavior, - dataTaskBehavior: URLSessionDataTaskBehavior, - didReceive data: Data) { + public func urlSessionBehavior( + _ session: URLSessionBehavior, + dataTaskBehavior: URLSessionDataTaskBehavior, + didReceive data: Data + ) { mapper.operation(for: dataTaskBehavior)?.updateProgress(data, response: dataTaskBehavior.taskBehaviorResponse) } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+URLSessionDelegate.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+URLSessionDelegate.swift index dd7fe7e8e7..4a5c916de3 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+URLSessionDelegate.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+URLSessionDelegate.swift @@ -10,28 +10,36 @@ import Foundation public typealias AuthChallengeDispositionHandler = (URLSession.AuthChallengeDisposition, URLCredential?) -> Void extension AWSAPIPlugin: URLSessionDelegate { - @objc public func urlSession(_ session: URLSession, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping AuthChallengeDispositionHandler) { + @objc public func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping AuthChallengeDispositionHandler + ) { completionHandler(.performDefaultHandling, nil) } } extension AWSAPIPlugin: URLSessionTaskDelegate { - @objc public func urlSession(_ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping AuthChallengeDispositionHandler) { + @objc public func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping AuthChallengeDispositionHandler + ) { completionHandler(.performDefaultHandling, nil) } - @objc public func urlSession(_ session: URLSession, - task: URLSessionTask, - didCompleteWithError error: Error?) { - urlSessionBehavior(session, - dataTaskBehavior: task, - didCompleteWithError: error) + @objc public func urlSession( + _ session: URLSession, + task: URLSessionTask, + didCompleteWithError error: Error? + ) { + urlSessionBehavior( + session, + dataTaskBehavior: task, + didCompleteWithError: error + ) } @@ -45,11 +53,15 @@ extension AWSAPIPlugin: URLSessionDataDelegate { // completionHandler(.allow) // } - @objc public func urlSession(_ session: URLSession, - dataTask: URLSessionDataTask, - didReceive data: Data) { - urlSessionBehavior(session, - dataTaskBehavior: dataTask, - didReceive: data) + @objc public func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive data: Data + ) { + urlSessionBehavior( + session, + dataTaskBehavior: dataTask, + didReceive: data + ) } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin.swift index dcdcd7095a..52fee625ae 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin.swift @@ -7,10 +7,10 @@ import Amplify import AWSPluginsCore -import InternalAmplifyCredentials import Foundation +import InternalAmplifyCredentials -final public class AWSAPIPlugin: NSObject, APICategoryPlugin, AWSAPIAuthInformation { +public final class AWSAPIPlugin: NSObject, APICategoryPlugin, AWSAPIAuthInformation { /// Used for the default GraphQL API represented by the `data` category in `amplify_outputs.json` /// This constant is not used for APIs present in `amplifyconfiguration.json` since they always have names. public static let defaultGraphQLAPI = "defaultGraphQLAPI" diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeClient+HandleRequest.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeClient+HandleRequest.swift index 63842c547b..2d51cad30f 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeClient+HandleRequest.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeClient+HandleRequest.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation -import Combine import Amplify +import Combine +import Foundation extension AppSyncRealTimeClient { /** @@ -31,7 +30,7 @@ extension AppSyncRealTimeClient { } // listen to response - self.subject + subject .setFailureType(to: AppSyncRealTimeRequest.Error.self) .flatMap { Self.filterResponse(request: request, result: $0) } .timeout(.seconds(timeout), scheduler: DispatchQueue.global(qos: .userInitiated), customError: { .timeout }) @@ -53,7 +52,7 @@ extension AppSyncRealTimeClient { event: request, url: self.endpoint ) - let requestJSON = String(data: try Self.jsonEncoder.encode(decoratedRequest), encoding: .utf8) + let requestJSON = try String(data: Self.jsonEncoder.encode(decoratedRequest), encoding: .utf8) try await self.webSocketClient.write(message: requestJSON!) } catch { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeClient.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeClient.swift index 7f3d75abbc..75dc72633a 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeClient.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeClient.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Amplify import Combine +import Foundation @_spi(WebSocket) import AWSPluginsCore /** @@ -41,21 +40,21 @@ actor AppSyncRealTimeClient: AppSyncRealTimeClientProtocol { private var cancellablesBindToConnection = Set() /// AppSync RealTime server endpoint - internal let endpoint: URL + let endpoint: URL /// Interceptor for decorating AppSyncRealTimeRequest - internal let requestInterceptor: AppSyncRequestInterceptor + let requestInterceptor: AppSyncRequestInterceptor /// WebSocketClient offering connections at the WebSocket protocol level - internal var webSocketClient: AppSyncWebSocketClientProtocol + var webSocketClient: AppSyncWebSocketClientProtocol /// Writable data stream convert WebSocketEvent to AppSyncRealTimeResponse - internal let subject = PassthroughSubject, Never>() + let subject = PassthroughSubject, Never>() var isConnected: Bool { - self.state.value == .connected + state.value == .connected } - internal var numberOfSubscriptions: Int { - self.subscriptions.count + var numberOfSubscriptions: Int { + subscriptions.count } /** @@ -89,7 +88,7 @@ actor AppSyncRealTimeClient: AppSyncRealTimeClientProtocol { Connecting to remote AppSync real-time server. */ func connect() async throws { - switch self.state.value { + switch state.value { case .connecting, .connected: log.debug("[AppSyncRealTimeClient] client is already connecting or connected") return @@ -99,12 +98,12 @@ actor AppSyncRealTimeClient: AppSyncRealTimeClientProtocol { break } - guard self.state.value != .connecting else { + guard state.value != .connecting else { log.debug("[AppSyncRealTimeClient] actor reentry, state has been changed to connecting") return } - self.state.send(.connecting) + state.send(.connecting) log.debug("[AppSyncRealTimeClient] client start connecting") try await RetryWithJitter.execute { [weak self] in @@ -121,7 +120,7 @@ actor AppSyncRealTimeClient: AppSyncRealTimeClientProtocol { Disconnect only when there are no subscriptions exist. */ func disconnectWhenIdel() async { - if self.subscriptions.isEmpty { + if subscriptions.isEmpty { log.debug("[AppSyncRealTimeClient] no subscription exist, client is trying to disconnect") await disconnect() } else { @@ -133,7 +132,7 @@ actor AppSyncRealTimeClient: AppSyncRealTimeClientProtocol { Disconnect from AppSync real-time server. */ func disconnect() async { - guard self.state.value != .disconnecting else { + guard state.value != .disconnecting else { log.debug("[AppSyncRealTimeClient] client already disconnecting") return } @@ -141,9 +140,9 @@ actor AppSyncRealTimeClient: AppSyncRealTimeClientProtocol { defer { self.state.send(.disconnected) } log.debug("[AppSyncRealTimeClient] client start disconnecting") - self.state.send(.disconnecting) - self.cancellablesBindToConnection = Set() - await self.webSocketClient.disconnect() + state.send(.disconnecting) + cancellablesBindToConnection = Set() + await webSocketClient.disconnect() log.debug("[AppSyncRealTimeClient] client is disconnected") } @@ -171,7 +170,7 @@ actor AppSyncRealTimeClient: AppSyncRealTimeClientProtocol { try await connect() try await waitForState(.connected) } - await self.storeInConnectionCancellables(try await self.startSubscription(id)) + try await self.storeInConnectionCancellables(await self.startSubscription(id)) } self.storeInConnectionCancellables(task.toAnyCancellable) } @@ -184,7 +183,7 @@ actor AppSyncRealTimeClient: AppSyncRealTimeClientProtocol { private func waitForState(_ targetState: State) async throws { var cancellables = Set() - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) -> Void in + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in state.filter { $0 == targetState } .setFailureType(to: AppSyncRealTimeRequest.Error.self) .timeout(.seconds(10), scheduler: DispatchQueue.global()) @@ -237,7 +236,7 @@ actor AppSyncRealTimeClient: AppSyncRealTimeClientProtocol { } private func subscribeToWebSocketEvent() async { - let cancellable = await self.webSocketClient.publisher.sink { [weak self] _ in + let cancellable = await webSocketClient.publisher.sink { [weak self] _ in self?.log.debug("[AppSyncRealTimeClient] WebSocketClient terminated") } receiveValue: { webSocketEvent in Task { [weak self] in @@ -247,12 +246,12 @@ actor AppSyncRealTimeClient: AppSyncRealTimeClientProtocol { await self?.storeInCancellables(task.toAnyCancellable) } } - self.storeInCancellables(cancellable) + storeInCancellables(cancellable) } private func resumeExistingSubscriptions() { log.debug("[AppSyncRealTimeClient] Resuming existing subscriptions") - for (id, _) in self.subscriptions { + for (id, _) in subscriptions { Task { [weak self] in do { if let cancellable = try await self?.startSubscription(id) { @@ -266,13 +265,13 @@ actor AppSyncRealTimeClient: AppSyncRealTimeClientProtocol { } - nonisolated private func writeAppSyncEvent(_ event: AppSyncRealTimeRequest) async throws { - guard await self.webSocketClient.isConnected else { + private nonisolated func writeAppSyncEvent(_ event: AppSyncRealTimeRequest) async throws { + guard await webSocketClient.isConnected else { log.debug("[AppSyncRealTimeClient] Attempting to write to a webSocket haven't been connected.") return } - let interceptedEvent = await self.requestInterceptor.interceptRequest(event: event, url: self.endpoint) + let interceptedEvent = await requestInterceptor.interceptRequest(event: event, url: endpoint) let eventString = try String(data: Self.jsonEncoder.encode(interceptedEvent), encoding: .utf8)! log.debug("[AppSyncRealTimeClient] Writing AppSyncEvent \(eventString)") try await webSocketClient.write(message: eventString) @@ -365,7 +364,7 @@ extension AppSyncRealTimeClient { switch event { case .connected: log.debug("[AppSyncRealTimeClient] WebSocket connected") - if self.state.value == .connectionDropped { + if state.value == .connectionDropped { log.debug("[AppSyncRealTimeClient] reconnecting appSyncClient after connection drop") Task { [weak self] in let task = Task { [weak self] in @@ -377,15 +376,15 @@ extension AppSyncRealTimeClient { case let .disconnected(closeCode, reason): // log.debug("[AppSyncRealTimeClient] WebSocket disconnected with closeCode: \(closeCode), reason: \(String(describing: reason))") - if self.state.value != .disconnecting || self.state.value != .disconnected { - self.state.send(.connectionDropped) + if state.value != .disconnecting || state.value != .disconnected { + state.send(.connectionDropped) } - self.cancellablesBindToConnection = Set() + cancellablesBindToConnection = Set() case .error(let error): // Propagate connection error to downstream for Sync engine to restart log.debug("[AppSyncRealTimeClient] WebSocket error event: \(error)") - self.subject.send(.failure(error)) + subject.send(.failure(error)) case .string(let string): guard let data = string.data(using: .utf8) else { log.debug("[AppSyncRealTimeClient] Failed to decode string \(string)") @@ -395,14 +394,14 @@ extension AppSyncRealTimeClient { log.debug("[AppSyncRealTimeClient] Failed to decode string to AppSync event") return } - self.onAppSyncRealTimeResponse(response) + onAppSyncRealTimeResponse(response) case .data(let data): guard let response = try? Self.jsonDecoder.decode(AppSyncRealTimeResponse.self, from: data) else { log.debug("[AppSyncRealTimeClient] Failed to decode data to AppSync event") return } - self.onAppSyncRealTimeResponse(response) + onAppSyncRealTimeResponse(response) } } @@ -417,12 +416,12 @@ extension AppSyncRealTimeClient { log.debug("[AppSyncRealTimeClient] AppSync connected: \(String(describing: event.payload))") subject.send(.success(event)) - self.resumeExistingSubscriptions() - self.state.send(.connected) - self.monitorHeartBeats(event.payload) + resumeExistingSubscriptions() + state.send(.connected) + monitorHeartBeats(event.payload) case .keepAlive: - self.heartBeats.send(()) + heartBeats.send(()) default: log.debug("[AppSyncRealTimeClient] AppSync received response: \(event)") @@ -445,7 +444,7 @@ extension AppSyncRealTimeClient { await self?.storeInCancellables(task.toAnyCancellable) } }) - self.storeInConnectionCancellables(cancellable) + storeInConnectionCancellables(cancellable) // start counting down heartBeats.send(()) } @@ -453,17 +452,17 @@ extension AppSyncRealTimeClient { extension AppSyncRealTimeClient { private func storeInCancellables(_ cancellable: AnyCancellable) { - self.cancellables.insert(cancellable) + cancellables.insert(cancellable) } private func storeInConnectionCancellables(_ cancellable: AnyCancellable) { - self.cancellablesBindToConnection.insert(cancellable) + cancellablesBindToConnection.insert(cancellable) } } extension Publisher where Output == AppSyncRealTimeSubscription.State, Failure == Never { func toAppSyncSubscriptionEventStream() -> AnyPublisher { - self.compactMap { subscriptionState -> AppSyncSubscriptionEvent? in + compactMap { subscriptionState -> AppSyncSubscriptionEvent? in switch subscriptionState { case .subscribing: return .subscribing case .subscribed: return .subscribed @@ -495,7 +494,7 @@ extension AppSyncRealTimeClient: Resettable { } } -fileprivate extension Task { +private extension Task { var toAnyCancellable: AnyCancellable { AnyCancellable { if !self.isCancelled { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeRequest.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeRequest.swift index 19599820b4..b9fcf581b9 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeRequest.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeRequest.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation -import Combine import Amplify +import Combine +import Foundation public enum AppSyncRealTimeRequest { case connectionInit @@ -70,8 +69,8 @@ extension AppSyncRealTimeRequest: Encodable { } -extension AppSyncRealTimeRequest { - public enum Error: Swift.Error, Equatable { +public extension AppSyncRealTimeRequest { + enum Error: Swift.Error, Equatable { case timeout case limitExceeded case maxSubscriptionsReached @@ -99,7 +98,7 @@ extension AppSyncRealTimeRequest { } - public static func parseResponseError( + static func parseResponseError( error: JSONValue ) -> AppSyncRealTimeRequest.Error? { let limitExceededErrorString = "LimitExceededError" diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeRequestAuth.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeRequestAuth.swift index f649c3c380..37d077583d 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeRequestAuth.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeRequestAuth.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation public enum AppSyncRealTimeRequestAuth { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeResponse.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeResponse.swift index dfec371035..cc710b0bc9 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeResponse.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeResponse.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public struct AppSyncRealTimeResponse { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeSubscription.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeSubscription.swift index d7e4c6ef42..b840af80cb 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeSubscription.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRealTimeSubscription.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation -import Combine import Amplify +import Combine +import Foundation @_spi(WebSocket) import AWSPluginsCore /** @@ -51,58 +50,58 @@ actor AppSyncRealTimeSubscription { } func subscribe() async throws { - guard self.state.value != .subscribing else { + guard state.value != .subscribing else { log.debug("[AppSyncRealTimeSubscription-\(id)] Subscription already in subscribing state") return } - guard self.state.value != .subscribed else { + guard state.value != .subscribed else { log.debug("[AppSyncRealTimeSubscription-\(id)] Subscription already in subscribed state") return } log.debug("[AppSyncRealTimeSubscription-\(id)] Start subscribing") - self.state.send(.subscribing) + state.send(.subscribing) do { try await RetryWithJitter.execute(shouldRetryOnError: { error in (error as? AppSyncRealTimeRequest.Error) == .maxSubscriptionsReached }) { [weak self] in guard let self else { return } - try await self.appSyncRealTimeClient?.sendRequest( - .start(.init(id: self.id, data: self.query, auth: nil)) + try await appSyncRealTimeClient?.sendRequest( + .start(.init(id: id, data: query, auth: nil)) ) } } catch { log.debug("[AppSyncRealTimeSubscription-\(id)] Failed to subscribe, error: \(error)") - self.state.send(.failure) + state.send(.failure) throw error } log.debug("[AppSyncRealTimeSubscription-\(id)] Subscribed") - self.state.send(.subscribed) + state.send(.subscribed) } func unsubscribe() async throws { - guard self.state.value == .subscribed else { + guard state.value == .subscribed else { log.debug("[AppSyncRealTimeSubscription-\(id)] Subscription should be subscribed to be unsubscribed") return } log.debug("[AppSyncRealTimeSubscription-\(id)] Unsubscribing") - self.state.send(.unsubscribing) + state.send(.unsubscribing) do { let request = AppSyncRealTimeRequest.stop(id) try await appSyncRealTimeClient?.sendRequest(request) } catch { log.debug("[AppSyncRealTimeSubscription-\(id)] Failed to unsubscribe, error \(error)") - self.state.send(.failure) + state.send(.failure) throw error } log.debug("[AppSyncRealTimeSubscription-\(id)] Unsubscribed") - self.state.send(.unsubscribed) + state.send(.unsubscribed) } private static func sendAppSyncRealTimeRequest( @@ -110,7 +109,7 @@ actor AppSyncRealTimeSubscription { with webSocketClient: AppSyncWebSocketClientProtocol ) async throws { guard let requestJson = try String( - data: Self.jsonEncoder.encode(request), + data: jsonEncoder.encode(request), encoding: .utf8 ) else { return diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRequestInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRequestInterceptor.swift index 92414ea28c..36e354ee57 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRequestInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncRequestInterceptor.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation protocol AppSyncRequestInterceptor { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncSubscriptionEvent.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncSubscriptionEvent.swift index ec86c53e6a..1b14fa90c8 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncSubscriptionEvent.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncSubscriptionEvent.swift @@ -5,9 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Amplify +import Foundation public enum AppSyncSubscriptionEvent { case subscribing diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncWebSocketClientProtocol.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncWebSocketClientProtocol.swift index d7d9cadc29..a5d944a356 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncWebSocketClientProtocol.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AppSyncRealTimeClient/AppSyncWebSocketClientProtocol.swift @@ -5,9 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Combine +import Foundation @_spi(WebSocket) import AWSPluginsCore protocol AppSyncWebSocketClientProtocol: AnyObject { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Configuration/AWSAPICategoryPluginConfiguration+EndpointConfig.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Configuration/AWSAPICategoryPluginConfiguration+EndpointConfig.swift index 8be955bdb2..8e3aad56b8 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Configuration/AWSAPICategoryPluginConfiguration+EndpointConfig.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Configuration/AWSAPICategoryPluginConfiguration+EndpointConfig.swift @@ -6,8 +6,8 @@ // @_spi(InternalAmplifyConfiguration) import Amplify -import Foundation import AWSPluginsCore +import Foundation public extension AWSAPICategoryPluginConfiguration { struct EndpointConfig { @@ -27,10 +27,12 @@ public extension AWSAPICategoryPluginConfiguration { var apiKey: String? - public init(name: String, - jsonValue: JSONValue, - apiAuthProviderFactory: APIAuthProviderFactory, - authService: AWSAuthServiceBehavior? = nil) throws { + public init( + name: String, + jsonValue: JSONValue, + apiAuthProviderFactory: APIAuthProviderFactory, + authService: AWSAuthServiceBehavior? = nil + ) throws { guard case .object(let endpointJSON) = jsonValue else { throw PluginError.pluginConfigurationError( @@ -49,54 +51,66 @@ public extension AWSAPICategoryPluginConfiguration { apiKeyValue = apiKey } - try self.init(name: name, - baseURL: EndpointConfig.getBaseURL(from: endpointJSON), - region: AWSRegionType.region(from: endpointJSON), - authorizationType: AWSAuthorizationType.from(endpointJSON: endpointJSON), - endpointType: EndpointConfig.getEndpointType(from: endpointJSON), - apiKey: apiKeyValue, - apiAuthProviderFactory: apiAuthProviderFactory, - authService: authService) + try self.init( + name: name, + baseURL: EndpointConfig.getBaseURL(from: endpointJSON), + region: AWSRegionType.region(from: endpointJSON), + authorizationType: AWSAuthorizationType.from(endpointJSON: endpointJSON), + endpointType: EndpointConfig.getEndpointType(from: endpointJSON), + apiKey: apiKeyValue, + apiAuthProviderFactory: apiAuthProviderFactory, + authService: authService + ) } - init(name: String, - config: AmplifyOutputsData.DataCategory, - apiAuthProviderFactory: APIAuthProviderFactory, - authService: AWSAuthServiceBehavior? = nil) throws { - - try self.init(name: name, - baseURL: try EndpointConfig.getBaseURL(from: config.url), - region: config.awsRegion, - authorizationType: try AWSAuthorizationType.from(authorizationTypeString: config.defaultAuthorizationType.rawValue), - endpointType: .graphQL, - apiKey: config.apiKey, - apiAuthProviderFactory: apiAuthProviderFactory, - authService: authService) + init( + name: String, + config: AmplifyOutputsData.DataCategory, + apiAuthProviderFactory: APIAuthProviderFactory, + authService: AWSAuthServiceBehavior? = nil + ) throws { + + try self.init( + name: name, + baseURL: EndpointConfig.getBaseURL(from: config.url), + region: config.awsRegion, + authorizationType: AWSAuthorizationType.from(authorizationTypeString: config.defaultAuthorizationType.rawValue), + endpointType: .graphQL, + apiKey: config.apiKey, + apiAuthProviderFactory: apiAuthProviderFactory, + authService: authService + ) } - init(name: String, - baseURL: URL, - region: AWSRegionType?, - authorizationType: AWSAuthorizationType, - endpointType: AWSAPICategoryPluginEndpointType, - apiKey: String? = nil, - apiAuthProviderFactory: APIAuthProviderFactory, - authService: AWSAuthServiceBehavior? = nil) throws { + init( + name: String, + baseURL: URL, + region: AWSRegionType?, + authorizationType: AWSAuthorizationType, + endpointType: AWSAPICategoryPluginEndpointType, + apiKey: String? = nil, + apiAuthProviderFactory: APIAuthProviderFactory, + authService: AWSAuthServiceBehavior? = nil + ) throws { self.name = name self.baseURL = baseURL self.region = region self.authorizationType = authorizationType - self.authorizationConfiguration = try AWSAuthorizationConfiguration.makeConfiguration(authType: authorizationType, - region: region, - apiKey: apiKey) + self.authorizationConfiguration = try AWSAuthorizationConfiguration.makeConfiguration( + authType: authorizationType, + region: region, + apiKey: apiKey + ) self.endpointType = endpointType self.apiKey = apiKey } public func authorizationConfigurationFor(authType: AWSAuthorizationType) throws -> AWSAuthorizationConfiguration { - return try AWSAuthorizationConfiguration.makeConfiguration(authType: authType, - region: region, - apiKey: apiKey) + return try AWSAuthorizationConfiguration.makeConfiguration( + authType: authType, + region: region, + apiKey: apiKey + ) } // MARK: - Configuration file helpers @@ -165,12 +179,10 @@ public extension AWSAPICategoryPluginConfiguration { private extension AWSRegionType { static func region(from endpointJSON: [String: JSONValue]) throws -> AWSRegionType? { - let region: AWSRegionType? - - if case .string(let endpointRegion) = endpointJSON["region"] { - region = endpointRegion + let region: AWSRegionType? = if case .string(let endpointRegion) = endpointJSON["region"] { + endpointRegion } else { - region = nil + nil } return region @@ -198,7 +210,7 @@ private extension AWSAuthorizationType { static func from(authorizationTypeString: String) throws -> AWSAuthorizationType { guard let authorizationType = AWSAuthorizationType(rawValue: authorizationTypeString) else { - let authTypes = AWSAuthorizationType.allCases.map { $0.rawValue }.joined(separator: ", ") + let authTypes = AWSAuthorizationType.allCases.map(\.rawValue).joined(separator: ", ") throw PluginError.pluginConfigurationError( "Could not convert `\(authorizationTypeString)` to an AWSAuthorizationType", """ @@ -215,20 +227,22 @@ private extension AWSAuthorizationType { // MARK: - Dictionary + AWSAPICategoryPluginConfiguration.EndpointConfig -extension Dictionary where Key == String, Value == AWSAPICategoryPluginConfiguration.EndpointConfig { +extension [String: AWSAPICategoryPluginConfiguration.EndpointConfig] { /// Getting the `EndpointConfig` resolves to the following rules: /// 1. If `apiName` is specified, retrieve the endpoint configuration for this api /// 2. If `apiName` is not specified, and `endpointType` is, retrieve the endpoint if there is only one. /// 3. If nothing is specified, return the endpoint only if there is a single one, with GraphQL taking precedent /// over REST. - func getConfig(for apiName: String? = nil, - endpointType: AWSAPICategoryPluginEndpointType? = nil) throws -> + func getConfig( + for apiName: String? = nil, + endpointType: AWSAPICategoryPluginEndpointType? = nil + ) throws -> AWSAPICategoryPluginConfiguration.EndpointConfig { - if let apiName = apiName { + if let apiName { return try getConfig(for: apiName) } - if let endpointType = endpointType { + if let endpointType { return try getConfig(for: endpointType) } @@ -255,26 +269,29 @@ extension Dictionary where Key == String, Value == AWSAPICategoryPluginConfigura /// Retrieve the endpoint configuration when there is only one endpoint of the specified `endpointType` private func getConfig(for endpointType: AWSAPICategoryPluginEndpointType) throws -> AWSAPICategoryPluginConfiguration.EndpointConfig { - let apiForEndpointType = filter { (_, endpointConfig) -> Bool in + let apiForEndpointType = filter { _, endpointConfig -> Bool in return endpointConfig.endpointType == endpointType } guard let endpointConfig = apiForEndpointType.first else { - throw APIError.invalidConfiguration("Missing API for \(endpointType) endpointType", - "Add the \(endpointType) API to configuration.") + throw APIError.invalidConfiguration( + "Missing API for \(endpointType) endpointType", + "Add the \(endpointType) API to configuration." + ) } if apiForEndpointType.count > 1 { throw APIError.invalidConfiguration( "More than one \(endpointType) API configured. Could not infer which API to call", - "Use the apiName to specify which API to call") + "Use the apiName to specify which API to call" + ) } return endpointConfig.value } /// Retrieve the endpoint only if there is a single one, with GraphQL taking precedent over REST. private func getConfig() throws -> AWSAPICategoryPluginConfiguration.EndpointConfig { - let graphQLEndpoints = filter { (_, endpointConfig) -> Bool in + let graphQLEndpoints = filter { _, endpointConfig -> Bool in return endpointConfig.endpointType == .graphQL } @@ -282,7 +299,7 @@ extension Dictionary where Key == String, Value == AWSAPICategoryPluginConfigura return endpoint.value } - let restEndpoints = filter { (_, endpointConfig) -> Bool in + let restEndpoints = filter { _, endpointConfig -> Bool in return endpointConfig.endpointType == .rest } @@ -290,10 +307,12 @@ extension Dictionary where Key == String, Value == AWSAPICategoryPluginConfigura return endpoint.value } - throw APIError.invalidConfiguration("Unable to resolve endpoint configuration", - """ + throw APIError.invalidConfiguration( + "Unable to resolve endpoint configuration", + """ Pass in the apiName to specify the endpoint you are retrieving the config for - """) + """ + ) } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Configuration/AWSAPICategoryPluginConfiguration.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Configuration/AWSAPICategoryPluginConfiguration.swift index 07005a7034..0559bae0b5 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Configuration/AWSAPICategoryPluginConfiguration.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Configuration/AWSAPICategoryPluginConfiguration.swift @@ -6,8 +6,8 @@ // @_spi(InternalAmplifyConfiguration) import Amplify -import Foundation import AWSPluginsCore +import Foundation import InternalAmplifyCredentials // Convenience typealias @@ -20,9 +20,11 @@ public struct AWSAPICategoryPluginConfiguration { private var apiAuthProviderFactory: APIAuthProviderFactory? private var authService: AWSAuthCredentialsProviderBehavior? - init(jsonValue: JSONValue, - apiAuthProviderFactory: APIAuthProviderFactory, - authService: AWSAuthCredentialsProviderBehavior) throws { + init( + jsonValue: JSONValue, + apiAuthProviderFactory: APIAuthProviderFactory, + authService: AWSAuthCredentialsProviderBehavior + ) throws { guard case .object(let config) = jsonValue else { throw PluginError.pluginConfigurationError( "Could not cast incoming configuration to a JSONValue `.object`", @@ -35,23 +37,31 @@ public struct AWSAPICategoryPluginConfiguration { ) } - let endpoints = try AWSAPICategoryPluginConfiguration.endpointsFromConfig(config: config, - apiAuthProviderFactory: apiAuthProviderFactory, - authService: authService) - let interceptors = try AWSAPICategoryPluginConfiguration.makeInterceptors(forEndpoints: endpoints, - apiAuthProviderFactory: apiAuthProviderFactory, - authService: authService) + let endpoints = try AWSAPICategoryPluginConfiguration.endpointsFromConfig( + config: config, + apiAuthProviderFactory: apiAuthProviderFactory, + authService: authService + ) + let interceptors = try AWSAPICategoryPluginConfiguration.makeInterceptors( + forEndpoints: endpoints, + apiAuthProviderFactory: apiAuthProviderFactory, + authService: authService + ) - self.init(endpoints: endpoints, - interceptors: interceptors, - apiAuthProviderFactory: apiAuthProviderFactory, - authService: authService) + self.init( + endpoints: endpoints, + interceptors: interceptors, + apiAuthProviderFactory: apiAuthProviderFactory, + authService: authService + ) } - init(configuration: AmplifyOutputsData, - apiAuthProviderFactory: APIAuthProviderFactory, - authService: AWSAuthCredentialsProviderBehavior) throws { + init( + configuration: AmplifyOutputsData, + apiAuthProviderFactory: APIAuthProviderFactory, + authService: AWSAuthCredentialsProviderBehavior + ) throws { guard let data = configuration.data else { throw PluginError.pluginConfigurationError( @@ -66,16 +76,20 @@ public struct AWSAPICategoryPluginConfiguration { let endpoints = try AWSAPICategoryPluginConfiguration.endpointsFromConfig( config: data, apiAuthProviderFactory: apiAuthProviderFactory, - authService: authService) + authService: authService + ) let interceptors = try AWSAPICategoryPluginConfiguration.makeInterceptors( forEndpoints: endpoints, apiAuthProviderFactory: apiAuthProviderFactory, - authService: authService) + authService: authService + ) - self.init(endpoints: endpoints, - interceptors: interceptors, - apiAuthProviderFactory: apiAuthProviderFactory, - authService: authService) + self.init( + endpoints: endpoints, + interceptors: interceptors, + apiAuthProviderFactory: apiAuthProviderFactory, + authService: authService + ) } @@ -83,8 +97,10 @@ public struct AWSAPICategoryPluginConfiguration { /// - Parameters: /// - endpoints: dictionary of EndpointConfig whose keys are the API endpoint name /// - interceptors: dictionary of AWSAPIEndpointInterceptors whose keys are the API endpoint name - internal init(endpoints: [APIEndpointName: EndpointConfig], - interceptors: [APIEndpointName: AWSAPIEndpointInterceptors] = [:]) { + init( + endpoints: [APIEndpointName: EndpointConfig], + interceptors: [APIEndpointName: AWSAPIEndpointInterceptors] = [:] + ) { self.endpoints = endpoints self.interceptors = interceptors } @@ -93,10 +109,12 @@ public struct AWSAPICategoryPluginConfiguration { /// - Parameters: /// - endpoints: dictionary of EndpointConfig whose keys are the API endpoint name /// - interceptors: dictionary of AWSAPIEndpointInterceptors whose keys are the API endpoint name - internal init(endpoints: [APIEndpointName: EndpointConfig], - interceptors: [APIEndpointName: AWSAPIEndpointInterceptors] = [:], - apiAuthProviderFactory: APIAuthProviderFactory, - authService: AWSAuthCredentialsProviderBehavior) { + init( + endpoints: [APIEndpointName: EndpointConfig], + interceptors: [APIEndpointName: AWSAPIEndpointInterceptors] = [:], + apiAuthProviderFactory: APIAuthProviderFactory, + authService: AWSAuthCredentialsProviderBehavior + ) { self.endpoints = endpoints self.interceptors = interceptors self.apiAuthProviderFactory = apiAuthProviderFactory @@ -106,8 +124,10 @@ public struct AWSAPICategoryPluginConfiguration { /// Registers an customer interceptor for the provided API endpoint /// - Parameter interceptor: operation interceptor used to decorate API requests /// - Parameter toEndpoint: API endpoint name - mutating func addInterceptor(_ interceptor: URLRequestInterceptor, - toEndpoint apiName: APIEndpointName) { + mutating func addInterceptor( + _ interceptor: URLRequestInterceptor, + toEndpoint apiName: APIEndpointName + ) { guard interceptors[apiName] != nil else { log.error("No interceptors configuration found for \(apiName)") return @@ -118,7 +138,7 @@ public struct AWSAPICategoryPluginConfiguration { /// Returns all the interceptors registered for `apiName` API endpoint /// - Parameter apiName: API endpoint name /// - Returns: Optional AWSAPIEndpointInterceptors for the apiName - internal func interceptorsForEndpoint(named apiName: APIEndpointName) -> AWSAPIEndpointInterceptors? { + func interceptorsForEndpoint(named apiName: APIEndpointName) -> AWSAPIEndpointInterceptors? { return interceptors[apiName] } @@ -126,7 +146,7 @@ public struct AWSAPICategoryPluginConfiguration { /// - Parameters: /// - endpointConfig: endpoint configuration /// - Returns: Optional AWSAPIEndpointInterceptors for the endpointConfig - internal func interceptorsForEndpoint(withConfig endpointConfig: EndpointConfig) -> AWSAPIEndpointInterceptors? { + func interceptorsForEndpoint(withConfig endpointConfig: EndpointConfig) -> AWSAPIEndpointInterceptors? { return interceptorsForEndpoint(named: endpointConfig.name) } @@ -136,23 +156,29 @@ public struct AWSAPICategoryPluginConfiguration { /// - authType: overrides the registered auth interceptor /// - Throws: PluginConfigurationError in case of failure building an instance of AWSAuthorizationConfiguration /// - Returns: Optional AWSAPIEndpointInterceptors for the endpointConfig and authType - internal func interceptorsForEndpoint( + func interceptorsForEndpoint( withConfig endpointConfig: EndpointConfig, authType: AWSAuthorizationType ) throws -> AWSAPIEndpointInterceptors? { - guard let apiAuthProviderFactory = self.apiAuthProviderFactory else { + guard let apiAuthProviderFactory else { return interceptorsForEndpoint(named: endpointConfig.name) } - var config = AWSAPIEndpointInterceptors(endpointName: endpointConfig.name, - apiAuthProviderFactory: apiAuthProviderFactory, - authService: authService) - let authConfiguration = try AWSAuthorizationConfiguration.makeConfiguration(authType: authType, - region: endpointConfig.region, - apiKey: endpointConfig.apiKey) - try config.addAuthInterceptorsToEndpoint(endpointType: endpointConfig.endpointType, - authConfiguration: authConfiguration) + var config = AWSAPIEndpointInterceptors( + endpointName: endpointConfig.name, + apiAuthProviderFactory: apiAuthProviderFactory, + authService: authService + ) + let authConfiguration = try AWSAuthorizationConfiguration.makeConfiguration( + authType: authType, + region: endpointConfig.region, + apiKey: endpointConfig.apiKey + ) + try config.addAuthInterceptorsToEndpoint( + endpointType: endpointConfig.endpointType, + authConfiguration: authConfiguration + ) // retrieve current interceptors and replace auth interceptor let currentInterceptors = interceptorsForEndpoint(named: endpointConfig.name) @@ -181,10 +207,12 @@ public struct AWSAPICategoryPluginConfiguration { for (key, jsonValue) in config { let name = key - let endpointConfig = try EndpointConfig(name: name, - jsonValue: jsonValue, - apiAuthProviderFactory: apiAuthProviderFactory, - authService: authService) + let endpointConfig = try EndpointConfig( + name: name, + jsonValue: jsonValue, + apiAuthProviderFactory: apiAuthProviderFactory, + authService: authService + ) endpoints[name] = endpointConfig } @@ -198,10 +226,12 @@ public struct AWSAPICategoryPluginConfiguration { ) throws -> [APIEndpointName: EndpointConfig] { var endpoints = [APIEndpointName: EndpointConfig]() let name = AWSAPIPlugin.defaultGraphQLAPI - let endpointConfig = try EndpointConfig(name: name, - config: config, - apiAuthProviderFactory: apiAuthProviderFactory, - authService: authService) + let endpointConfig = try EndpointConfig( + name: name, + config: config, + apiAuthProviderFactory: apiAuthProviderFactory, + authService: authService + ) endpoints[name] = endpointConfig return endpoints } @@ -214,16 +244,22 @@ public struct AWSAPICategoryPluginConfiguration { /// - authService: authService /// - Throws: /// - Returns: dictionary of AWSAPIEndpointInterceptors indexed by API endpoint name - private static func makeInterceptors(forEndpoints endpoints: [APIEndpointName: EndpointConfig], - apiAuthProviderFactory: APIAuthProviderFactory, - authService: AWSAuthCredentialsProviderBehavior) throws -> [APIEndpointName: AWSAPIEndpointInterceptors] { + private static func makeInterceptors( + forEndpoints endpoints: [APIEndpointName: EndpointConfig], + apiAuthProviderFactory: APIAuthProviderFactory, + authService: AWSAuthCredentialsProviderBehavior + ) throws -> [APIEndpointName: AWSAPIEndpointInterceptors] { var interceptors: [APIEndpointName: AWSAPIEndpointInterceptors] = [:] for (name, config) in endpoints { - var interceptorsConfig = AWSAPIEndpointInterceptors(endpointName: name, - apiAuthProviderFactory: apiAuthProviderFactory, - authService: authService) - try interceptorsConfig.addAuthInterceptorsToEndpoint(endpointType: config.endpointType, - authConfiguration: config.authorizationConfiguration) + var interceptorsConfig = AWSAPIEndpointInterceptors( + endpointName: name, + apiAuthProviderFactory: apiAuthProviderFactory, + authService: authService + ) + try interceptorsConfig.addAuthInterceptorsToEndpoint( + endpointType: config.endpointType, + authConfiguration: config.authorizationConfiguration + ) interceptors[name] = interceptorsConfig } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Configuration/AWSAPIEndpointInterceptors.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Configuration/AWSAPIEndpointInterceptors.swift index 99191e40dc..cff8e3838b 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Configuration/AWSAPIEndpointInterceptors.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Configuration/AWSAPIEndpointInterceptors.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSPluginsCore +import Foundation import InternalAmplifyCredentials /// The order of interceptor decoration is as follows: @@ -31,23 +31,26 @@ struct AWSAPIEndpointInterceptors { var postludeInterceptors: [URLRequestInterceptor] = [] - /// Validates whether the access token has expired. A best-effort attempt is made, + /// Validates whether the access token has expired. A best-effort attempt is made, /// and it returns `false` if the expiration cannot be determined. - var expiryValidator: ((String) -> Bool) { + var expiryValidator: (String) -> Bool { { token in guard let authService, let claims = try? authService.getTokenClaims(tokenString: token).get(), - let tokenExpiration = claims["exp"]?.doubleValue else { + let tokenExpiration = claims["exp"]?.doubleValue + else { return false } let currentTime = Date().timeIntervalSince1970 return currentTime > tokenExpiration } } - - init(endpointName: APIEndpointName, - apiAuthProviderFactory: APIAuthProviderFactory, - authService: AWSAuthCredentialsProviderBehavior? = nil) { + + init( + endpointName: APIEndpointName, + apiAuthProviderFactory: APIAuthProviderFactory, + authService: AWSAuthCredentialsProviderBehavior? = nil + ) { self.apiEndpointName = endpointName self.apiAuthProviderFactory = apiAuthProviderFactory self.authService = authService @@ -60,8 +63,10 @@ struct AWSAPIEndpointInterceptors { } /// Initialize authorization interceptors - mutating func addAuthInterceptorsToEndpoint(endpointType: AWSAPICategoryPluginEndpointType, - authConfiguration: AWSAuthorizationConfiguration) throws { + mutating func addAuthInterceptorsToEndpoint( + endpointType: AWSAPICategoryPluginEndpointType, + authConfiguration: AWSAuthorizationConfiguration + ) throws { switch authConfiguration { case .none: // No interceptors needed @@ -71,36 +76,48 @@ struct AWSAPIEndpointInterceptors { let interceptor = APIKeyURLRequestInterceptor(apiKeyProvider: provider) preludeInterceptors.append(interceptor) case .awsIAM(let iamConfig): - guard let authService = authService else { - throw PluginError.pluginConfigurationError("AuthService is not set for IAM", - "") + guard let authService else { + throw PluginError.pluginConfigurationError( + "AuthService is not set for IAM", + "" + ) } let provider = BasicIAMCredentialsProvider(authService: authService) - let interceptor = IAMURLRequestInterceptor(iamCredentialsProvider: provider, - region: iamConfig.region, - endpointType: endpointType) + let interceptor = IAMURLRequestInterceptor( + iamCredentialsProvider: provider, + region: iamConfig.region, + endpointType: endpointType + ) postludeInterceptors.append(interceptor) case .amazonCognitoUserPools: - guard let authService = authService else { - throw PluginError.pluginConfigurationError("AuthService not set for cognito user pools", - "") + guard let authService else { + throw PluginError.pluginConfigurationError( + "AuthService not set for cognito user pools", + "" + ) } let provider = BasicUserPoolTokenProvider(authService: authService) - let interceptor = AuthTokenURLRequestInterceptor(authTokenProvider: provider, - isTokenExpired: expiryValidator) + let interceptor = AuthTokenURLRequestInterceptor( + authTokenProvider: provider, + isTokenExpired: expiryValidator + ) preludeInterceptors.append(interceptor) case .openIDConnect: guard let oidcAuthProvider = apiAuthProviderFactory.oidcAuthProvider() else { - throw PluginError.pluginConfigurationError("AuthService not set for OIDC", - "Provide an AmplifyOIDCAuthProvider via API plugin configuration") + throw PluginError.pluginConfigurationError( + "AuthService not set for OIDC", + "Provide an AmplifyOIDCAuthProvider via API plugin configuration" + ) } let wrappedAuthProvider = AuthTokenProviderWrapper(tokenAuthProvider: oidcAuthProvider) let interceptor = AuthTokenURLRequestInterceptor(authTokenProvider: wrappedAuthProvider) preludeInterceptors.append(interceptor) case .function: guard let functionAuthProvider = apiAuthProviderFactory.functionAuthProvider() else { - throw PluginError.pluginConfigurationError("AuthService not set for function auth", - "Provide an AmplifyFunctionAuthProvider via API plugin configuration") + throw PluginError.pluginConfigurationError( + "AuthService not set for function auth", + "Provide an AmplifyFunctionAuthProvider via API plugin configuration" + ) } let wrappedAuthProvider = AuthTokenProviderWrapper(tokenAuthProvider: functionAuthProvider) let interceptor = AuthTokenURLRequestInterceptor(authTokenProvider: wrappedAuthProvider) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListDecoder.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListDecoder.swift index e75add220b..bb385814ea 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListDecoder.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListDecoder.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation /// This decoder is registered and used to detect various data payloads objects to store /// inside an AppSyncListProvider when decoding to the Lazy `List` type as a "not yet loaded" List. If the data payload @@ -25,7 +25,7 @@ public struct AppSyncListDecoder: ModelListDecoder { /// Used by the custom decoder implemented in the `List` type to detect if the payload can be /// decoded to an AppSyncListProvider. public static func decode(modelType: ModelType.Type, decoder: Decoder) -> AnyModelListProvider? { - self.shouldDecodeToAppSyncListProvider(modelType: modelType, decoder: decoder)?.eraseToAnyModelListProvider() + shouldDecodeToAppSyncListProvider(modelType: modelType, decoder: decoder)?.eraseToAnyModelListProvider() } static func shouldDecodeToAppSyncListProvider(modelType: ModelType.Type, decoder: Decoder) -> AppSyncListProvider? { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListPayload.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListPayload.swift index 033c718d86..6cd95ca1c5 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListPayload.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListPayload.swift @@ -18,10 +18,12 @@ public struct AppSyncListPayload: Codable { let apiName: String? let authMode: AWSAuthorizationType? - public init(graphQLData: JSONValue, - apiName: String?, - authMode: AWSAuthorizationType?, - variables: [String: JSONValue]?) { + public init( + graphQLData: JSONValue, + apiName: String?, + authMode: AWSAuthorizationType?, + variables: [String: JSONValue]? + ) { self.apiName = apiName self.authMode = authMode self.variables = variables @@ -35,7 +37,8 @@ public struct AppSyncListPayload: Codable { var graphQLFilter: [String: Any]? { guard let storedVariables = variables, let filters = storedVariables["filter"], - case let .object(filterValue) = filters else { + case let .object(filterValue) = filters + else { return nil } @@ -46,7 +49,8 @@ public struct AppSyncListPayload: Codable { // `GraphQLFilter`. guard let filterVariablesData = try? encoder.encode(filterValue), let filterVariablesJSON = try? JSONSerialization.jsonObject(with: filterVariablesData) - as? GraphQLFilter else { + as? GraphQLFilter + else { assertionFailure("Filter variables is not a valid JSON object: \(filterValue)") return nil diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListProvider.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListProvider.swift index 19f1368dd6..26b1ebdbf6 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListProvider.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListProvider.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation public class AppSyncListProvider: ModelListProvider { @@ -28,14 +28,18 @@ public class AppSyncListProvider: ModelListProvider { /// The associatedFields represents the field to which the owner of the `List` is linked to. /// For example, if `Post.comments` is associated with `Comment.post` the `List` /// of `Post` will have a reference to the `post` field in `Comment`. - case notLoaded(associatedIdentifiers: [String], - associatedFields: [String]) + case notLoaded( + associatedIdentifiers: [String], + associatedFields: [String] + ) /// If the list is retrieved directly, this state holds the underlying data, nextToken used to create /// the subsequent GraphQL request, and previous filter used to create the loaded list - case loaded(elements: [Element], - nextToken: String?, - filter: [String: Any]?) + case loaded( + elements: [Element], + nextToken: String?, + filter: [String: Any]? + ) } var loadedState: LoadedState @@ -43,52 +47,68 @@ public class AppSyncListProvider: ModelListProvider { // MARK: - Initializers convenience init(payload: AppSyncListPayload) throws { - let listResponse = try AppSyncListResponse.initWithMetadata(type: Element.self, - graphQLData: payload.graphQLData, - apiName: payload.apiName, - authMode: payload.authMode) - - self.init(elements: listResponse.items, - nextToken: listResponse.nextToken, - apiName: payload.apiName, - limit: payload.limit, - filter: payload.graphQLFilter) + let listResponse = try AppSyncListResponse.initWithMetadata( + type: Element.self, + graphQLData: payload.graphQLData, + apiName: payload.apiName, + authMode: payload.authMode + ) + + self.init( + elements: listResponse.items, + nextToken: listResponse.nextToken, + apiName: payload.apiName, + limit: payload.limit, + filter: payload.graphQLFilter + ) } convenience init(listResponse: AppSyncListResponse) throws { - self.init(elements: listResponse.items, - nextToken: listResponse.nextToken) + self.init( + elements: listResponse.items, + nextToken: listResponse.nextToken + ) } convenience init(metadata: AppSyncListDecoder.Metadata) { - self.init(associatedIdentifiers: metadata.appSyncAssociatedIdentifiers, - associatedFields: metadata.appSyncAssociatedFields, - apiName: metadata.apiName, - authMode: metadata.authMode) + self.init( + associatedIdentifiers: metadata.appSyncAssociatedIdentifiers, + associatedFields: metadata.appSyncAssociatedFields, + apiName: metadata.apiName, + authMode: metadata.authMode + ) } // Internal initializer for testing - init(elements: [Element], - nextToken: String? = nil, - apiName: String? = nil, - authMode: AWSAuthorizationType? = nil, - limit: Int? = nil, - filter: [String: Any]? = nil) { - self.loadedState = .loaded(elements: elements, - nextToken: nextToken, - filter: filter) + init( + elements: [Element], + nextToken: String? = nil, + apiName: String? = nil, + authMode: AWSAuthorizationType? = nil, + limit: Int? = nil, + filter: [String: Any]? = nil + ) { + self.loadedState = .loaded( + elements: elements, + nextToken: nextToken, + filter: filter + ) self.apiName = apiName self.authMode = authMode self.limit = limit } // Internal initializer for testing - init(associatedIdentifiers: [String], - associatedFields: [String], - apiName: String? = nil, - authMode: AWSAuthorizationType? = nil) { - self.loadedState = .notLoaded(associatedIdentifiers: associatedIdentifiers, - associatedFields: associatedFields) + init( + associatedIdentifiers: [String], + associatedFields: [String], + apiName: String? = nil, + authMode: AWSAuthorizationType? = nil + ) { + self.loadedState = .notLoaded( + associatedIdentifiers: associatedIdentifiers, + associatedFields: associatedFields + ) self.apiName = apiName self.authMode = authMode } @@ -114,8 +134,10 @@ public class AppSyncListProvider: ModelListProvider { } //// Internal `load` to perform the retrieval of the first page and storing it in memory - func load(associatedIdentifiers: [String], - associatedFields: [String]) async throws -> [Element] { + func load( + associatedIdentifiers: [String], + associatedFields: [String] + ) async throws -> [Element] { let filter: GraphQLFilter if associatedIdentifiers.count == 1, let associatedId = associatedIdentifiers.first, @@ -128,49 +150,60 @@ public class AppSyncListProvider: ModelListProvider { let columnNames = columnNames(fields: associatedFields, Element.schema) let predicateValues = zip(columnNames, associatedIdentifiers) for (identifierName, identifierValue) in predicateValues { - queryPredicates.append(QueryPredicateOperation(field: identifierName, - operator: .equals(identifierValue))) + queryPredicates.append(QueryPredicateOperation( + field: identifierName, + operator: .equals(identifierValue) + )) } let groupedQueryPredicates = QueryPredicateGroup(type: .and, predicates: queryPredicates) filter = groupedQueryPredicates.graphQLFilter(for: Element.schema) } - let request = GraphQLRequest.listQuery(responseType: JSONValue.self, - modelSchema: Element.schema, - filter: filter, - limit: limit, - apiName: apiName, - authMode: authMode) + let request = GraphQLRequest.listQuery( + responseType: JSONValue.self, + modelSchema: Element.schema, + filter: filter, + limit: limit, + apiName: apiName, + authMode: authMode + ) do { let graphQLResponse = try await Amplify.API.query(request: request) switch graphQLResponse { case .success(let graphQLData): - guard let listResponse = try? AppSyncListResponse.initWithMetadata(type: Element.self, - graphQLData: graphQLData, - apiName: self.apiName, - authMode: self.authMode) else { + guard let listResponse = try? AppSyncListResponse.initWithMetadata( + type: Element.self, + graphQLData: graphQLData, + apiName: apiName, + authMode: authMode + ) else { throw CoreError.listOperation(""" The AppSync response return successfully, but could not decode to AWSAppSyncListResponse from: \(graphQLData) """, "", nil) } - self.loadedState = .loaded(elements: listResponse.items, - nextToken: listResponse.nextToken, - filter: filter) + loadedState = .loaded( + elements: listResponse.items, + nextToken: listResponse.nextToken, + filter: filter + ) return listResponse.items case .failure(let graphQLError): log.error(error: graphQLError) throw CoreError.listOperation( "The AppSync response returned successfully with GraphQL errors.", "Check the underlying error for the failed GraphQL response.", - graphQLError) + graphQLError + ) } } catch let apiError as APIError { log.error(error: apiError) - throw CoreError.listOperation("The AppSync request failed", - "See underlying `APIError` for more details.", - apiError) + throw CoreError.listOperation( + "The AppSync request failed", + "See underlying `APIError` for more details.", + apiError + ) } catch { throw error } @@ -193,24 +226,30 @@ public class AppSyncListProvider: ModelListProvider { """, "", nil) } guard let nextToken = nextTokenOptional else { - throw CoreError.clientValidation("There is no next page.", - "Only call `getNextPage()` when `hasNextPage()` is true.", - nil) + throw CoreError.clientValidation( + "There is no next page.", + "Only call `getNextPage()` when `hasNextPage()` is true.", + nil + ) } return try await getNextPage(nextToken: nextToken, filter: filter) } /// Internal `getNextPage` to retrieve the next page and return it as a new List object - func getNextPage(nextToken: String, - filter: [String: Any]?) async throws -> List { - let request = GraphQLRequest>.listQuery(responseType: List.self, - modelSchema: Element.schema, - filter: filter, - limit: limit, - nextToken: nextToken, - apiName: apiName, - authMode: authMode) + func getNextPage( + nextToken: String, + filter: [String: Any]? + ) async throws -> List { + let request = GraphQLRequest>.listQuery( + responseType: List.self, + modelSchema: Element.schema, + filter: filter, + limit: limit, + nextToken: nextToken, + apiName: apiName, + authMode: authMode + ) do { let graphQLResponse = try await Amplify.API.query(request: request) switch graphQLResponse { @@ -225,9 +264,11 @@ public class AppSyncListProvider: ModelListProvider { } } catch let apiError as APIError { log.error(error: apiError) - throw CoreError.listOperation("The AppSync request failed", - "See underlying `APIError` for more details.", - apiError) + throw CoreError.listOperation( + "The AppSync request failed", + "See underlying `APIError` for more details.", + apiError + ) } catch { throw error } @@ -240,7 +281,8 @@ public class AppSyncListProvider: ModelListProvider { appSyncAssociatedIdentifiers: associatedIdentifiers, appSyncAssociatedFields: associatedFields, apiName: apiName, - authMode: authMode) + authMode: authMode + ) var container = encoder.singleValueContainer() try container.encode(metadata) case .loaded(let elements, _, _): diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListResponse.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListResponse.swift index a30821853d..c867897249 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListResponse.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListResponse.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSPluginsCore +import Foundation /// Resembles the AppSync's GraphQL response for a list operation. struct AppSyncListResponse: Codable { @@ -24,16 +24,19 @@ extension AppSyncListResponse { /// Modify the incoming `graphQLData` by decoding each item in the response with /// model metadata on its array associations. - static func initWithMetadata(type: Element.Type, - graphQLData: JSONValue, - apiName: String?, - authMode: AWSAuthorizationType?) throws -> AppSyncListResponse { + static func initWithMetadata( + type: Element.Type, + graphQLData: JSONValue, + apiName: String?, + authMode: AWSAuthorizationType? + ) throws -> AppSyncListResponse { var elements = [Element]() if case let .array(jsonArray) = graphQLData["items"] { let jsonArrayWithMetadata = AppSyncModelMetadataUtils.addMetadata( toModelArray: jsonArray, apiName: apiName, - authMode: authMode) + authMode: authMode + ) let encoder = JSONEncoder() encoder.dateEncodingStrategy = ModelDateFormatting.encodingStrategy diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelDecoder.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelDecoder.swift index dab2e44756..eb24725b95 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelDecoder.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelDecoder.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation /// This decoder is registered and used to detect various data payloads to store /// inside an `AppSyncModelProvider` when decoding to the `LazyReference` as a "not yet loaded" Reference. If the data payload @@ -21,10 +21,12 @@ public struct AppSyncModelDecoder: ModelProviderDecoder { let authMode: AWSAuthorizationType? let source: String - init(identifiers: [LazyReferenceIdentifier], - apiName: String?, - authMode: AWSAuthorizationType?, - source: String = ModelProviderRegistry.DecoderSource.appSync) { + init( + identifiers: [LazyReferenceIdentifier], + apiName: String?, + authMode: AWSAuthorizationType?, + source: String = ModelProviderRegistry.DecoderSource.appSync + ) { self.identifiers = identifiers self.apiName = apiName self.authMode = authMode diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelMetadata.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelMetadata.swift index 20f0b88dd0..73fd5c5291 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelMetadata.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelMetadata.swift @@ -6,11 +6,11 @@ // import Amplify -import Foundation import AWSPluginsCore +import Foundation /// Holds the methods to traverse and maniupulate the response data object by injecting -public struct AppSyncModelMetadataUtils { +public enum AppSyncModelMetadataUtils { // A fairly light check to make sure the payload is an object and we have the schema for `addMetadata`. // Note: `addMetadata` should be very tightly checking the associated fields to determine when it should add @@ -25,10 +25,12 @@ public struct AppSyncModelMetadataUtils { return true } - static func addMetadata(toModelArray graphQLDataArray: [JSONValue], - apiName: String?, - authMode: AWSAuthorizationType?) -> [JSONValue] { - return graphQLDataArray.map { (graphQLData) -> JSONValue in + static func addMetadata( + toModelArray graphQLDataArray: [JSONValue], + apiName: String?, + authMode: AWSAuthorizationType? + ) -> [JSONValue] { + return graphQLDataArray.map { graphQLData -> JSONValue in addMetadata(toModel: graphQLData, apiName: apiName, authMode: authMode) } } @@ -37,8 +39,9 @@ public struct AppSyncModelMetadataUtils { toModel graphQLData: JSONValue, apiName: String?, authMode: AWSAuthorizationType?, - source: String = ModelProviderRegistry.DecoderSource.appSync) -> JSONValue { - + source: String = ModelProviderRegistry.DecoderSource.appSync + ) -> JSONValue { + guard case var .object(modelJSON) = graphQLData else { Amplify.API.log.debug("Not an model object: \(graphQLData)") return graphQLData @@ -89,11 +92,13 @@ public struct AppSyncModelMetadataUtils { let associatedModelType = ModelRegistry.modelType(from: associatedModelName) { // Scenario: Belongs-To Primary Keys only are available for lazy loading - if let modelIdentifierMetadata = createModelIdentifierMetadata(associatedModelType, - modelObject: modelObject, - apiName: apiName, - authMode: authMode, - source: source) { + if let modelIdentifierMetadata = createModelIdentifierMetadata( + associatedModelType, + modelObject: modelObject, + apiName: apiName, + authMode: authMode, + source: source + ) { if let serializedMetadata = try? encoder.encode(modelIdentifierMetadata), let metadataJSON = try? decoder.decode(JSONValue.self, from: serializedMetadata) { Amplify.API.log.verbose("Adding [\(modelField.name): \(metadataJSON)]") @@ -108,9 +113,11 @@ public struct AppSyncModelMetadataUtils { // add metadata to its fields, to create not loaded LazyReference objects // only if the model type allowsfor lazy loading functionality else if associatedModelType.rootPath != nil { - let nestedModelWithMetadata = addMetadata(toModel: nestedModelJSON, - apiName: apiName, - authMode: authMode) + let nestedModelWithMetadata = addMetadata( + toModel: nestedModelJSON, + apiName: apiName, + authMode: authMode + ) modelJSON.updateValue(nestedModelWithMetadata, forKey: modelField.name) } // otherwise do nothing to the data. @@ -124,10 +131,12 @@ public struct AppSyncModelMetadataUtils { // Store the association data (parent's identifier and field name) // This allows the list to perform lazy loading of child items using parent identifier as the predicate if modelJSON[modelField.name] == nil { - let appSyncModelMetadata = AppSyncListDecoder.Metadata(appSyncAssociatedIdentifiers: identifiers, - appSyncAssociatedFields: modelField.associatedFieldNames, - apiName: apiName, - authMode: authMode) + let appSyncModelMetadata = AppSyncListDecoder.Metadata( + appSyncAssociatedIdentifiers: identifiers, + appSyncAssociatedFields: modelField.associatedFieldNames, + apiName: apiName, + authMode: authMode + ) if let serializedMetadata = try? encoder.encode(appSyncModelMetadata), let metadataJSON = try? decoder.decode(JSONValue.self, from: serializedMetadata) { log.verbose("Adding [\(modelField.name): \(metadataJSON)]") @@ -148,17 +157,21 @@ public struct AppSyncModelMetadataUtils { associatedModelType.rootPath != nil { for (index, item) in graphQLDataArray.enumerated() { - let modelJSON = AppSyncModelMetadataUtils.addMetadata(toModel: item, - apiName: apiName, - authMode: authMode) + let modelJSON = AppSyncModelMetadataUtils.addMetadata( + toModel: item, + apiName: apiName, + authMode: authMode + ) graphQLDataArray[index] = modelJSON } graphQLDataObject["items"] = JSONValue.array(graphQLDataArray) - let payload = AppSyncListPayload(graphQLData: JSONValue.object(graphQLDataObject), - apiName: apiName, - authMode: authMode, - variables: nil) + let payload = AppSyncListPayload( + graphQLData: JSONValue.object(graphQLDataObject), + apiName: apiName, + authMode: authMode, + variables: nil + ) if let serializedPayload = try? encoder.encode(payload), let payloadJSON = try? decoder.decode(JSONValue.self, from: serializedPayload) { @@ -178,11 +191,13 @@ public struct AppSyncModelMetadataUtils { /// fields on the `modelObject` is useful determining if the `modelOject` is eager or lazy loaded. If the identifiers /// plus one additional field (`__typename`) doesn't match the number of keys on the `modelObject` then there /// are more keys in the `modelObject` which means it was eager loaded. - static func createModelIdentifierMetadata(_ associatedModel: Model.Type, - modelObject: [String: JSONValue], - apiName: String?, - authMode: AWSAuthorizationType?, - source: String) -> AppSyncModelDecoder.Metadata? { + static func createModelIdentifierMetadata( + _ associatedModel: Model.Type, + modelObject: [String: JSONValue], + apiName: String?, + authMode: AWSAuthorizationType?, + source: String + ) -> AppSyncModelDecoder.Metadata? { let primarykeys = associatedModel.schema.primaryKey var identifiers = [LazyReferenceIdentifier]() for identifierField in primarykeys.fields { @@ -200,7 +215,8 @@ public struct AppSyncModelMetadataUtils { identifiers: identifiers, apiName: apiName, authMode: authMode, - source: source) + source: source + ) } else { return nil } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelProvider.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelProvider.swift index cdcaa16d88..f8fcc29125 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelProvider.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelProvider.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation public class AppSyncModelProvider: ModelProvider { @@ -38,22 +38,24 @@ public class AppSyncModelProvider: ModelProvider { switch loadedState { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { - self.loadedState = .loaded(model: nil) + guard let identifiers else { + loadedState = .loaded(model: nil) return nil } - let request = GraphQLRequest.getRequest(ModelType.self, - byIdentifiers: identifiers, - apiName: apiName, - authMode: authMode) + let request = GraphQLRequest.getRequest( + ModelType.self, + byIdentifiers: identifiers, + apiName: apiName, + authMode: authMode + ) log.verbose("Loading \(ModelType.modelName) with \(identifiers)") let graphQLResponse = try await Amplify.API.query(request: request) switch graphQLResponse { case .success(let model): - self.loadedState = .loaded(model: model) + loadedState = .loaded(model: model) return model case .failure(let graphQLError): - self.log.error(error: graphQLError) + log.error(error: graphQLError) throw graphQLError } case .loaded(let element): @@ -72,7 +74,8 @@ public class AppSyncModelProvider: ModelProvider { identifiers: identifiers ?? [], apiName: apiName, authMode: authMode, - source: source) + source: source + ) try metadata.encode(to: encoder) case .loaded(let element): diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/APIKeyURLRequestInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/APIKeyURLRequestInterceptor.swift index 225d597c04..f8f360e538 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/APIKeyURLRequestInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/APIKeyURLRequestInterceptor.swift @@ -7,8 +7,8 @@ import Amplify import AWSPluginsCore -import InternalAmplifyCredentials import Foundation +import InternalAmplifyCredentials struct APIKeyURLRequestInterceptor: URLRequestInterceptor { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenProviderWrapper.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenProviderWrapper.swift index 9137c018b5..6cd1164cd0 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenProviderWrapper.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenProviderWrapper.swift @@ -7,8 +7,8 @@ import Amplify import AWSPluginsCore -import InternalAmplifyCredentials import Foundation +import InternalAmplifyCredentials class AuthTokenProviderWrapper: AuthTokenProvider { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift index 9ed5783c28..413d5c6e52 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift @@ -7,8 +7,8 @@ import Amplify import AWSPluginsCore -import InternalAmplifyCredentials import Foundation +import InternalAmplifyCredentials struct AuthTokenURLRequestInterceptor: URLRequestInterceptor { @@ -18,8 +18,10 @@ struct AuthTokenURLRequestInterceptor: URLRequestInterceptor { let authTokenProvider: AuthTokenProvider let isTokenExpired: ((String) -> Bool)? - init(authTokenProvider: AuthTokenProvider, - isTokenExpired: ((String) -> Bool)? = nil) { + init( + authTokenProvider: AuthTokenProvider, + isTokenExpired: ((String) -> Bool)? = nil + ) { self.authTokenProvider = authTokenProvider self.isTokenExpired = isTokenExpired } @@ -34,10 +36,14 @@ struct AuthTokenURLRequestInterceptor: URLRequestInterceptor { dateFormatter.dateFormat = Self.AWSDateISO8601DateFormat2 let amzDate = dateFormatter.string(from: date) - mutableRequest.setValue(amzDate, - forHTTPHeaderField: URLRequestConstants.Header.xAmzDate) - mutableRequest.addValue(userAgent, - forHTTPHeaderField: URLRequestConstants.Header.userAgent) + mutableRequest.setValue( + amzDate, + forHTTPHeaderField: URLRequestConstants.Header.xAmzDate + ) + mutableRequest.addValue( + userAgent, + forHTTPHeaderField: URLRequestConstants.Header.userAgent + ) let token: String do { @@ -45,13 +51,15 @@ struct AuthTokenURLRequestInterceptor: URLRequestInterceptor { } catch { throw APIError.operationError("Failed to retrieve authorization token.", "", error) } - + if isTokenExpired?(token) ?? false { // If the access token has expired, we send back the underlying "AuthError.sessionExpired" error. // Without a more specific AuthError case like "tokenExpired", this is the closest representation. - throw APIError.operationError("Auth Token Provider returned a expired token.", - "Please call `Amplify.Auth.fetchAuthSession()` or sign in again.", - AuthError.sessionExpired("", "", nil)) + throw APIError.operationError( + "Auth Token Provider returned a expired token.", + "Please call `Amplify.Auth.fetchAuthSession()` or sign in again.", + AuthError.sessionExpired("", "", nil) + ) } mutableRequest.setValue(token, forHTTPHeaderField: "authorization") diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift index 534f70f5da..21ebb113a4 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift @@ -7,10 +7,10 @@ import Amplify import AWSPluginsCore -import InternalAmplifyCredentials import Foundation -import SmithyHTTPAPI +import InternalAmplifyCredentials import Smithy +import SmithyHTTPAPI typealias AWSRegionType = String @@ -20,9 +20,11 @@ struct IAMURLRequestInterceptor: URLRequestInterceptor { let endpointType: AWSAPICategoryPluginEndpointType private let userAgent = AmplifyAWSServiceConfiguration.userAgentLib - init(iamCredentialsProvider: IAMCredentialsProvider, - region: AWSRegionType, - endpointType: AWSAPICategoryPluginEndpointType) { + init( + iamCredentialsProvider: IAMCredentialsProvider, + region: AWSRegionType, + endpointType: AWSAPICategoryPluginEndpointType + ) { self.iamCredentialsProvider = iamCredentialsProvider self.region = region self.endpointType = endpointType diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/APIKeyAuthInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/APIKeyAuthInterceptor.swift index 5906f7567e..3c2c41eeae 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/APIKeyAuthInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/APIKeyAuthInterceptor.swift @@ -5,9 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Amplify +import Foundation @_spi(WebSocket) import AWSPluginsCore class APIKeyAuthInterceptor { @@ -24,7 +23,7 @@ extension APIKeyAuthInterceptor: WebSocketInterceptor { func interceptConnection(request: URLRequest) async -> URLRequest { guard let url = request.url else { return request } - + let authHeader = getAuthHeader(apiKey, AppSyncRealTimeClientFactory.appSyncApiEndpoint(url).host!) return request.injectAppSyncAuthToRequestHeader(auth: .apiKey(authHeader)) } @@ -44,7 +43,7 @@ extension APIKeyAuthInterceptor: AppSyncRequestInterceptor { } } -fileprivate func authHeaderBuilder() -> (String, String) -> AppSyncRealTimeRequestAuth.ApiKey { +private func authHeaderBuilder() -> (String, String) -> AppSyncRealTimeRequestAuth.ApiKey { let formatter = DateFormatter() formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.locale = Locale(identifier: "en_US_POSIX") diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/AuthTokenInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/AuthTokenInterceptor.swift index 95f96698b1..d02283dc37 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/AuthTokenInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/AuthTokenInterceptor.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation @_spi(WebSocket) import AWSPluginsCore /// General purpose authenticatication subscriptions interceptor for providers whose only @@ -33,7 +33,7 @@ class AuthTokenInterceptor { // the authorization check, which ends up being propagated back to the caller // as a "bad request". Example of bad requests are when the header and payload // query strings are missing or when the data is not base64 encoded. - (try? await getLatestAuthToken()) ?? "" + await (try? getLatestAuthToken()) ?? "" } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift index f44000655a..493d5705c1 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation @_spi(WebSocket) import AWSPluginsCore import InternalAmplifyCredentials -import Amplify import SmithyHTTPAPI import SmithyIdentity @@ -50,11 +50,13 @@ class IAMAuthInterceptor { /// 2. The request is SigV4 signed by using all the available headers on the request. By signing the request, the signature is added to /// the request headers as authorization and security token. do { - guard let urlRequest = try await signer.sigV4SignedRequest(requestBuilder: requestBuilder, - credentialIdentityResolver: authProvider, - signingName: "appsync", - signingRegion: region, - date: Date()) else { + guard let urlRequest = try await signer.sigV4SignedRequest( + requestBuilder: requestBuilder, + credentialIdentityResolver: authProvider, + signingName: "appsync", + signingRegion: region, + date: Date() + ) else { Amplify.Logging.error("Unable to sign request") return nil } @@ -110,7 +112,8 @@ extension IAMAuthInterceptor: AppSyncRequestInterceptor { let authHeader = await getAuthHeader( AppSyncRealTimeClientFactory.appSyncApiEndpoint(url), - with: request.data) + with: request.data + ) return .start(.init( id: request.id, data: request.data, diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/APIOperationResponse.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/APIOperationResponse.swift index 0e750a66b1..709e6d4898 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/APIOperationResponse.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/APIOperationResponse.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct APIOperationResponse { let urlError: URLError? diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSAPIOperation+APIOperation.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSAPIOperation+APIOperation.swift index 99e67ac46b..4ca3693e40 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSAPIOperation+APIOperation.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSAPIOperation+APIOperation.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension AWSRESTOperation: APIOperation { func getOperationId() -> UUID { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation+APIOperation.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation+APIOperation.swift index 97cd297bee..ba48c86493 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation+APIOperation.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation+APIOperation.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension AWSGraphQLOperation: APIOperation { func getOperationId() -> UUID { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation.swift index b3a61608fb..4d39b2e001 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation.swift @@ -9,28 +9,32 @@ import Amplify import AWSPluginsCore import Foundation -final public class AWSGraphQLOperation: GraphQLOperation { +public final class AWSGraphQLOperation: GraphQLOperation { let session: URLSessionBehavior let mapper: OperationTaskMapper let pluginConfig: AWSAPICategoryPluginConfiguration let graphQLResponseDecoder: GraphQLResponseDecoder - init(request: GraphQLOperationRequest, - session: URLSessionBehavior, - mapper: OperationTaskMapper, - pluginConfig: AWSAPICategoryPluginConfiguration, - resultListener: AWSGraphQLOperation.ResultListener?) { + init( + request: GraphQLOperationRequest, + session: URLSessionBehavior, + mapper: OperationTaskMapper, + pluginConfig: AWSAPICategoryPluginConfiguration, + resultListener: AWSGraphQLOperation.ResultListener? + ) { self.session = session self.mapper = mapper self.pluginConfig = pluginConfig self.graphQLResponseDecoder = GraphQLResponseDecoder(request: request) - super.init(categoryType: .api, - eventName: request.operationType.hubEventName, - request: request, - resultListener: resultListener) + super.init( + categoryType: .api, + eventName: request.operationType.hubEventName, + request: request, + resultListener: resultListener + ) } override public func main() { @@ -119,17 +123,21 @@ final public class AWSGraphQLOperation: GraphQLOperation { private func getRequestPayload(from request: GraphQLOperationRequest) -> Result { // Prepare request payload - let queryDocument = GraphQLOperationRequestUtils.getQueryDocument(document: request.document, - variables: request.variables) + let queryDocument = GraphQLOperationRequestUtils.getQueryDocument( + document: request.document, + variables: request.variables + ) if Amplify.API.log.logLevel == .verbose, - let serializedJSON = try? JSONSerialization.data(withJSONObject: queryDocument, - options: .prettyPrinted), + let serializedJSON = try? JSONSerialization.data( + withJSONObject: queryDocument, + options: .prettyPrinted + ), let prettyPrintedQueryDocument = String(data: serializedJSON, encoding: .utf8) { Amplify.API.log.verbose("\(prettyPrintedQueryDocument)") } do { - return .success(try JSONSerialization.data(withJSONObject: queryDocument)) + return try .success(JSONSerialization.data(withJSONObject: queryDocument)) } catch { return .failure(APIError.operationError( "Failed to serialize query document", @@ -141,7 +149,7 @@ final public class AWSGraphQLOperation: GraphQLOperation { private func getEndpointConfig(from request: GraphQLOperationRequest) -> Result { do { - return .success(try pluginConfig.endpoints.getConfig(for: request.apiName, endpointType: .graphQL)) + return try .success(pluginConfig.endpoints.getConfig(for: request.apiName, endpointType: .graphQL)) } catch let error as APIError { return .failure(error) @@ -155,12 +163,12 @@ final public class AWSGraphQLOperation: GraphQLOperation { do { if let pluginOptions = request.options.pluginOptions as? AWSAPIPluginDataStoreOptions, let authType = pluginOptions.authType { - return .success(try pluginConfig.interceptorsForEndpoint( + return try .success(pluginConfig.interceptorsForEndpoint( withConfig: endpointConfig, authType: authType )) } else if let authType = request.authMode as? AWSAuthorizationType { - return .success(try pluginConfig.interceptorsForEndpoint( + return try .success(pluginConfig.interceptorsForEndpoint( withConfig: endpointConfig, authType: authType )) @@ -177,7 +185,7 @@ final public class AWSGraphQLOperation: GraphQLOperation { private func applyInterceptor(_ interceptor: URLRequestInterceptor, request: URLRequest) async -> Result { do { - return .success(try await interceptor.intercept(request)) + return try await .success(interceptor.intercept(request)) } catch let error as APIError { return .failure(error) } catch { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift index 3ee8e9856f..421808869f 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift @@ -8,8 +8,8 @@ import Amplify import Foundation @_spi(WebSocket) import AWSPluginsCore -import InternalAmplifyCredentials import Combine +import InternalAmplifyCredentials public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, InternalTaskAsyncThrowingSequence, InternalTaskThrowingChannel { @@ -22,7 +22,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, var appSyncClient: AppSyncRealTimeClientProtocol? var subscription: AnyCancellable? { willSet { - self.subscription?.cancel() + subscription?.cancel() } } let appSyncClientFactory: AppSyncRealTimeClientFactoryProtocol @@ -34,11 +34,13 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, private var running = false - init(request: Request, - pluginConfig: AWSAPICategoryPluginConfiguration, - appSyncClientFactory: AppSyncRealTimeClientFactoryProtocol, - authService: AWSAuthCredentialsProviderBehavior, - apiAuthProviderFactory: APIAuthProviderFactory) { + init( + request: Request, + pluginConfig: AWSAPICategoryPluginConfiguration, + appSyncClientFactory: AppSyncRealTimeClientFactoryProtocol, + authService: AWSAuthCredentialsProviderBehavior, + apiAuthProviderFactory: APIAuthProviderFactory + ) { self.request = request self.pluginConfig = pluginConfig self.appSyncClientFactory = appSyncClientFactory @@ -50,7 +52,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, /// In this situation, we need to send the disconnected event because /// the top-level AmplifyThrowingSequence is terminated immediately upon cancellation. public func cancel() { - self.send(GraphQLSubscriptionEvent.connection(.disconnected)) + send(GraphQLSubscriptionEvent.connection(.disconnected)) Task { guard let appSyncClient = self.appSyncClient else { return @@ -93,17 +95,16 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, return } - let authType: AWSAuthorizationType? - if let pluginOptions = request.options.pluginOptions as? AWSAPIPluginDataStoreOptions { - authType = pluginOptions.authType + let authType: AWSAuthorizationType? = if let pluginOptions = request.options.pluginOptions as? AWSAPIPluginDataStoreOptions { + pluginOptions.authType } else if let authorizationMode = request.authMode as? AWSAuthorizationType { - authType = authorizationMode + authorizationMode } else { - authType = nil + nil } // Retrieve the subscription connection do { - self.appSyncClient = try await appSyncClientFactory.getAppSyncRealTimeClient( + appSyncClient = try await appSyncClientFactory.getAppSyncRealTimeClient( for: endpointConfig, endpoint: endpointConfig.baseURL, authService: authService, @@ -112,7 +113,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, ) // Create subscription - self.subscription = try await appSyncClient?.subscribe( + subscription = try await appSyncClient?.subscribe( id: subscriptionId, query: encodeRequest(query: request.document, variables: request.variables) ).sink(receiveValue: { [weak self] event in @@ -183,7 +184,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, } // Class is still necessary. See https://github.com/aws-amplify/amplify-swift/issues/2252 -final public class AWSGraphQLSubscriptionOperation: GraphQLSubscriptionOperation { +public final class AWSGraphQLSubscriptionOperation: GraphQLSubscriptionOperation { let pluginConfig: AWSAPICategoryPluginConfiguration let appSyncRealTimeClientFactory: AppSyncRealTimeClientFactoryProtocol @@ -193,31 +194,35 @@ final public class AWSGraphQLSubscriptionOperation: GraphQLSubscri var appSyncRealTimeClient: AppSyncRealTimeClientProtocol? var subscription: AnyCancellable? { willSet { - self.subscription?.cancel() + subscription?.cancel() } } var apiAuthProviderFactory: APIAuthProviderFactory private let subscriptionId = UUID().uuidString - init(request: GraphQLOperationRequest, - pluginConfig: AWSAPICategoryPluginConfiguration, - appSyncRealTimeClientFactory: AppSyncRealTimeClientFactoryProtocol, - authService: AWSAuthCredentialsProviderBehavior, - apiAuthProviderFactory: APIAuthProviderFactory, - inProcessListener: AWSGraphQLSubscriptionOperation.InProcessListener?, - resultListener: AWSGraphQLSubscriptionOperation.ResultListener?) { + init( + request: GraphQLOperationRequest, + pluginConfig: AWSAPICategoryPluginConfiguration, + appSyncRealTimeClientFactory: AppSyncRealTimeClientFactoryProtocol, + authService: AWSAuthCredentialsProviderBehavior, + apiAuthProviderFactory: APIAuthProviderFactory, + inProcessListener: AWSGraphQLSubscriptionOperation.InProcessListener?, + resultListener: AWSGraphQLSubscriptionOperation.ResultListener? + ) { self.pluginConfig = pluginConfig self.appSyncRealTimeClientFactory = appSyncRealTimeClientFactory self.authService = authService self.apiAuthProviderFactory = apiAuthProviderFactory - super.init(categoryType: .api, - eventName: HubPayload.EventName.API.subscribe, - request: request, - inProcessListener: inProcessListener, - resultListener: resultListener) + super.init( + categoryType: .api, + eventName: HubPayload.EventName.API.subscribe, + request: request, + inProcessListener: inProcessListener, + resultListener: resultListener + ) } override public func cancel() { @@ -271,13 +276,12 @@ final public class AWSGraphQLSubscriptionOperation: GraphQLSubscri return } - let authType: AWSAuthorizationType? - if let pluginOptions = request.options.pluginOptions as? AWSAPIPluginDataStoreOptions { - authType = pluginOptions.authType + let authType: AWSAuthorizationType? = if let pluginOptions = request.options.pluginOptions as? AWSAPIPluginDataStoreOptions { + pluginOptions.authType } else if let authorizationMode = request.authMode as? AWSAuthorizationType { - authType = authorizationMode + authorizationMode } else { - authType = nil + nil } Task { do { @@ -367,7 +371,7 @@ final public class AWSGraphQLSubscriptionOperation: GraphQLSubscri } } -fileprivate func encodeRequest(query: String, variables: [String: Any]?) -> String { +private func encodeRequest(query: String, variables: [String: Any]?) -> String { var json: [String: Any] = [ "query": query ] @@ -377,18 +381,18 @@ fileprivate func encodeRequest(query: String, variables: [String: Any]?) -> Stri } do { - return String(data: try JSONSerialization.data(withJSONObject: json), encoding: .utf8)! + return try String(data: JSONSerialization.data(withJSONObject: json), encoding: .utf8)! } catch { return "" } } -fileprivate func toAPIError(_ errors: [Error], type: R.Type) -> APIError { +private func toAPIError(_ errors: [Error], type: R.Type) -> APIError { func errorDescription(_ hasAuthorizationError: Bool = false) -> String { "Subscription item event failed with error" + (hasAuthorizationError ? ": \(APIError.UnauthorizedMessageString)" : "") } - + switch errors { case let errors as [AppSyncRealTimeRequest.Error]: let hasAuthorizationError = errors.contains(where: { $0 == .unauthorized}) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSHTTPURLResponse.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSHTTPURLResponse.swift index bb4a87396d..250be888c6 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSHTTPURLResponse.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSHTTPURLResponse.swift @@ -37,10 +37,12 @@ public class AWSHTTPURLResponse: HTTPURLResponse { // Call the super class initializer with dummy values to satisfy the requirement of the inheritance. // Subsequent access to any properties of this instance (including `url`) will be delegated to // the `response`. - super.init(url: URL(string: "dummyURL")!, - statusCode: 0, - httpVersion: nil, - headerFields: nil) + super.init( + url: URL(string: "dummyURL")!, + statusCode: 0, + httpVersion: nil, + headerFields: nil + ) } required init?(coder: NSCoder) { @@ -49,45 +51,45 @@ public class AWSHTTPURLResponse: HTTPURLResponse { super.init(coder: coder) } - public override class var supportsSecureCoding: Bool { + override public class var supportsSecureCoding: Bool { return true } - public override func encode(with coder: NSCoder) { + override public func encode(with coder: NSCoder) { coder.encode(body, forKey: "body") coder.encode(response, forKey: "response") super.encode(with: coder) } - public override var url: URL? { + override public var url: URL? { response.url } - public override var mimeType: String? { + override public var mimeType: String? { response.mimeType } - public override var expectedContentLength: Int64 { + override public var expectedContentLength: Int64 { response.expectedContentLength } - public override var textEncodingName: String? { + override public var textEncodingName: String? { response.textEncodingName } - public override var suggestedFilename: String? { + override public var suggestedFilename: String? { response.suggestedFilename } - public override var statusCode: Int { + override public var statusCode: Int { response.statusCode } - public override var allHeaderFields: [AnyHashable: Any] { + override public var allHeaderFields: [AnyHashable: Any] { response.allHeaderFields } - public override func value(forHTTPHeaderField field: String) -> String? { + override public func value(forHTTPHeaderField field: String) -> String? { response.value(forHTTPHeaderField: field) } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSRESTOperation.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSRESTOperation.swift index 3680b22728..e431d9b495 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSRESTOperation.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSRESTOperation.swift @@ -8,7 +8,7 @@ import Amplify import Foundation -final public class AWSRESTOperation: AmplifyOperation< +public final class AWSRESTOperation: AmplifyOperation< RESTOperationRequest, Data, APIError @@ -21,20 +21,24 @@ final public class AWSRESTOperation: AmplifyOperation< var mapper: OperationTaskMapper let pluginConfig: AWSAPICategoryPluginConfiguration - init(request: RESTOperationRequest, - session: URLSessionBehavior, - mapper: OperationTaskMapper, - pluginConfig: AWSAPICategoryPluginConfiguration, - resultListener: AWSRESTOperation.ResultListener?) { + init( + request: RESTOperationRequest, + session: URLSessionBehavior, + mapper: OperationTaskMapper, + pluginConfig: AWSAPICategoryPluginConfiguration, + resultListener: AWSRESTOperation.ResultListener? + ) { self.session = session self.mapper = mapper self.pluginConfig = pluginConfig - super.init(categoryType: .api, - eventName: request.operationType.hubEventName, - request: request, - resultListener: resultListener) + super.init( + categoryType: .api, + eventName: request.operationType.hubEventName, + request: request, + resultListener: resultListener + ) } @@ -123,7 +127,7 @@ final public class AWSRESTOperation: AmplifyOperation< from request: RESTOperationRequest ) -> Result { do { - return .success(try pluginConfig.endpoints.getConfig(for: request.apiName, endpointType: .rest)) + return try .success(pluginConfig.endpoints.getConfig(for: request.apiName, endpointType: .rest)) } catch let error as APIError { return .failure(error) } catch { @@ -154,7 +158,7 @@ final public class AWSRESTOperation: AmplifyOperation< private func applyInterceptor(_ interceptor: URLRequestInterceptor, request: URLRequest) async -> Result { do { - return .success(try await interceptor.intercept(request)) + return try await .success(interceptor.intercept(request)) } catch let error as APIError { return .failure(error) } catch { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyReachability.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyReachability.swift index 9045d31e03..fc7fbef2b3 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyReachability.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyReachability.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + #if !os(watchOS) // swiftformat:disable fileHeader /* @@ -27,10 +34,11 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +import Foundation + // This code was taken from the 5.0.0 release // Commit SHA1: 98e968e7b6c1318fb61df23e347bc319761e8acb import SystemConfiguration -import Foundation public enum AmplifyReachabilityError: Error { case failedToCreateWithAddress(sockaddr, Int32) @@ -88,7 +96,7 @@ public class AmplifyReachability { public var allowsCellularConnection: Bool // The notification center on which "reachability changed" events are being posted - public var notificationCenter: NotificationCenter = NotificationCenter.default + public var notificationCenter: NotificationCenter = .default @available(*, deprecated, renamed: "connection.description") public var currentReachabilityString: String { @@ -132,29 +140,35 @@ public class AmplifyReachability { } } - required public init(reachabilityRef: SCNetworkReachability, - queueQoS: DispatchQoS = .default, - targetQueue: DispatchQueue? = nil, - notificationQueue: DispatchQueue? = .main) { + public required init( + reachabilityRef: SCNetworkReachability, + queueQoS: DispatchQoS = .default, + targetQueue: DispatchQueue? = nil, + notificationQueue: DispatchQueue? = .main + ) { self.allowsCellularConnection = true self.reachabilityRef = reachabilityRef self.reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", qos: queueQoS, target: targetQueue) self.notificationQueue = notificationQueue } - public convenience init(hostname: String, - queueQoS: DispatchQoS = .default, - targetQueue: DispatchQueue? = nil, - notificationQueue: DispatchQueue? = .main) throws { + public convenience init( + hostname: String, + queueQoS: DispatchQoS = .default, + targetQueue: DispatchQueue? = nil, + notificationQueue: DispatchQueue? = .main + ) throws { guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { throw AmplifyReachabilityError.failedToCreateWithHostname(hostname, SCError()) } self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue, notificationQueue: notificationQueue) } - public convenience init(queueQoS: DispatchQoS = .default, - targetQueue: DispatchQueue? = nil, - notificationQueue: DispatchQueue? = .main) throws { + public convenience init( + queueQoS: DispatchQoS = .default, + targetQueue: DispatchQueue? = nil, + notificationQueue: DispatchQueue? = .main + ) throws { var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout.size) zeroAddress.sa_family = sa_family_t(AF_INET) @@ -178,7 +192,7 @@ public extension AmplifyReachability { guard !notifierRunning else { return } let callback: SCNetworkReachabilityCallBack = { _, flags, info in - guard let info = info else { return } + guard let info else { return } // `weakifiedReachability` is guaranteed to exist by virtue of our // retain/release callbacks which we provided to the `SCNetworkReachabilityContext`. @@ -200,7 +214,7 @@ public extension AmplifyReachability { _ = unmanagedWeakifiedReachability.retain() return UnsafeRawPointer(unmanagedWeakifiedReachability.toOpaque()) }, - release: { (info: UnsafeRawPointer) -> Void in + release: { (info: UnsafeRawPointer) in let unmanagedWeakifiedReachability = Unmanaged.fromOpaque(info) unmanagedWeakifiedReachability.release() }, @@ -262,8 +276,8 @@ private extension AmplifyReachability { func setReachabilityFlags() throws { try reachabilitySerialQueue.sync { [unowned self] in var flags = SCNetworkReachabilityFlags() - if !SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags) { - self.stopNotifier() + if !SCNetworkReachabilityGetFlags(reachabilityRef, &flags) { + stopNotifier() throw AmplifyReachabilityError.unableToGetFlags(SCError()) } @@ -273,9 +287,9 @@ private extension AmplifyReachability { func notifyReachabilityChanged() { let notify = { [weak self] in - guard let self = self else { return } - self.connection != .unavailable ? self.whenReachable?(self) : self.whenUnreachable?(self) - self.notificationCenter.post(name: .reachabilityChanged, object: self) + guard let self else { return } + connection != .unavailable ? whenReachable?(self) : whenUnreachable?(self) + notificationCenter.post(name: .reachabilityChanged, object: self) } // notify on the configured `notificationQueue`, or the caller's (i.e. `reachabilitySerialQueue`) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyRechability+watchOS.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyRechability+watchOS.swift index c5bf5e5dc9..51915742f7 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyRechability+watchOS.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyRechability+watchOS.swift @@ -22,7 +22,7 @@ public class AmplifyReachability { public var allowsCellularConnection: Bool // The notification center on which "reachability changed" events are being posted - public var notificationCenter: NotificationCenter = NotificationCenter.default + public var notificationCenter: NotificationCenter = .default public var connection: AmplifyReachability.Connection { guard networkReachability.currentPath.status != .unsatisfied else { @@ -82,8 +82,8 @@ public class AmplifyReachability { public func startNotifier() throws { guard networkReachability.pathUpdateHandler == nil else { return } networkReachability.pathUpdateHandler = { [weak self] _ in - guard let self = self else { return } - self.notificationQueue.async { + guard let self else { return } + notificationQueue.async { self.notificationCenter.post(name: .reachabilityChanged, object: self) } } @@ -94,8 +94,8 @@ public class AmplifyReachability { } } -extension AmplifyReachability { - public enum Connection: CustomStringConvertible { +public extension AmplifyReachability { + enum Connection: CustomStringConvertible { @available(*, deprecated, renamed: "unavailable") case none case unavailable, wifi, cellular diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/NetworkReachabilityNotifier.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/NetworkReachabilityNotifier.swift index 5a6b0212fa..d814ca9236 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/NetworkReachabilityNotifier.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/NetworkReachabilityNotifier.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import Combine +import Foundation class NetworkReachabilityNotifier { private var reachability: NetworkReachabilityProviding? @@ -19,9 +19,11 @@ class NetworkReachabilityNotifier { return reachabilityPublisher.eraseToAnyPublisher() } - public init(host: String, - allowsCellularAccess: Bool, - reachabilityFactory: NetworkReachabilityProvidingFactory.Type) throws { + public init( + host: String, + allowsCellularAccess: Bool, + reachabilityFactory: NetworkReachabilityProvidingFactory.Type + ) throws { #if os(watchOS) self.reachability = reachabilityFactory.make() #else @@ -30,10 +32,12 @@ class NetworkReachabilityNotifier { self.allowsCellularAccess = allowsCellularAccess // Add listener for Reachability and start its notifier - NotificationCenter.default.addObserver(self, - selector: #selector(respondToReachabilityChange), - name: .reachabilityChanged, - object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(respondToReachabilityChange), + name: .reachabilityChanged, + object: nil + ) do { try reachability?.startNotifier() } catch { @@ -49,18 +53,17 @@ class NetworkReachabilityNotifier { // MARK: - Notifications @objc private func respondToReachabilityChange() { - guard let reachability = reachability else { + guard let reachability else { return } - let isReachable: Bool - switch reachability.connection { + let isReachable: Bool = switch reachability.connection { case .wifi: - isReachable = true + true case .cellular: - isReachable = allowsCellularAccess + allowsCellularAccess case .none, .unavailable: - isReachable = false + false } let reachabilityMessageUpdate = ReachabilityUpdate(isOnline: isReachable) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/SubscriptionFactory/AWSOIDCAuthProvider.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/SubscriptionFactory/AWSOIDCAuthProvider.swift index 1887aa1b06..f062dc9594 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/SubscriptionFactory/AWSOIDCAuthProvider.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/SubscriptionFactory/AWSOIDCAuthProvider.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation class AWSOIDCAuthProvider { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/SubscriptionFactory/AppSyncRealTimeClientFactory.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/SubscriptionFactory/AppSyncRealTimeClientFactory.swift index 9f30e88c8f..d99fdd1dda 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/SubscriptionFactory/AppSyncRealTimeClientFactory.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/SubscriptionFactory/AppSyncRealTimeClientFactory.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Amplify import Combine +import Foundation import InternalAmplifyCredentials @_spi(WebSocket) import AWSPluginsCore @@ -47,8 +46,8 @@ actor AppSyncRealTimeClientFactory: AppSyncRealTimeClientFactoryProtocol { ) throws -> AppSyncRealTimeClientProtocol { let apiName = endpointConfig.name - let authInterceptor = try self.getInterceptor( - for: self.getOrCreateAuthConfiguration(from: endpointConfig, authType: authType), + let authInterceptor = try getInterceptor( + for: getOrCreateAuthConfiguration(from: endpointConfig, authType: authType), authService: authService, apiAuthProviderFactory: apiAuthProviderFactory ) @@ -101,20 +100,24 @@ actor AppSyncRealTimeClientFactory: AppSyncRealTimeClientFactoryProtocol { let provider = AWSOIDCAuthProvider(authService: authService) return AuthTokenInterceptor(getLatestAuthToken: provider.getLatestAuthToken) case .awsIAM(let awsIAMConfiguration): - return IAMAuthInterceptor(authService.getCredentialIdentityResolver(), - region: awsIAMConfiguration.region) + return IAMAuthInterceptor( + authService.getCredentialIdentityResolver(), + region: awsIAMConfiguration.region + ) case .openIDConnect: guard let oidcAuthProvider = apiAuthProviderFactory.oidcAuthProvider() else { throw APIError.invalidConfiguration( "Using openIDConnect requires passing in an APIAuthProvider with an OIDC AuthProvider", - "When instantiating AWSAPIPlugin pass in an instance of APIAuthProvider", nil) + "When instantiating AWSAPIPlugin pass in an instance of APIAuthProvider", nil + ) } return AuthTokenInterceptor(getLatestAuthToken: oidcAuthProvider.getLatestAuthToken) case .function: guard let functionAuthProvider = apiAuthProviderFactory.functionAuthProvider() else { throw APIError.invalidConfiguration( "Using function as auth provider requires passing in an APIAuthProvider with a Function AuthProvider", - "When instantiating AWSAPIPlugin pass in an instance of APIAuthProvider", nil) + "When instantiating AWSAPIPlugin pass in an instance of APIAuthProvider", nil + ) } return AuthTokenInterceptor(authTokenProvider: functionAuthProvider) case .none: diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Constants/URLRequestConstants.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Constants/URLRequestConstants.swift index 2cc34b8235..37f3f921ed 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Constants/URLRequestConstants.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Constants/URLRequestConstants.swift @@ -8,11 +8,11 @@ import Foundation // TODO: remove this https://github.com/aws-amplify/amplify-ios/issues/75 -struct URLRequestConstants { +enum URLRequestConstants { static let appSyncServiceName = "appsync" static let apiGatewayServiceName = "execute-api" - struct Header { + enum Header { static let xAmzDate = "X-Amz-Date" static let contentType = "Content-Type" static let userAgent = "User-Agent" @@ -21,7 +21,7 @@ struct URLRequestConstants { static let webSocketSubprotocols = "Sec-WebSocket-Protocol" } - struct ContentType { + enum ContentType { static let applicationJson = "application/json" } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLErrorDecoder.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLErrorDecoder.swift index f6c80c047c..3e3b6a95f6 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLErrorDecoder.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLErrorDecoder.swift @@ -8,7 +8,7 @@ import Amplify import Foundation -struct GraphQLErrorDecoder { +enum GraphQLErrorDecoder { static func decodeErrors(graphQLErrors: [JSONValue]) throws -> [GraphQLError] { var responseErrors = [GraphQLError]() for error in graphQLErrors { @@ -60,17 +60,19 @@ struct GraphQLErrorDecoder { return graphQLError } - graphQLErrorObject.forEach { key, value in + for (key, value) in graphQLErrorObject { if keys.contains(key) { - return + continue } mergedExtensions[key] = value } - return GraphQLError(message: graphQLError.message, - locations: graphQLError.locations, - path: graphQLError.path, - extensions: mergedExtensions.isEmpty ? nil : mergedExtensions) + return GraphQLError( + message: graphQLError.message, + locations: graphQLError.locations, + path: graphQLError.path, + extensions: mergedExtensions.isEmpty ? nil : mergedExtensions + ) } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder+DecodeData.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder+DecodeData.swift index 425a0c46c5..cb195b1b28 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder+DecodeData.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder+DecodeData.swift @@ -14,7 +14,7 @@ extension GraphQLResponseDecoder { /* The sequence of `responseType` checking attempts to decode to specific types before falling back to (5) serializing the data and letting the default decode run its course (6). - + 1. String, special case where the object is serialized as a JSON string. 2. AnyModel, used by DataStore's sync engine 3. ModelListMarker, checks if it is a List type, inject additional information to create a loaded list. @@ -47,31 +47,36 @@ extension GraphQLResponseDecoder { case .object(var graphQLDataObject) = graphQLData, case .array(var graphQLDataArray) = graphQLDataObject["items"] { for (index, item) in graphQLDataArray.enumerated() { - let modelJSON: JSONValue - if let _ = (request.options.pluginOptions as? AWSAPIPluginDataStoreOptions) { - modelJSON = AppSyncModelMetadataUtils.addMetadata( + let modelJSON: JSONValue = if let _ = (request.options.pluginOptions as? AWSAPIPluginDataStoreOptions) { + AppSyncModelMetadataUtils.addMetadata( toModel: item, apiName: request.apiName, authMode: request.authMode as? AWSAuthorizationType, - source: ModelProviderRegistry.DecoderSource.dataStore) + source: ModelProviderRegistry.DecoderSource.dataStore + ) } else { - modelJSON = AppSyncModelMetadataUtils.addMetadata( + AppSyncModelMetadataUtils.addMetadata( toModel: item, apiName: request.apiName, - authMode: request.authMode as? AWSAuthorizationType) + authMode: request.authMode as? AWSAuthorizationType + ) } graphQLDataArray[index] = modelJSON } graphQLDataObject["items"] = JSONValue.array(graphQLDataArray) - let payload = AppSyncListPayload(graphQLData: JSONValue.object(graphQLDataObject), - apiName: request.apiName, - authMode: request.authMode as? AWSAuthorizationType, - variables: try getVariablesJSON()) + let payload = try AppSyncListPayload( + graphQLData: JSONValue.object(graphQLDataObject), + apiName: request.apiName, + authMode: request.authMode as? AWSAuthorizationType, + variables: getVariablesJSON() + ) serializedJSON = try encoder.encode(payload) } else if AppSyncModelMetadataUtils.shouldAddMetadata(toModel: graphQLData) { // 4 - let modelJSON = AppSyncModelMetadataUtils.addMetadata(toModel: graphQLData, - apiName: request.apiName, - authMode: request.authMode as? AWSAuthorizationType) + let modelJSON = AppSyncModelMetadataUtils.addMetadata( + toModel: graphQLData, + apiName: request.apiName, + authMode: request.authMode as? AWSAuthorizationType + ) serializedJSON = try encoder.encode(modelJSON) } else { // 5 serializedJSON = try encoder.encode(graphQLData) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder.swift index a80a16e4b3..0aa330d50e 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation class GraphQLResponseDecoder { @@ -45,13 +45,16 @@ class GraphQLResponseDecoder { case .invalidResponse: guard let rawGraphQLResponseString = String(data: response, encoding: .utf8) else { throw APIError.operationError( - "Could not get the String representation of the GraphQL response", "") + "Could not get the String representation of the GraphQL response", "" + ) } - throw APIError.unknown("The service returned some data without any `data` and `errors`", - """ + throw APIError.unknown( + "The service returned some data without any `data` and `errors`", + """ The service did not return an expected GraphQL response: \ \(rawGraphQLResponseString) - """) + """ + ) } } @@ -63,7 +66,8 @@ class GraphQLResponseDecoder { let error = APIError(error: decodingError) guard let rawGraphQLResponseString = String(data: response, encoding: .utf8) else { throw APIError.operationError( - "Could not get the String representation of the GraphQL response", "") + "Could not get the String representation of the GraphQL response", "" + ) } return GraphQLResponse.failure(.transformationError(rawGraphQLResponseString, error)) } catch { @@ -76,8 +80,10 @@ class GraphQLResponseDecoder { return GraphQLResponse.failure(.error(responseErrors)) } - func decodePartial(graphQLData: [String: JSONValue], - graphQLErrors: [JSONValue]) throws -> GraphQLResponse { + func decodePartial( + graphQLData: [String: JSONValue], + graphQLErrors: [JSONValue] + ) throws -> GraphQLResponse { do { if let first = graphQLData.first, case .null = first.value { let responseErrors = try GraphQLErrorDecoder.decodeErrors(graphQLErrors: graphQLErrors) @@ -90,7 +96,8 @@ class GraphQLResponseDecoder { let error = APIError(error: decodingError) guard let rawGraphQLResponseString = String(data: response, encoding: .utf8) else { throw APIError.operationError( - "Could not get the String representation of the GraphQL response", "") + "Could not get the String representation of the GraphQL response", "" + ) } return GraphQLResponse.failure(.transformationError(rawGraphQLResponseString, error)) } catch { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Internal/AWSAppSyncGraphQLResponse.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Internal/AWSAppSyncGraphQLResponse.swift index dd16b335b1..c0aae13474 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Internal/AWSAppSyncGraphQLResponse.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Internal/AWSAppSyncGraphQLResponse.swift @@ -45,14 +45,18 @@ enum AWSAppSyncGraphQLResponse { decoder.dateDecodingStrategy = ModelDateFormatting.decodingStrategy json = try decoder.decode(JSONValue.self, from: graphQLResponse) } catch { - throw APIError.operationError("Could not decode to JSONValue from the GraphQL Response", - "Service issue", - error) + throw APIError.operationError( + "Could not decode to JSONValue from the GraphQL Response", + "Service issue", + error + ) } guard case .object(let jsonObject) = json else { - throw APIError.unknown("The GraphQL response is not an object", - "The AppSync service returned a malformed GraphQL response") + throw APIError.unknown( + "The GraphQL response is not an object", + "The AppSync service returned a malformed GraphQL response" + ) } return jsonObject @@ -64,8 +68,10 @@ enum AWSAppSyncGraphQLResponse { } guard case .array(let errorArray) = errors else { - throw APIError.unknown("The GraphQL response containing errors should be an array", - "The AppSync service returned a malformed GraphQL response") + throw APIError.unknown( + "The GraphQL response containing errors should be an array", + "The AppSync service returned a malformed GraphQL response" + ) } return errorArray @@ -82,8 +88,10 @@ enum AWSAppSyncGraphQLResponse { case .null: return nil default: - throw APIError.unknown("Failed to get object or null from data.", - "The AppSync service returned a malformed GraphQL response") + throw APIError.unknown( + "Failed to get object or null from data.", + "The AppSync service returned a malformed GraphQL response" + ) } } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/APIError+DecodingError.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/APIError+DecodingError.swift index 2426474dc4..c63b4751b2 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/APIError+DecodingError.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/APIError+DecodingError.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation // TODO: Extract context and fill out better error handling diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/AnyModel+JSONInit.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/AnyModel+JSONInit.swift index 3578239708..80daef24dd 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/AnyModel+JSONInit.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/AnyModel+JSONInit.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation extension AnyModel { /// Initializes an AnyModel instance from incoming JSONValue. The JSONValue is expected to be provided by the AWS @@ -27,7 +27,8 @@ extension AnyModel { } guard let underlyingModelData = try? JSONEncoder().encode(modelJSON), - let underlyingModelString = String(data: underlyingModelData, encoding: .utf8) else { + let underlyingModelString = String(data: underlyingModelData, encoding: .utf8) + else { throw APIError.operationError( "Could not convert model data to string", """ @@ -42,9 +43,11 @@ extension AnyModel { let decoder = JSONDecoder() decoder.dateDecodingStrategy = ModelDateFormatting.decodingStrategy - let model = try ModelRegistry.decode(modelName: typename, - from: underlyingModelString, - jsonDecoder: decoder) + let model = try ModelRegistry.decode( + modelName: typename, + from: underlyingModelString, + jsonDecoder: decoder + ) self.init(model) } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/Array+Error+TypeCast.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/Array+Error+TypeCast.swift index 3592791dc2..703b5d7ea7 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/Array+Error+TypeCast.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/Array+Error+TypeCast.swift @@ -5,13 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation @_spi(AmplifyAPI) -extension Array where Element == Error { +extension [Error] { func cast(to type: T.Type) -> [T]? { - self.reduce([]) { partialResult, ele in + reduce([]) { partialResult, ele in if let partialResult, let ele = ele as? T { return partialResult + [ele] } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLOperationRequest+Validate.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLOperationRequest+Validate.swift index 1faa65afde..b110375135 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLOperationRequest+Validate.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLOperationRequest+Validate.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension GraphQLOperationRequest { // Performs client side validation and returns a `APIError` for any validation failures diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLOperationRequestUtils+Validator.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLOperationRequestUtils+Validator.swift index b8e1a6ae65..e8266c1403 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLOperationRequestUtils+Validator.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLOperationRequestUtils+Validator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension GraphQLOperationRequestUtils { @@ -17,7 +17,7 @@ extension GraphQLOperationRequestUtils { } static func validateVariables(_ variables: [String: Any]?) throws { - if let variables = variables { + if let variables { if !JSONSerialization.isValidJSONObject(variables) { throw APIError.operationError("Variables is a not a valid JSON object", "") diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLOperationRequestUtils.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLOperationRequestUtils.swift index 80e7bc74df..88e49368c0 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLOperationRequestUtils.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLOperationRequestUtils.swift @@ -12,7 +12,7 @@ class GraphQLOperationRequestUtils { // Get the graphQL request payload from the query document and variables static func getQueryDocument(document: String, variables: [String: Any]?) -> [String: Any] { var queryDocument = ["query": document] as [String: Any] - if let variables = variables { + if let variables { queryDocument["variables"] = variables } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toListQuery.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toListQuery.swift index d023097d9d..cdcf856acf 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toListQuery.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toListQuery.swift @@ -11,45 +11,57 @@ import AWSPluginsCore extension GraphQLRequest { /// Retrieve a GraphQL List operation request - static func listQuery(responseType: ResponseType.Type, - modelSchema: ModelSchema, - filter: [String: Any]? = nil, - limit: Int? = nil, - nextToken: String? = nil, - apiName: String? = nil, - authMode: AWSAuthorizationType?) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, - operationType: .query) + static func listQuery( + responseType: ResponseType.Type, + modelSchema: ModelSchema, + filter: [String: Any]? = nil, + limit: Int? = nil, + nextToken: String? = nil, + apiName: String? = nil, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelSchema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) - if let filter = filter { + if let filter { documentBuilder.add(decorator: FilterDecorator(filter: filter)) } documentBuilder.add(decorator: PaginationDecorator(limit: limit, nextToken: nextToken)) let document = documentBuilder.build() - return GraphQLRequest(apiName: apiName, - document: document.stringValue, - variables: document.variables, - responseType: responseType.self, - decodePath: document.name, - authMode: authMode) + return GraphQLRequest( + apiName: apiName, + document: document.stringValue, + variables: document.variables, + responseType: responseType.self, + decodePath: document.name, + authMode: authMode + ) } - static func getRequest(_ modelType: M.Type, - byIdentifiers identifiers: [LazyReferenceIdentifier], - apiName: String?, - authMode: AWSAuthorizationType?) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .query) + static func getRequest( + _ modelType: M.Type, + byIdentifiers identifiers: [LazyReferenceIdentifier], + apiName: String?, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: ModelIdDecorator(identifiers: identifiers)) let document = documentBuilder.build() - return GraphQLRequest(apiName: apiName, - document: document.stringValue, - variables: document.variables, - responseType: M?.self, - decodePath: document.name, - authMode: authMode) + return GraphQLRequest( + apiName: apiName, + document: document.stringValue, + variables: document.variables, + responseType: M?.self, + decodePath: document.name, + authMode: authMode + ) } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toOperationRequest.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toOperationRequest.swift index ba518bbe6e..a6d24d7961 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toOperationRequest.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toOperationRequest.swift @@ -10,13 +10,15 @@ import Amplify extension GraphQLRequest { func toOperationRequest(operationType: GraphQLOperationType) -> GraphQLOperationRequest { let requestOptions = GraphQLOperationRequest.Options(pluginOptions: options?.pluginOptions) - return GraphQLOperationRequest(apiName: apiName, - operationType: operationType, - document: document, - variables: variables, - responseType: responseType, - decodePath: decodePath, - authMode: authMode, - options: requestOptions) + return GraphQLOperationRequest( + apiName: apiName, + operationType: operationType, + document: document, + variables: variables, + responseType: responseType, + decodePath: decodePath, + authMode: authMode, + options: requestOptions + ) } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequest+RESTRequest.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequest+RESTRequest.swift index 40f99d7dc4..947ebbcdc1 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequest+RESTRequest.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequest+RESTRequest.swift @@ -9,12 +9,14 @@ import Amplify extension RESTOperationRequest { init(request: RESTRequest, operationType: RESTOperationType) { - self = RESTOperationRequest(apiName: request.apiName, - operationType: operationType, - path: request.path, - headers: request.headers, - queryParameters: request.queryParameters, - body: request.body, - options: RESTOperationRequest.Options()) + self = RESTOperationRequest( + apiName: request.apiName, + operationType: operationType, + path: request.path, + headers: request.headers, + queryParameters: request.queryParameters, + body: request.body, + options: RESTOperationRequest.Options() + ) } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequest+Validate.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequest+Validate.swift index 570e4c7d88..27185229fe 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequest+Validate.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequest+Validate.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension RESTOperationRequest { // Performs client side validation and returns a `APIError` for any validation failures func validate() throws { - if let apiName = apiName { + if let apiName { try RESTOperationRequestUtils.validateApiName(apiName) } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequestUtils+Validator.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequestUtils+Validator.swift index dd56377d91..10736575bb 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequestUtils+Validator.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequestUtils+Validator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension RESTOperationRequestUtils { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequestUtils.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequestUtils.swift index a73f46eaae..7ee535e1bb 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequestUtils.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/RESTOperationRequestUtils.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation final class RESTOperationRequestUtils { private init() {} @@ -29,11 +29,11 @@ final class RESTOperationRequestUtils { ) } - if let path = path { + if let path { components.path.append(path) } - if let queryParameters = queryParameters { + if let queryParameters { components.queryItems = try prepareQueryParamsForSigning(params: queryParameters) } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/URLRequest+AppSyncAuth.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/URLRequest+AppSyncAuth.swift index c186934f8d..ffec10753c 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/URLRequest+AppSyncAuth.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/URLRequest+AppSyncAuth.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation extension URLRequest { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/URLSessionBehavior/OperationTaskMapper.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/URLSessionBehavior/OperationTaskMapper.swift index b649290614..00266cfccd 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/URLSessionBehavior/OperationTaskMapper.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/URLSessionBehavior/OperationTaskMapper.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Maps operations, which conform to `APIOperation`, to URLSessionTaskBehaviors and /// provides convenience methods for accessing them @@ -79,11 +79,11 @@ class OperationTaskMapper { /// Not inherently thread safe--this must be called from `concurrencyQueue` private func removePair(operationId: UUID?, taskId: Int?) { dispatchPrecondition(condition: .onQueue(Self.concurrencyQueue)) - if let operationId = operationId { + if let operationId { operations[operationId] = nil taskIdsByOperationId[operationId] = nil } - if let taskId = taskId { + if let taskId { tasks[taskId] = nil operationIdsByTaskId[taskId] = nil } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/URLSessionBehavior/URLSessionBehaviorDelegate.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/URLSessionBehavior/URLSessionBehaviorDelegate.swift index c8bb175d85..d30027b188 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/URLSessionBehavior/URLSessionBehaviorDelegate.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/URLSessionBehavior/URLSessionBehaviorDelegate.swift @@ -9,13 +9,17 @@ import Foundation /// Defines URLSession behaviors used during fulfillment of API tasks public protocol URLSessionBehaviorDelegate: AnyObject { - func urlSessionBehavior(_ session: URLSessionBehavior, - dataTaskBehavior: URLSessionDataTaskBehavior, - didCompleteWithError error: Error?) + func urlSessionBehavior( + _ session: URLSessionBehavior, + dataTaskBehavior: URLSessionDataTaskBehavior, + didCompleteWithError error: Error? + ) - func urlSessionBehavior(_ session: URLSessionBehavior, - dataTaskBehavior: URLSessionDataTaskBehavior, - didReceive data: Data) + func urlSessionBehavior( + _ session: URLSessionBehavior, + dataTaskBehavior: URLSessionDataTaskBehavior, + didReceive data: Data + ) } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/URLSessionBehavior/URLSessionFactory.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/URLSessionBehavior/URLSessionFactory.swift index 706f790aa3..1eccd804de 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/URLSessionBehavior/URLSessionFactory.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/URLSessionBehavior/URLSessionFactory.swift @@ -13,9 +13,11 @@ struct URLSessionFactory: URLSessionBehaviorFactory { func makeSession(withDelegate delegate: URLSessionBehaviorDelegate?) -> URLSessionBehavior { let urlSessionDelegate = delegate?.asURLSessionDelegate - let session = URLSession(configuration: configuration, - delegate: urlSessionDelegate, - delegateQueue: delegateQueue) + let session = URLSession( + configuration: configuration, + delegate: urlSessionDelegate, + delegateQueue: delegateQueue + ) return session } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/APIHostApp/SubscriptionView.swift b/AmplifyPlugins/API/Tests/APIHostApp/APIHostApp/SubscriptionView.swift index 5f29525508..afc43d900d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/APIHostApp/SubscriptionView.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/APIHostApp/SubscriptionView.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import SwiftUI +import Amplify import AWSAPIPlugin import AWSPluginsCore -import Amplify +import SwiftUI public extension AsyncSequence { func forEach(_ block: (Element) async throws -> Void) async rethrows { @@ -19,7 +19,7 @@ public extension AsyncSequence { } class SubscriptionViewModel: ObservableObject { - + @Published var todos = [Todo]() let apiPlugin = AWSAPIPlugin() @@ -29,12 +29,12 @@ class SubscriptionViewModel: ObservableObject { try await subscription.forEach { subscriptionEvent in await self.processSubscription(subscriptionEvent) } - + } catch { print("Failed to subscribe error: \(error)") } } - + func processSubscription(_ subscriptionEvent: GraphQLSubscriptionEvent) async { switch subscriptionEvent { case .connection(let subscriptionConnectionState): @@ -49,29 +49,29 @@ class SubscriptionViewModel: ObservableObject { } } } - + @MainActor func storeTodo(_ todo: Todo) async { - self.todos.append(todo) + todos.append(todo) } } @available(iOS 14.0, *) struct SubscriptionView: View { @StateObject var vm = SubscriptionViewModel() - + var body: some View { if #available(iOS 15.0, *) { VStack { - + }.task { await vm.subscribe() } - + } else { // Fallback on earlier versions Text("task is on iOS 15.0") } - + } - + } @available(iOS 14.0, *) @@ -86,35 +86,38 @@ public struct Todo: Model { public var name: String public var description: String? - public init(id: String = UUID().uuidString, - name: String, - description: String? = nil) { + public init( + id: String = UUID().uuidString, + name: String, + description: String? = nil + ) { self.id = id self.name = name self.description = description } } -extension Todo { +public extension Todo { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case description } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todo = Todo.keys model.listPluralName = "Todos" model.syncPluralName = "Todos" model.fields( - .id(), - .field(todo.name, is: .required, ofType: .string), - .field(todo.description, is: .optional, ofType: .string)) + .id(), + .field(todo.name, is: .required, ofType: .string), + .field(todo.description, is: .optional, ofType: .string) + ) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/API.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/API.swift index 81f1b87158..4b17109a40 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/API.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/API.swift @@ -1,26 +1,34 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // This file was automatically generated and should not be edited. #if canImport(AWSAPIPlugin) import Foundation + public protocol GraphQLInputValue { } public struct GraphQLVariable { let name: String - + public init(_ name: String) { self.name = name } } extension GraphQLVariable: GraphQLInputValue { } -extension JSONEncodable { - public func evaluate(with variables: [String: JSONEncodable]?) throws -> Any { +public extension JSONEncodable { + func evaluate(with variables: [String: JSONEncodable]?) throws -> Any { return jsonValue } } public typealias GraphQLMap = [String: JSONEncodable?] -extension Dictionary where Key == String, Value == JSONEncodable? { - public var withNilValuesRemoved: Dictionary { - var filtered = Dictionary(minimumCapacity: count) +public extension [String: JSONEncodable?] { + var withNilValuesRemoved: [String: JSONEncodable] { + var filtered = [String: JSONEncodable](minimumCapacity: count) for (key, value) in self { if value != nil { filtered[key] = value @@ -39,13 +47,13 @@ public extension GraphQLMapConvertible { } public typealias GraphQLID = String public protocol APISwiftGraphQLOperation: AnyObject { - + static var operationString: String { get } static var requestString: String { get } static var operationIdentifier: String? { get } - + var variables: GraphQLMap? { get } - + associatedtype Data: GraphQLSelectionSet } public extension APISwiftGraphQLOperation { @@ -68,12 +76,12 @@ public protocol GraphQLFragment: GraphQLSelectionSet { public typealias Snapshot = [String: Any?] public protocol GraphQLSelectionSet: Decodable { static var selections: [GraphQLSelection] { get } - + var snapshot: Snapshot { get } init(snapshot: Snapshot) } -extension GraphQLSelectionSet { - public init(from decoder: Decoder) throws { +public extension GraphQLSelectionSet { + init(from decoder: Decoder) throws { if let jsonObject = try? APISwiftJSONValue(from: decoder) { let encoder = JSONEncoder() let jsonData = try encoder.encode(jsonObject) @@ -92,10 +100,10 @@ enum APISwiftJSONValue: Codable { case object([String: APISwiftJSONValue]) case string(String) case null - + init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() - + if let value = try? container.decode([String: APISwiftJSONValue].self) { self = .object(value) } else if let value = try? container.decode([APISwiftJSONValue].self) { @@ -110,10 +118,10 @@ enum APISwiftJSONValue: Codable { self = .null } } - + func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() - + switch self { case .array(let value): try container.encode(value) @@ -136,19 +144,19 @@ public struct GraphQLField: GraphQLSelection { let name: String let alias: String? let arguments: [String: GraphQLInputValue]? - + var responseKey: String { return alias ?? name } - + let type: GraphQLOutputType - + public init(_ name: String, alias: String? = nil, arguments: [String: GraphQLInputValue]? = nil, type: GraphQLOutputType) { self.name = name self.alias = alias - + self.arguments = arguments - + self.type = type } } @@ -157,7 +165,7 @@ public indirect enum GraphQLOutputType { case object([GraphQLSelection]) case nonNull(GraphQLOutputType) case list(GraphQLOutputType) - + var namedType: GraphQLOutputType { switch self { case .nonNull(let innerType), .list(let innerType): @@ -171,25 +179,25 @@ public struct GraphQLBooleanCondition: GraphQLSelection { let variableName: String let inverted: Bool let selections: [GraphQLSelection] - + public init(variableName: String, inverted: Bool, selections: [GraphQLSelection]) { self.variableName = variableName - self.inverted = inverted; - self.selections = selections; + self.inverted = inverted + self.selections = selections } } public struct GraphQLTypeCondition: GraphQLSelection { let possibleTypes: [String] let selections: [GraphQLSelection] - + public init(possibleTypes: [String], selections: [GraphQLSelection]) { self.possibleTypes = possibleTypes - self.selections = selections; + self.selections = selections } } public struct GraphQLFragmentSpread: GraphQLSelection { let fragment: GraphQLFragment.Type - + public init(_ fragment: GraphQLFragment.Type) { self.fragment = fragment } @@ -197,10 +205,10 @@ public struct GraphQLFragmentSpread: GraphQLSelection { public struct GraphQLTypeCase: GraphQLSelection { let variants: [String: [GraphQLSelection]] let `default`: [GraphQLSelection] - + public init(variants: [String: [GraphQLSelection]], default: [GraphQLSelection]) { self.variants = variants - self.default = `default`; + self.default = `default` } } public typealias JSONObject = [String: Any] @@ -215,7 +223,7 @@ public enum JSONDecodingError: Error, LocalizedError { case nullValue case wrongType case couldNotConvert(value: Any, to: Any.Type) - + public var errorDescription: String? { switch self { case .missingValue: @@ -284,8 +292,8 @@ extension Bool: JSONDecodable, JSONEncodable { return self } } -extension RawRepresentable where RawValue: JSONDecodable { - public init(jsonValue value: Any) throws { +public extension RawRepresentable where RawValue: JSONDecodable { + init(jsonValue value: Any) throws { let rawValue = try RawValue(jsonValue: value) if let tempSelf = Self(rawValue: rawValue) { self = tempSelf @@ -294,17 +302,17 @@ extension RawRepresentable where RawValue: JSONDecodable { } } } -extension RawRepresentable where RawValue: JSONEncodable { - public var jsonValue: Any { +public extension RawRepresentable where RawValue: JSONEncodable { + var jsonValue: Any { return rawValue.jsonValue } } -extension Optional where Wrapped: JSONDecodable { - public init(jsonValue value: Any) throws { +public extension Optional where Wrapped: JSONDecodable { + init(jsonValue value: Any) throws { if value is NSNull { self = .none } else { - self = .some(try Wrapped(jsonValue: value)) + self = try .some(Wrapped(jsonValue: value)) } } } @@ -324,7 +332,7 @@ extension Dictionary: JSONEncodable { public var jsonValue: Any { return jsonObject } - + public var jsonObject: JSONObject { var jsonObject = JSONObject(minimumCapacity: count) for (key, value) in self { @@ -339,7 +347,7 @@ extension Dictionary: JSONEncodable { } extension Array: JSONEncodable { public var jsonValue: Any { - return map() { element -> (Any) in + return map { element -> (Any) in if case let element as JSONEncodable = element { return element.jsonValue } else { @@ -356,12 +364,12 @@ extension URL: JSONDecodable, JSONEncodable { self.init(string: string)! } public var jsonValue: Any { - return self.absoluteString + return absoluteString } } extension Dictionary { static func += (lhs: inout Dictionary, rhs: Dictionary) { - lhs.merge(rhs) { (_, new) in new } + lhs.merge(rhs) { _, new in new } } } #elseif canImport(AWSAppSync) @@ -369,15 +377,15 @@ import AWSAppSync #endif public struct APISwift { - - + + public struct CreatePostInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, title: String, content: String, createdAt: String? = nil, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil) { - graphQLMap = ["id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status] + self.graphQLMap = ["id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -386,7 +394,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return graphQLMap["title"] as! String @@ -395,7 +403,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return graphQLMap["content"] as! String @@ -404,7 +412,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var createdAt: String? { get { return graphQLMap["createdAt"] as! String? @@ -413,7 +421,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return graphQLMap["updatedAt"] as! String? @@ -422,7 +430,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return graphQLMap["draft"] as! Bool? @@ -431,7 +439,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return graphQLMap["rating"] as! Double? @@ -440,7 +448,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return graphQLMap["status"] as! PostStatus? @@ -450,7 +458,7 @@ public struct APISwift { } } } - + public enum PostStatus: RawRepresentable, Equatable, JSONDecodable, JSONEncodable { public typealias RawValue = String case `private` @@ -458,7 +466,7 @@ public struct APISwift { case published /// Auto generated constant for unknown enum values case unknown(RawValue) - + public init?(rawValue: RawValue) { switch rawValue { case "PRIVATE": self = .private @@ -467,7 +475,7 @@ public struct APISwift { default: self = .unknown(rawValue) } } - + public var rawValue: RawValue { switch self { case .private: return "PRIVATE" @@ -476,7 +484,7 @@ public struct APISwift { case .unknown(let value): return value } } - + public static func == (lhs: PostStatus, rhs: PostStatus) -> Bool { switch (lhs, rhs) { case (.private, .private): return true @@ -487,14 +495,14 @@ public struct APISwift { } } } - + public struct ModelPostConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(title: ModelStringInput? = nil, content: ModelStringInput? = nil, createdAt: ModelStringInput? = nil, updatedAt: ModelStringInput? = nil, draft: ModelBooleanInput? = nil, rating: ModelFloatInput? = nil, status: ModelPostStatusInput? = nil, and: [ModelPostConditionInput?]? = nil, or: [ModelPostConditionInput?]? = nil, not: ModelPostConditionInput? = nil) { - graphQLMap = ["title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "and": and, "or": or, "not": not] + self.graphQLMap = ["title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "and": and, "or": or, "not": not] } - + public var title: ModelStringInput? { get { return graphQLMap["title"] as! ModelStringInput? @@ -503,7 +511,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var content: ModelStringInput? { get { return graphQLMap["content"] as! ModelStringInput? @@ -512,7 +520,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var createdAt: ModelStringInput? { get { return graphQLMap["createdAt"] as! ModelStringInput? @@ -521,7 +529,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: ModelStringInput? { get { return graphQLMap["updatedAt"] as! ModelStringInput? @@ -530,7 +538,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: ModelBooleanInput? { get { return graphQLMap["draft"] as! ModelBooleanInput? @@ -539,7 +547,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "draft") } } - + public var rating: ModelFloatInput? { get { return graphQLMap["rating"] as! ModelFloatInput? @@ -548,7 +556,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "rating") } } - + public var status: ModelPostStatusInput? { get { return graphQLMap["status"] as! ModelPostStatusInput? @@ -557,7 +565,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "status") } } - + public var and: [ModelPostConditionInput?]? { get { return graphQLMap["and"] as! [ModelPostConditionInput?]? @@ -566,7 +574,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelPostConditionInput?]? { get { return graphQLMap["or"] as! [ModelPostConditionInput?]? @@ -575,7 +583,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelPostConditionInput? { get { return graphQLMap["not"] as! ModelPostConditionInput? @@ -585,14 +593,14 @@ public struct APISwift { } } } - + public struct ModelStringInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(ne: String? = nil, eq: String? = nil, le: String? = nil, lt: String? = nil, ge: String? = nil, gt: String? = nil, contains: String? = nil, notContains: String? = nil, between: [String?]? = nil, beginsWith: String? = nil, attributeExists: Bool? = nil, attributeType: ModelAttributeTypes? = nil, size: ModelSizeInput? = nil) { - graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "contains": contains, "notContains": notContains, "between": between, "beginsWith": beginsWith, "attributeExists": attributeExists, "attributeType": attributeType, "size": size] + self.graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "contains": contains, "notContains": notContains, "between": between, "beginsWith": beginsWith, "attributeExists": attributeExists, "attributeType": attributeType, "size": size] } - + public var ne: String? { get { return graphQLMap["ne"] as! String? @@ -601,7 +609,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var eq: String? { get { return graphQLMap["eq"] as! String? @@ -610,7 +618,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var le: String? { get { return graphQLMap["le"] as! String? @@ -619,7 +627,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "le") } } - + public var lt: String? { get { return graphQLMap["lt"] as! String? @@ -628,7 +636,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "lt") } } - + public var ge: String? { get { return graphQLMap["ge"] as! String? @@ -637,7 +645,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ge") } } - + public var gt: String? { get { return graphQLMap["gt"] as! String? @@ -646,7 +654,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "gt") } } - + public var contains: String? { get { return graphQLMap["contains"] as! String? @@ -655,7 +663,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "contains") } } - + public var notContains: String? { get { return graphQLMap["notContains"] as! String? @@ -664,7 +672,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "notContains") } } - + public var between: [String?]? { get { return graphQLMap["between"] as! [String?]? @@ -673,7 +681,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "between") } } - + public var beginsWith: String? { get { return graphQLMap["beginsWith"] as! String? @@ -682,7 +690,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "beginsWith") } } - + public var attributeExists: Bool? { get { return graphQLMap["attributeExists"] as! Bool? @@ -691,7 +699,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeExists") } } - + public var attributeType: ModelAttributeTypes? { get { return graphQLMap["attributeType"] as! ModelAttributeTypes? @@ -700,7 +708,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeType") } } - + public var size: ModelSizeInput? { get { return graphQLMap["size"] as! ModelSizeInput? @@ -710,7 +718,7 @@ public struct APISwift { } } } - + public enum ModelAttributeTypes: RawRepresentable, Equatable, JSONDecodable, JSONEncodable { public typealias RawValue = String case binary @@ -725,7 +733,7 @@ public struct APISwift { case null /// Auto generated constant for unknown enum values case unknown(RawValue) - + public init?(rawValue: RawValue) { switch rawValue { case "binary": self = .binary @@ -741,7 +749,7 @@ public struct APISwift { default: self = .unknown(rawValue) } } - + public var rawValue: RawValue { switch self { case .binary: return "binary" @@ -757,7 +765,7 @@ public struct APISwift { case .unknown(let value): return value } } - + public static func == (lhs: ModelAttributeTypes, rhs: ModelAttributeTypes) -> Bool { switch (lhs, rhs) { case (.binary, .binary): return true @@ -775,14 +783,14 @@ public struct APISwift { } } } - + public struct ModelSizeInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(ne: Int? = nil, eq: Int? = nil, le: Int? = nil, lt: Int? = nil, ge: Int? = nil, gt: Int? = nil, between: [Int?]? = nil) { - graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "between": between] + self.graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "between": between] } - + public var ne: Int? { get { return graphQLMap["ne"] as! Int? @@ -791,7 +799,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var eq: Int? { get { return graphQLMap["eq"] as! Int? @@ -800,7 +808,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var le: Int? { get { return graphQLMap["le"] as! Int? @@ -809,7 +817,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "le") } } - + public var lt: Int? { get { return graphQLMap["lt"] as! Int? @@ -818,7 +826,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "lt") } } - + public var ge: Int? { get { return graphQLMap["ge"] as! Int? @@ -827,7 +835,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ge") } } - + public var gt: Int? { get { return graphQLMap["gt"] as! Int? @@ -836,7 +844,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "gt") } } - + public var between: [Int?]? { get { return graphQLMap["between"] as! [Int?]? @@ -846,14 +854,14 @@ public struct APISwift { } } } - + public struct ModelBooleanInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(ne: Bool? = nil, eq: Bool? = nil, attributeExists: Bool? = nil, attributeType: ModelAttributeTypes? = nil) { - graphQLMap = ["ne": ne, "eq": eq, "attributeExists": attributeExists, "attributeType": attributeType] + self.graphQLMap = ["ne": ne, "eq": eq, "attributeExists": attributeExists, "attributeType": attributeType] } - + public var ne: Bool? { get { return graphQLMap["ne"] as! Bool? @@ -862,7 +870,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var eq: Bool? { get { return graphQLMap["eq"] as! Bool? @@ -871,7 +879,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var attributeExists: Bool? { get { return graphQLMap["attributeExists"] as! Bool? @@ -880,7 +888,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeExists") } } - + public var attributeType: ModelAttributeTypes? { get { return graphQLMap["attributeType"] as! ModelAttributeTypes? @@ -890,14 +898,14 @@ public struct APISwift { } } } - + public struct ModelFloatInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(ne: Double? = nil, eq: Double? = nil, le: Double? = nil, lt: Double? = nil, ge: Double? = nil, gt: Double? = nil, between: [Double?]? = nil, attributeExists: Bool? = nil, attributeType: ModelAttributeTypes? = nil) { - graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "between": between, "attributeExists": attributeExists, "attributeType": attributeType] + self.graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "between": between, "attributeExists": attributeExists, "attributeType": attributeType] } - + public var ne: Double? { get { return graphQLMap["ne"] as! Double? @@ -906,7 +914,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var eq: Double? { get { return graphQLMap["eq"] as! Double? @@ -915,7 +923,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var le: Double? { get { return graphQLMap["le"] as! Double? @@ -924,7 +932,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "le") } } - + public var lt: Double? { get { return graphQLMap["lt"] as! Double? @@ -933,7 +941,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "lt") } } - + public var ge: Double? { get { return graphQLMap["ge"] as! Double? @@ -942,7 +950,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ge") } } - + public var gt: Double? { get { return graphQLMap["gt"] as! Double? @@ -951,7 +959,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "gt") } } - + public var between: [Double?]? { get { return graphQLMap["between"] as! [Double?]? @@ -960,7 +968,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "between") } } - + public var attributeExists: Bool? { get { return graphQLMap["attributeExists"] as! Bool? @@ -969,7 +977,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeExists") } } - + public var attributeType: ModelAttributeTypes? { get { return graphQLMap["attributeType"] as! ModelAttributeTypes? @@ -979,14 +987,14 @@ public struct APISwift { } } } - + public struct ModelPostStatusInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(eq: PostStatus? = nil, ne: PostStatus? = nil) { - graphQLMap = ["eq": eq, "ne": ne] + self.graphQLMap = ["eq": eq, "ne": ne] } - + public var eq: PostStatus? { get { return graphQLMap["eq"] as! PostStatus? @@ -995,7 +1003,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var ne: PostStatus? { get { return graphQLMap["ne"] as! PostStatus? @@ -1005,14 +1013,14 @@ public struct APISwift { } } } - + public struct UpdatePostInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, title: String? = nil, content: String? = nil, createdAt: String? = nil, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil) { - graphQLMap = ["id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status] + self.graphQLMap = ["id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1021,7 +1029,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: String? { get { return graphQLMap["title"] as! String? @@ -1030,7 +1038,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var content: String? { get { return graphQLMap["content"] as! String? @@ -1039,7 +1047,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var createdAt: String? { get { return graphQLMap["createdAt"] as! String? @@ -1048,7 +1056,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return graphQLMap["updatedAt"] as! String? @@ -1057,7 +1065,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return graphQLMap["draft"] as! Bool? @@ -1066,7 +1074,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return graphQLMap["rating"] as! Double? @@ -1075,7 +1083,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return graphQLMap["status"] as! PostStatus? @@ -1085,14 +1093,14 @@ public struct APISwift { } } } - + public struct DeletePostInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1102,14 +1110,14 @@ public struct APISwift { } } } - + public struct CreateCommentInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, content: String, createdAt: String? = nil, commentPostId: GraphQLID? = nil) { - graphQLMap = ["id": id, "content": content, "createdAt": createdAt, "commentPostId": commentPostId] + self.graphQLMap = ["id": id, "content": content, "createdAt": createdAt, "commentPostId": commentPostId] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -1118,7 +1126,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return graphQLMap["content"] as! String @@ -1127,7 +1135,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var createdAt: String? { get { return graphQLMap["createdAt"] as! String? @@ -1136,7 +1144,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "createdAt") } } - + public var commentPostId: GraphQLID? { get { return graphQLMap["commentPostId"] as! GraphQLID? @@ -1146,14 +1154,14 @@ public struct APISwift { } } } - + public struct ModelCommentConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(content: ModelStringInput? = nil, createdAt: ModelStringInput? = nil, and: [ModelCommentConditionInput?]? = nil, or: [ModelCommentConditionInput?]? = nil, not: ModelCommentConditionInput? = nil) { - graphQLMap = ["content": content, "createdAt": createdAt, "and": and, "or": or, "not": not] + self.graphQLMap = ["content": content, "createdAt": createdAt, "and": and, "or": or, "not": not] } - + public var content: ModelStringInput? { get { return graphQLMap["content"] as! ModelStringInput? @@ -1162,7 +1170,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var createdAt: ModelStringInput? { get { return graphQLMap["createdAt"] as! ModelStringInput? @@ -1171,7 +1179,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "createdAt") } } - + public var and: [ModelCommentConditionInput?]? { get { return graphQLMap["and"] as! [ModelCommentConditionInput?]? @@ -1180,7 +1188,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelCommentConditionInput?]? { get { return graphQLMap["or"] as! [ModelCommentConditionInput?]? @@ -1189,7 +1197,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelCommentConditionInput? { get { return graphQLMap["not"] as! ModelCommentConditionInput? @@ -1199,14 +1207,14 @@ public struct APISwift { } } } - + public struct UpdateCommentInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, content: String? = nil, createdAt: String? = nil, commentPostId: GraphQLID? = nil) { - graphQLMap = ["id": id, "content": content, "createdAt": createdAt, "commentPostId": commentPostId] + self.graphQLMap = ["id": id, "content": content, "createdAt": createdAt, "commentPostId": commentPostId] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1215,7 +1223,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var content: String? { get { return graphQLMap["content"] as! String? @@ -1224,7 +1232,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var createdAt: String? { get { return graphQLMap["createdAt"] as! String? @@ -1233,7 +1241,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "createdAt") } } - + public var commentPostId: GraphQLID? { get { return graphQLMap["commentPostId"] as! GraphQLID? @@ -1243,14 +1251,14 @@ public struct APISwift { } } } - + public struct DeleteCommentInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1260,14 +1268,14 @@ public struct APISwift { } } } - + public struct CreateProject1Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, name: String? = nil, project1TeamId: GraphQLID? = nil) { - graphQLMap = ["id": id, "name": name, "project1TeamId": project1TeamId] + self.graphQLMap = ["id": id, "name": name, "project1TeamId": project1TeamId] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -1276,7 +1284,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return graphQLMap["name"] as! String? @@ -1285,7 +1293,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var project1TeamId: GraphQLID? { get { return graphQLMap["project1TeamId"] as! GraphQLID? @@ -1295,14 +1303,14 @@ public struct APISwift { } } } - + public struct ModelProject1ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(name: ModelStringInput? = nil, and: [ModelProject1ConditionInput?]? = nil, or: [ModelProject1ConditionInput?]? = nil, not: ModelProject1ConditionInput? = nil) { - graphQLMap = ["name": name, "and": and, "or": or, "not": not] + self.graphQLMap = ["name": name, "and": and, "or": or, "not": not] } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -1311,7 +1319,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var and: [ModelProject1ConditionInput?]? { get { return graphQLMap["and"] as! [ModelProject1ConditionInput?]? @@ -1320,7 +1328,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelProject1ConditionInput?]? { get { return graphQLMap["or"] as! [ModelProject1ConditionInput?]? @@ -1329,7 +1337,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelProject1ConditionInput? { get { return graphQLMap["not"] as! ModelProject1ConditionInput? @@ -1339,14 +1347,14 @@ public struct APISwift { } } } - + public struct UpdateProject1Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, name: String? = nil, project1TeamId: GraphQLID? = nil) { - graphQLMap = ["id": id, "name": name, "project1TeamId": project1TeamId] + self.graphQLMap = ["id": id, "name": name, "project1TeamId": project1TeamId] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1355,7 +1363,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return graphQLMap["name"] as! String? @@ -1364,7 +1372,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var project1TeamId: GraphQLID? { get { return graphQLMap["project1TeamId"] as! GraphQLID? @@ -1374,14 +1382,14 @@ public struct APISwift { } } } - + public struct DeleteProject1Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1391,14 +1399,14 @@ public struct APISwift { } } } - + public struct CreateTeam1Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, name: String) { - graphQLMap = ["id": id, "name": name] + self.graphQLMap = ["id": id, "name": name] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -1407,7 +1415,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return graphQLMap["name"] as! String @@ -1417,14 +1425,14 @@ public struct APISwift { } } } - + public struct ModelTeam1ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(name: ModelStringInput? = nil, and: [ModelTeam1ConditionInput?]? = nil, or: [ModelTeam1ConditionInput?]? = nil, not: ModelTeam1ConditionInput? = nil) { - graphQLMap = ["name": name, "and": and, "or": or, "not": not] + self.graphQLMap = ["name": name, "and": and, "or": or, "not": not] } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -1433,7 +1441,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var and: [ModelTeam1ConditionInput?]? { get { return graphQLMap["and"] as! [ModelTeam1ConditionInput?]? @@ -1442,7 +1450,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelTeam1ConditionInput?]? { get { return graphQLMap["or"] as! [ModelTeam1ConditionInput?]? @@ -1451,7 +1459,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelTeam1ConditionInput? { get { return graphQLMap["not"] as! ModelTeam1ConditionInput? @@ -1461,14 +1469,14 @@ public struct APISwift { } } } - + public struct UpdateTeam1Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, name: String? = nil) { - graphQLMap = ["id": id, "name": name] + self.graphQLMap = ["id": id, "name": name] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1477,7 +1485,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return graphQLMap["name"] as! String? @@ -1487,14 +1495,14 @@ public struct APISwift { } } } - + public struct DeleteTeam1Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1504,14 +1512,14 @@ public struct APISwift { } } } - + public struct CreateProject2Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, name: String? = nil, teamId: GraphQLID) { - graphQLMap = ["id": id, "name": name, "teamID": teamId] + self.graphQLMap = ["id": id, "name": name, "teamID": teamId] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -1520,7 +1528,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return graphQLMap["name"] as! String? @@ -1529,7 +1537,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var teamId: GraphQLID { get { return graphQLMap["teamID"] as! GraphQLID @@ -1539,14 +1547,14 @@ public struct APISwift { } } } - + public struct ModelProject2ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(name: ModelStringInput? = nil, teamId: ModelIDInput? = nil, and: [ModelProject2ConditionInput?]? = nil, or: [ModelProject2ConditionInput?]? = nil, not: ModelProject2ConditionInput? = nil) { - graphQLMap = ["name": name, "teamID": teamId, "and": and, "or": or, "not": not] + self.graphQLMap = ["name": name, "teamID": teamId, "and": and, "or": or, "not": not] } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -1555,7 +1563,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var teamId: ModelIDInput? { get { return graphQLMap["teamID"] as! ModelIDInput? @@ -1564,7 +1572,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "teamID") } } - + public var and: [ModelProject2ConditionInput?]? { get { return graphQLMap["and"] as! [ModelProject2ConditionInput?]? @@ -1573,7 +1581,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelProject2ConditionInput?]? { get { return graphQLMap["or"] as! [ModelProject2ConditionInput?]? @@ -1582,7 +1590,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelProject2ConditionInput? { get { return graphQLMap["not"] as! ModelProject2ConditionInput? @@ -1592,14 +1600,14 @@ public struct APISwift { } } } - + public struct ModelIDInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(ne: GraphQLID? = nil, eq: GraphQLID? = nil, le: GraphQLID? = nil, lt: GraphQLID? = nil, ge: GraphQLID? = nil, gt: GraphQLID? = nil, contains: GraphQLID? = nil, notContains: GraphQLID? = nil, between: [GraphQLID?]? = nil, beginsWith: GraphQLID? = nil, attributeExists: Bool? = nil, attributeType: ModelAttributeTypes? = nil, size: ModelSizeInput? = nil) { - graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "contains": contains, "notContains": notContains, "between": between, "beginsWith": beginsWith, "attributeExists": attributeExists, "attributeType": attributeType, "size": size] + self.graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "contains": contains, "notContains": notContains, "between": between, "beginsWith": beginsWith, "attributeExists": attributeExists, "attributeType": attributeType, "size": size] } - + public var ne: GraphQLID? { get { return graphQLMap["ne"] as! GraphQLID? @@ -1608,7 +1616,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var eq: GraphQLID? { get { return graphQLMap["eq"] as! GraphQLID? @@ -1617,7 +1625,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var le: GraphQLID? { get { return graphQLMap["le"] as! GraphQLID? @@ -1626,7 +1634,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "le") } } - + public var lt: GraphQLID? { get { return graphQLMap["lt"] as! GraphQLID? @@ -1635,7 +1643,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "lt") } } - + public var ge: GraphQLID? { get { return graphQLMap["ge"] as! GraphQLID? @@ -1644,7 +1652,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ge") } } - + public var gt: GraphQLID? { get { return graphQLMap["gt"] as! GraphQLID? @@ -1653,7 +1661,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "gt") } } - + public var contains: GraphQLID? { get { return graphQLMap["contains"] as! GraphQLID? @@ -1662,7 +1670,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "contains") } } - + public var notContains: GraphQLID? { get { return graphQLMap["notContains"] as! GraphQLID? @@ -1671,7 +1679,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "notContains") } } - + public var between: [GraphQLID?]? { get { return graphQLMap["between"] as! [GraphQLID?]? @@ -1680,7 +1688,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "between") } } - + public var beginsWith: GraphQLID? { get { return graphQLMap["beginsWith"] as! GraphQLID? @@ -1689,7 +1697,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "beginsWith") } } - + public var attributeExists: Bool? { get { return graphQLMap["attributeExists"] as! Bool? @@ -1698,7 +1706,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeExists") } } - + public var attributeType: ModelAttributeTypes? { get { return graphQLMap["attributeType"] as! ModelAttributeTypes? @@ -1707,7 +1715,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeType") } } - + public var size: ModelSizeInput? { get { return graphQLMap["size"] as! ModelSizeInput? @@ -1717,14 +1725,14 @@ public struct APISwift { } } } - + public struct UpdateProject2Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, name: String? = nil, teamId: GraphQLID? = nil) { - graphQLMap = ["id": id, "name": name, "teamID": teamId] + self.graphQLMap = ["id": id, "name": name, "teamID": teamId] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1733,7 +1741,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return graphQLMap["name"] as! String? @@ -1742,7 +1750,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var teamId: GraphQLID? { get { return graphQLMap["teamID"] as! GraphQLID? @@ -1752,14 +1760,14 @@ public struct APISwift { } } } - + public struct DeleteProject2Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1769,14 +1777,14 @@ public struct APISwift { } } } - + public struct CreateTeam2Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, name: String) { - graphQLMap = ["id": id, "name": name] + self.graphQLMap = ["id": id, "name": name] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -1785,7 +1793,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return graphQLMap["name"] as! String @@ -1795,14 +1803,14 @@ public struct APISwift { } } } - + public struct ModelTeam2ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(name: ModelStringInput? = nil, and: [ModelTeam2ConditionInput?]? = nil, or: [ModelTeam2ConditionInput?]? = nil, not: ModelTeam2ConditionInput? = nil) { - graphQLMap = ["name": name, "and": and, "or": or, "not": not] + self.graphQLMap = ["name": name, "and": and, "or": or, "not": not] } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -1811,7 +1819,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var and: [ModelTeam2ConditionInput?]? { get { return graphQLMap["and"] as! [ModelTeam2ConditionInput?]? @@ -1820,7 +1828,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelTeam2ConditionInput?]? { get { return graphQLMap["or"] as! [ModelTeam2ConditionInput?]? @@ -1829,7 +1837,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelTeam2ConditionInput? { get { return graphQLMap["not"] as! ModelTeam2ConditionInput? @@ -1839,14 +1847,14 @@ public struct APISwift { } } } - + public struct UpdateTeam2Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, name: String? = nil) { - graphQLMap = ["id": id, "name": name] + self.graphQLMap = ["id": id, "name": name] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1855,7 +1863,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return graphQLMap["name"] as! String? @@ -1865,14 +1873,14 @@ public struct APISwift { } } } - + public struct DeleteTeam2Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1882,14 +1890,14 @@ public struct APISwift { } } } - + public struct CreatePost3Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, title: String) { - graphQLMap = ["id": id, "title": title] + self.graphQLMap = ["id": id, "title": title] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -1898,7 +1906,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return graphQLMap["title"] as! String @@ -1908,14 +1916,14 @@ public struct APISwift { } } } - + public struct ModelPost3ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(title: ModelStringInput? = nil, and: [ModelPost3ConditionInput?]? = nil, or: [ModelPost3ConditionInput?]? = nil, not: ModelPost3ConditionInput? = nil) { - graphQLMap = ["title": title, "and": and, "or": or, "not": not] + self.graphQLMap = ["title": title, "and": and, "or": or, "not": not] } - + public var title: ModelStringInput? { get { return graphQLMap["title"] as! ModelStringInput? @@ -1924,7 +1932,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var and: [ModelPost3ConditionInput?]? { get { return graphQLMap["and"] as! [ModelPost3ConditionInput?]? @@ -1933,7 +1941,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelPost3ConditionInput?]? { get { return graphQLMap["or"] as! [ModelPost3ConditionInput?]? @@ -1942,7 +1950,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelPost3ConditionInput? { get { return graphQLMap["not"] as! ModelPost3ConditionInput? @@ -1952,14 +1960,14 @@ public struct APISwift { } } } - + public struct UpdatePost3Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, title: String? = nil) { - graphQLMap = ["id": id, "title": title] + self.graphQLMap = ["id": id, "title": title] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1968,7 +1976,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: String? { get { return graphQLMap["title"] as! String? @@ -1978,14 +1986,14 @@ public struct APISwift { } } } - + public struct DeletePost3Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -1995,14 +2003,14 @@ public struct APISwift { } } } - + public struct CreateComment3Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, postId: GraphQLID, content: String) { - graphQLMap = ["id": id, "postID": postId, "content": content] + self.graphQLMap = ["id": id, "postID": postId, "content": content] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -2011,7 +2019,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return graphQLMap["postID"] as! GraphQLID @@ -2020,7 +2028,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return graphQLMap["content"] as! String @@ -2030,14 +2038,14 @@ public struct APISwift { } } } - + public struct ModelComment3ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(postId: ModelIDInput? = nil, content: ModelStringInput? = nil, and: [ModelComment3ConditionInput?]? = nil, or: [ModelComment3ConditionInput?]? = nil, not: ModelComment3ConditionInput? = nil) { - graphQLMap = ["postID": postId, "content": content, "and": and, "or": or, "not": not] + self.graphQLMap = ["postID": postId, "content": content, "and": and, "or": or, "not": not] } - + public var postId: ModelIDInput? { get { return graphQLMap["postID"] as! ModelIDInput? @@ -2046,7 +2054,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var content: ModelStringInput? { get { return graphQLMap["content"] as! ModelStringInput? @@ -2055,7 +2063,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var and: [ModelComment3ConditionInput?]? { get { return graphQLMap["and"] as! [ModelComment3ConditionInput?]? @@ -2064,7 +2072,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelComment3ConditionInput?]? { get { return graphQLMap["or"] as! [ModelComment3ConditionInput?]? @@ -2073,7 +2081,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelComment3ConditionInput? { get { return graphQLMap["not"] as! ModelComment3ConditionInput? @@ -2083,14 +2091,14 @@ public struct APISwift { } } } - + public struct UpdateComment3Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, postId: GraphQLID? = nil, content: String? = nil) { - graphQLMap = ["id": id, "postID": postId, "content": content] + self.graphQLMap = ["id": id, "postID": postId, "content": content] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2099,7 +2107,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID? { get { return graphQLMap["postID"] as! GraphQLID? @@ -2108,7 +2116,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var content: String? { get { return graphQLMap["content"] as! String? @@ -2118,14 +2126,14 @@ public struct APISwift { } } } - + public struct DeleteComment3Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2135,14 +2143,14 @@ public struct APISwift { } } } - + public struct CreatePost4Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, title: String) { - graphQLMap = ["id": id, "title": title] + self.graphQLMap = ["id": id, "title": title] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -2151,7 +2159,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return graphQLMap["title"] as! String @@ -2161,14 +2169,14 @@ public struct APISwift { } } } - + public struct ModelPost4ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(title: ModelStringInput? = nil, and: [ModelPost4ConditionInput?]? = nil, or: [ModelPost4ConditionInput?]? = nil, not: ModelPost4ConditionInput? = nil) { - graphQLMap = ["title": title, "and": and, "or": or, "not": not] + self.graphQLMap = ["title": title, "and": and, "or": or, "not": not] } - + public var title: ModelStringInput? { get { return graphQLMap["title"] as! ModelStringInput? @@ -2177,7 +2185,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var and: [ModelPost4ConditionInput?]? { get { return graphQLMap["and"] as! [ModelPost4ConditionInput?]? @@ -2186,7 +2194,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelPost4ConditionInput?]? { get { return graphQLMap["or"] as! [ModelPost4ConditionInput?]? @@ -2195,7 +2203,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelPost4ConditionInput? { get { return graphQLMap["not"] as! ModelPost4ConditionInput? @@ -2205,14 +2213,14 @@ public struct APISwift { } } } - + public struct UpdatePost4Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, title: String? = nil) { - graphQLMap = ["id": id, "title": title] + self.graphQLMap = ["id": id, "title": title] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2221,7 +2229,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: String? { get { return graphQLMap["title"] as! String? @@ -2231,14 +2239,14 @@ public struct APISwift { } } } - + public struct DeletePost4Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2248,14 +2256,14 @@ public struct APISwift { } } } - + public struct CreateComment4Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, postId: GraphQLID, content: String) { - graphQLMap = ["id": id, "postID": postId, "content": content] + self.graphQLMap = ["id": id, "postID": postId, "content": content] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -2264,7 +2272,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return graphQLMap["postID"] as! GraphQLID @@ -2273,7 +2281,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return graphQLMap["content"] as! String @@ -2283,14 +2291,14 @@ public struct APISwift { } } } - + public struct ModelComment4ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(postId: ModelIDInput? = nil, content: ModelStringInput? = nil, and: [ModelComment4ConditionInput?]? = nil, or: [ModelComment4ConditionInput?]? = nil, not: ModelComment4ConditionInput? = nil) { - graphQLMap = ["postID": postId, "content": content, "and": and, "or": or, "not": not] + self.graphQLMap = ["postID": postId, "content": content, "and": and, "or": or, "not": not] } - + public var postId: ModelIDInput? { get { return graphQLMap["postID"] as! ModelIDInput? @@ -2299,7 +2307,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var content: ModelStringInput? { get { return graphQLMap["content"] as! ModelStringInput? @@ -2308,7 +2316,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var and: [ModelComment4ConditionInput?]? { get { return graphQLMap["and"] as! [ModelComment4ConditionInput?]? @@ -2317,7 +2325,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelComment4ConditionInput?]? { get { return graphQLMap["or"] as! [ModelComment4ConditionInput?]? @@ -2326,7 +2334,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelComment4ConditionInput? { get { return graphQLMap["not"] as! ModelComment4ConditionInput? @@ -2336,14 +2344,14 @@ public struct APISwift { } } } - + public struct UpdateComment4Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, postId: GraphQLID? = nil, content: String? = nil) { - graphQLMap = ["id": id, "postID": postId, "content": content] + self.graphQLMap = ["id": id, "postID": postId, "content": content] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2352,7 +2360,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID? { get { return graphQLMap["postID"] as! GraphQLID? @@ -2361,7 +2369,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var content: String? { get { return graphQLMap["content"] as! String? @@ -2371,14 +2379,14 @@ public struct APISwift { } } } - + public struct DeleteComment4Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2388,14 +2396,14 @@ public struct APISwift { } } } - + public struct CreatePost5Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, title: String) { - graphQLMap = ["id": id, "title": title] + self.graphQLMap = ["id": id, "title": title] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -2404,7 +2412,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return graphQLMap["title"] as! String @@ -2414,14 +2422,14 @@ public struct APISwift { } } } - + public struct ModelPost5ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(title: ModelStringInput? = nil, and: [ModelPost5ConditionInput?]? = nil, or: [ModelPost5ConditionInput?]? = nil, not: ModelPost5ConditionInput? = nil) { - graphQLMap = ["title": title, "and": and, "or": or, "not": not] + self.graphQLMap = ["title": title, "and": and, "or": or, "not": not] } - + public var title: ModelStringInput? { get { return graphQLMap["title"] as! ModelStringInput? @@ -2430,7 +2438,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var and: [ModelPost5ConditionInput?]? { get { return graphQLMap["and"] as! [ModelPost5ConditionInput?]? @@ -2439,7 +2447,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelPost5ConditionInput?]? { get { return graphQLMap["or"] as! [ModelPost5ConditionInput?]? @@ -2448,7 +2456,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelPost5ConditionInput? { get { return graphQLMap["not"] as! ModelPost5ConditionInput? @@ -2458,14 +2466,14 @@ public struct APISwift { } } } - + public struct UpdatePost5Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, title: String? = nil) { - graphQLMap = ["id": id, "title": title] + self.graphQLMap = ["id": id, "title": title] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2474,7 +2482,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: String? { get { return graphQLMap["title"] as! String? @@ -2484,14 +2492,14 @@ public struct APISwift { } } } - + public struct DeletePost5Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2501,14 +2509,14 @@ public struct APISwift { } } } - + public struct CreatePostEditor5Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, postId: GraphQLID, editorId: GraphQLID) { - graphQLMap = ["id": id, "postID": postId, "editorID": editorId] + self.graphQLMap = ["id": id, "postID": postId, "editorID": editorId] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -2517,7 +2525,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return graphQLMap["postID"] as! GraphQLID @@ -2526,7 +2534,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return graphQLMap["editorID"] as! GraphQLID @@ -2536,14 +2544,14 @@ public struct APISwift { } } } - + public struct ModelPostEditor5ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(postId: ModelIDInput? = nil, editorId: ModelIDInput? = nil, and: [ModelPostEditor5ConditionInput?]? = nil, or: [ModelPostEditor5ConditionInput?]? = nil, not: ModelPostEditor5ConditionInput? = nil) { - graphQLMap = ["postID": postId, "editorID": editorId, "and": and, "or": or, "not": not] + self.graphQLMap = ["postID": postId, "editorID": editorId, "and": and, "or": or, "not": not] } - + public var postId: ModelIDInput? { get { return graphQLMap["postID"] as! ModelIDInput? @@ -2552,7 +2560,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var editorId: ModelIDInput? { get { return graphQLMap["editorID"] as! ModelIDInput? @@ -2561,7 +2569,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "editorID") } } - + public var and: [ModelPostEditor5ConditionInput?]? { get { return graphQLMap["and"] as! [ModelPostEditor5ConditionInput?]? @@ -2570,7 +2578,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelPostEditor5ConditionInput?]? { get { return graphQLMap["or"] as! [ModelPostEditor5ConditionInput?]? @@ -2579,7 +2587,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelPostEditor5ConditionInput? { get { return graphQLMap["not"] as! ModelPostEditor5ConditionInput? @@ -2589,14 +2597,14 @@ public struct APISwift { } } } - + public struct UpdatePostEditor5Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, postId: GraphQLID? = nil, editorId: GraphQLID? = nil) { - graphQLMap = ["id": id, "postID": postId, "editorID": editorId] + self.graphQLMap = ["id": id, "postID": postId, "editorID": editorId] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2605,7 +2613,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID? { get { return graphQLMap["postID"] as! GraphQLID? @@ -2614,7 +2622,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID? { get { return graphQLMap["editorID"] as! GraphQLID? @@ -2624,14 +2632,14 @@ public struct APISwift { } } } - + public struct DeletePostEditor5Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2641,14 +2649,14 @@ public struct APISwift { } } } - + public struct CreateUser5Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, username: String) { - graphQLMap = ["id": id, "username": username] + self.graphQLMap = ["id": id, "username": username] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -2657,7 +2665,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return graphQLMap["username"] as! String @@ -2667,14 +2675,14 @@ public struct APISwift { } } } - + public struct ModelUser5ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(username: ModelStringInput? = nil, and: [ModelUser5ConditionInput?]? = nil, or: [ModelUser5ConditionInput?]? = nil, not: ModelUser5ConditionInput? = nil) { - graphQLMap = ["username": username, "and": and, "or": or, "not": not] + self.graphQLMap = ["username": username, "and": and, "or": or, "not": not] } - + public var username: ModelStringInput? { get { return graphQLMap["username"] as! ModelStringInput? @@ -2683,7 +2691,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "username") } } - + public var and: [ModelUser5ConditionInput?]? { get { return graphQLMap["and"] as! [ModelUser5ConditionInput?]? @@ -2692,7 +2700,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelUser5ConditionInput?]? { get { return graphQLMap["or"] as! [ModelUser5ConditionInput?]? @@ -2701,7 +2709,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelUser5ConditionInput? { get { return graphQLMap["not"] as! ModelUser5ConditionInput? @@ -2711,14 +2719,14 @@ public struct APISwift { } } } - + public struct UpdateUser5Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, username: String? = nil) { - graphQLMap = ["id": id, "username": username] + self.graphQLMap = ["id": id, "username": username] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2727,7 +2735,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var username: String? { get { return graphQLMap["username"] as! String? @@ -2737,14 +2745,14 @@ public struct APISwift { } } } - + public struct DeleteUser5Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2754,14 +2762,14 @@ public struct APISwift { } } } - + public struct CreateBlog6Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, name: String) { - graphQLMap = ["id": id, "name": name] + self.graphQLMap = ["id": id, "name": name] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -2770,7 +2778,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return graphQLMap["name"] as! String @@ -2780,14 +2788,14 @@ public struct APISwift { } } } - + public struct ModelBlog6ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(name: ModelStringInput? = nil, and: [ModelBlog6ConditionInput?]? = nil, or: [ModelBlog6ConditionInput?]? = nil, not: ModelBlog6ConditionInput? = nil) { - graphQLMap = ["name": name, "and": and, "or": or, "not": not] + self.graphQLMap = ["name": name, "and": and, "or": or, "not": not] } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -2796,7 +2804,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var and: [ModelBlog6ConditionInput?]? { get { return graphQLMap["and"] as! [ModelBlog6ConditionInput?]? @@ -2805,7 +2813,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelBlog6ConditionInput?]? { get { return graphQLMap["or"] as! [ModelBlog6ConditionInput?]? @@ -2814,7 +2822,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelBlog6ConditionInput? { get { return graphQLMap["not"] as! ModelBlog6ConditionInput? @@ -2824,14 +2832,14 @@ public struct APISwift { } } } - + public struct UpdateBlog6Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, name: String? = nil) { - graphQLMap = ["id": id, "name": name] + self.graphQLMap = ["id": id, "name": name] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2840,7 +2848,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return graphQLMap["name"] as! String? @@ -2850,14 +2858,14 @@ public struct APISwift { } } } - + public struct DeleteBlog6Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2867,14 +2875,14 @@ public struct APISwift { } } } - + public struct CreatePost6Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, title: String, blogId: GraphQLID) { - graphQLMap = ["id": id, "title": title, "blogID": blogId] + self.graphQLMap = ["id": id, "title": title, "blogID": blogId] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -2883,7 +2891,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return graphQLMap["title"] as! String @@ -2892,7 +2900,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return graphQLMap["blogID"] as! GraphQLID @@ -2902,14 +2910,14 @@ public struct APISwift { } } } - + public struct ModelPost6ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(title: ModelStringInput? = nil, blogId: ModelIDInput? = nil, and: [ModelPost6ConditionInput?]? = nil, or: [ModelPost6ConditionInput?]? = nil, not: ModelPost6ConditionInput? = nil) { - graphQLMap = ["title": title, "blogID": blogId, "and": and, "or": or, "not": not] + self.graphQLMap = ["title": title, "blogID": blogId, "and": and, "or": or, "not": not] } - + public var title: ModelStringInput? { get { return graphQLMap["title"] as! ModelStringInput? @@ -2918,7 +2926,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var blogId: ModelIDInput? { get { return graphQLMap["blogID"] as! ModelIDInput? @@ -2927,7 +2935,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "blogID") } } - + public var and: [ModelPost6ConditionInput?]? { get { return graphQLMap["and"] as! [ModelPost6ConditionInput?]? @@ -2936,7 +2944,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelPost6ConditionInput?]? { get { return graphQLMap["or"] as! [ModelPost6ConditionInput?]? @@ -2945,7 +2953,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelPost6ConditionInput? { get { return graphQLMap["not"] as! ModelPost6ConditionInput? @@ -2955,14 +2963,14 @@ public struct APISwift { } } } - + public struct UpdatePost6Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, title: String? = nil, blogId: GraphQLID? = nil) { - graphQLMap = ["id": id, "title": title, "blogID": blogId] + self.graphQLMap = ["id": id, "title": title, "blogID": blogId] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -2971,7 +2979,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: String? { get { return graphQLMap["title"] as! String? @@ -2980,7 +2988,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID? { get { return graphQLMap["blogID"] as! GraphQLID? @@ -2990,14 +2998,14 @@ public struct APISwift { } } } - + public struct DeletePost6Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -3007,14 +3015,14 @@ public struct APISwift { } } } - + public struct CreateComment6Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, postId: GraphQLID, content: String) { - graphQLMap = ["id": id, "postID": postId, "content": content] + self.graphQLMap = ["id": id, "postID": postId, "content": content] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -3023,7 +3031,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return graphQLMap["postID"] as! GraphQLID @@ -3032,7 +3040,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return graphQLMap["content"] as! String @@ -3042,14 +3050,14 @@ public struct APISwift { } } } - + public struct ModelComment6ConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(postId: ModelIDInput? = nil, content: ModelStringInput? = nil, and: [ModelComment6ConditionInput?]? = nil, or: [ModelComment6ConditionInput?]? = nil, not: ModelComment6ConditionInput? = nil) { - graphQLMap = ["postID": postId, "content": content, "and": and, "or": or, "not": not] + self.graphQLMap = ["postID": postId, "content": content, "and": and, "or": or, "not": not] } - + public var postId: ModelIDInput? { get { return graphQLMap["postID"] as! ModelIDInput? @@ -3058,7 +3066,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var content: ModelStringInput? { get { return graphQLMap["content"] as! ModelStringInput? @@ -3067,7 +3075,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var and: [ModelComment6ConditionInput?]? { get { return graphQLMap["and"] as! [ModelComment6ConditionInput?]? @@ -3076,7 +3084,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelComment6ConditionInput?]? { get { return graphQLMap["or"] as! [ModelComment6ConditionInput?]? @@ -3085,7 +3093,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelComment6ConditionInput? { get { return graphQLMap["not"] as! ModelComment6ConditionInput? @@ -3095,14 +3103,14 @@ public struct APISwift { } } } - + public struct UpdateComment6Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, postId: GraphQLID? = nil, content: String? = nil) { - graphQLMap = ["id": id, "postID": postId, "content": content] + self.graphQLMap = ["id": id, "postID": postId, "content": content] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -3111,7 +3119,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID? { get { return graphQLMap["postID"] as! GraphQLID? @@ -3120,7 +3128,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var content: String? { get { return graphQLMap["content"] as! String? @@ -3130,14 +3138,14 @@ public struct APISwift { } } } - + public struct DeleteComment6Input: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -3147,14 +3155,14 @@ public struct APISwift { } } } - + public struct CreateScalarContainerInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, myString: String? = nil, myInt: Int? = nil, myDouble: Double? = nil, myBool: Bool? = nil, myDate: String? = nil, myTime: String? = nil, myDateTime: String? = nil, myTimeStamp: Int? = nil, myEmail: String? = nil, myJson: String? = nil, myPhone: String? = nil, myUrl: String? = nil, myIpAddress: String? = nil) { - graphQLMap = ["id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress] + self.graphQLMap = ["id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -3163,7 +3171,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var myString: String? { get { return graphQLMap["myString"] as! String? @@ -3172,7 +3180,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myString") } } - + public var myInt: Int? { get { return graphQLMap["myInt"] as! Int? @@ -3181,7 +3189,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myInt") } } - + public var myDouble: Double? { get { return graphQLMap["myDouble"] as! Double? @@ -3190,7 +3198,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myDouble") } } - + public var myBool: Bool? { get { return graphQLMap["myBool"] as! Bool? @@ -3199,7 +3207,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myBool") } } - + public var myDate: String? { get { return graphQLMap["myDate"] as! String? @@ -3208,7 +3216,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myDate") } } - + public var myTime: String? { get { return graphQLMap["myTime"] as! String? @@ -3217,7 +3225,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myTime") } } - + public var myDateTime: String? { get { return graphQLMap["myDateTime"] as! String? @@ -3226,7 +3234,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myDateTime") } } - + public var myTimeStamp: Int? { get { return graphQLMap["myTimeStamp"] as! Int? @@ -3235,7 +3243,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myTimeStamp") } } - + public var myEmail: String? { get { return graphQLMap["myEmail"] as! String? @@ -3244,7 +3252,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myEmail") } } - + public var myJson: String? { get { return graphQLMap["myJSON"] as! String? @@ -3253,7 +3261,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myJSON") } } - + public var myPhone: String? { get { return graphQLMap["myPhone"] as! String? @@ -3262,7 +3270,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myPhone") } } - + public var myUrl: String? { get { return graphQLMap["myURL"] as! String? @@ -3271,7 +3279,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myURL") } } - + public var myIpAddress: String? { get { return graphQLMap["myIPAddress"] as! String? @@ -3281,14 +3289,14 @@ public struct APISwift { } } } - + public struct ModelScalarContainerConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(myString: ModelStringInput? = nil, myInt: ModelIntInput? = nil, myDouble: ModelFloatInput? = nil, myBool: ModelBooleanInput? = nil, myDate: ModelStringInput? = nil, myTime: ModelStringInput? = nil, myDateTime: ModelStringInput? = nil, myTimeStamp: ModelIntInput? = nil, myEmail: ModelStringInput? = nil, myJson: ModelStringInput? = nil, myPhone: ModelStringInput? = nil, myUrl: ModelStringInput? = nil, myIpAddress: ModelStringInput? = nil, and: [ModelScalarContainerConditionInput?]? = nil, or: [ModelScalarContainerConditionInput?]? = nil, not: ModelScalarContainerConditionInput? = nil) { - graphQLMap = ["myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress, "and": and, "or": or, "not": not] + self.graphQLMap = ["myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress, "and": and, "or": or, "not": not] } - + public var myString: ModelStringInput? { get { return graphQLMap["myString"] as! ModelStringInput? @@ -3297,7 +3305,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myString") } } - + public var myInt: ModelIntInput? { get { return graphQLMap["myInt"] as! ModelIntInput? @@ -3306,7 +3314,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myInt") } } - + public var myDouble: ModelFloatInput? { get { return graphQLMap["myDouble"] as! ModelFloatInput? @@ -3315,7 +3323,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myDouble") } } - + public var myBool: ModelBooleanInput? { get { return graphQLMap["myBool"] as! ModelBooleanInput? @@ -3324,7 +3332,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myBool") } } - + public var myDate: ModelStringInput? { get { return graphQLMap["myDate"] as! ModelStringInput? @@ -3333,7 +3341,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myDate") } } - + public var myTime: ModelStringInput? { get { return graphQLMap["myTime"] as! ModelStringInput? @@ -3342,7 +3350,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myTime") } } - + public var myDateTime: ModelStringInput? { get { return graphQLMap["myDateTime"] as! ModelStringInput? @@ -3351,7 +3359,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myDateTime") } } - + public var myTimeStamp: ModelIntInput? { get { return graphQLMap["myTimeStamp"] as! ModelIntInput? @@ -3360,7 +3368,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myTimeStamp") } } - + public var myEmail: ModelStringInput? { get { return graphQLMap["myEmail"] as! ModelStringInput? @@ -3369,7 +3377,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myEmail") } } - + public var myJson: ModelStringInput? { get { return graphQLMap["myJSON"] as! ModelStringInput? @@ -3378,7 +3386,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myJSON") } } - + public var myPhone: ModelStringInput? { get { return graphQLMap["myPhone"] as! ModelStringInput? @@ -3387,7 +3395,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myPhone") } } - + public var myUrl: ModelStringInput? { get { return graphQLMap["myURL"] as! ModelStringInput? @@ -3396,7 +3404,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myURL") } } - + public var myIpAddress: ModelStringInput? { get { return graphQLMap["myIPAddress"] as! ModelStringInput? @@ -3405,7 +3413,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myIPAddress") } } - + public var and: [ModelScalarContainerConditionInput?]? { get { return graphQLMap["and"] as! [ModelScalarContainerConditionInput?]? @@ -3414,7 +3422,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelScalarContainerConditionInput?]? { get { return graphQLMap["or"] as! [ModelScalarContainerConditionInput?]? @@ -3423,7 +3431,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelScalarContainerConditionInput? { get { return graphQLMap["not"] as! ModelScalarContainerConditionInput? @@ -3433,14 +3441,14 @@ public struct APISwift { } } } - + public struct ModelIntInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(ne: Int? = nil, eq: Int? = nil, le: Int? = nil, lt: Int? = nil, ge: Int? = nil, gt: Int? = nil, between: [Int?]? = nil, attributeExists: Bool? = nil, attributeType: ModelAttributeTypes? = nil) { - graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "between": between, "attributeExists": attributeExists, "attributeType": attributeType] + self.graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "between": between, "attributeExists": attributeExists, "attributeType": attributeType] } - + public var ne: Int? { get { return graphQLMap["ne"] as! Int? @@ -3449,7 +3457,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var eq: Int? { get { return graphQLMap["eq"] as! Int? @@ -3458,7 +3466,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var le: Int? { get { return graphQLMap["le"] as! Int? @@ -3467,7 +3475,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "le") } } - + public var lt: Int? { get { return graphQLMap["lt"] as! Int? @@ -3476,7 +3484,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "lt") } } - + public var ge: Int? { get { return graphQLMap["ge"] as! Int? @@ -3485,7 +3493,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ge") } } - + public var gt: Int? { get { return graphQLMap["gt"] as! Int? @@ -3494,7 +3502,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "gt") } } - + public var between: [Int?]? { get { return graphQLMap["between"] as! [Int?]? @@ -3503,7 +3511,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "between") } } - + public var attributeExists: Bool? { get { return graphQLMap["attributeExists"] as! Bool? @@ -3512,7 +3520,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeExists") } } - + public var attributeType: ModelAttributeTypes? { get { return graphQLMap["attributeType"] as! ModelAttributeTypes? @@ -3522,14 +3530,14 @@ public struct APISwift { } } } - + public struct UpdateScalarContainerInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, myString: String? = nil, myInt: Int? = nil, myDouble: Double? = nil, myBool: Bool? = nil, myDate: String? = nil, myTime: String? = nil, myDateTime: String? = nil, myTimeStamp: Int? = nil, myEmail: String? = nil, myJson: String? = nil, myPhone: String? = nil, myUrl: String? = nil, myIpAddress: String? = nil) { - graphQLMap = ["id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress] + self.graphQLMap = ["id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -3538,7 +3546,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var myString: String? { get { return graphQLMap["myString"] as! String? @@ -3547,7 +3555,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myString") } } - + public var myInt: Int? { get { return graphQLMap["myInt"] as! Int? @@ -3556,7 +3564,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myInt") } } - + public var myDouble: Double? { get { return graphQLMap["myDouble"] as! Double? @@ -3565,7 +3573,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myDouble") } } - + public var myBool: Bool? { get { return graphQLMap["myBool"] as! Bool? @@ -3574,7 +3582,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myBool") } } - + public var myDate: String? { get { return graphQLMap["myDate"] as! String? @@ -3583,7 +3591,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myDate") } } - + public var myTime: String? { get { return graphQLMap["myTime"] as! String? @@ -3592,7 +3600,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myTime") } } - + public var myDateTime: String? { get { return graphQLMap["myDateTime"] as! String? @@ -3601,7 +3609,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myDateTime") } } - + public var myTimeStamp: Int? { get { return graphQLMap["myTimeStamp"] as! Int? @@ -3610,7 +3618,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myTimeStamp") } } - + public var myEmail: String? { get { return graphQLMap["myEmail"] as! String? @@ -3619,7 +3627,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myEmail") } } - + public var myJson: String? { get { return graphQLMap["myJSON"] as! String? @@ -3628,7 +3636,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myJSON") } } - + public var myPhone: String? { get { return graphQLMap["myPhone"] as! String? @@ -3637,7 +3645,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myPhone") } } - + public var myUrl: String? { get { return graphQLMap["myURL"] as! String? @@ -3646,7 +3654,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myURL") } } - + public var myIpAddress: String? { get { return graphQLMap["myIPAddress"] as! String? @@ -3656,14 +3664,14 @@ public struct APISwift { } } } - + public struct DeleteScalarContainerInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -3673,14 +3681,14 @@ public struct APISwift { } } } - + public struct CreateListIntContainerInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, test: Int, nullableInt: Int? = nil, intList: [Int], intNullableList: [Int]? = nil, nullableIntList: [Int?], nullableIntNullableList: [Int?]? = nil) { - graphQLMap = ["id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList] + self.graphQLMap = ["id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -3689,7 +3697,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var test: Int { get { return graphQLMap["test"] as! Int @@ -3698,7 +3706,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "test") } } - + public var nullableInt: Int? { get { return graphQLMap["nullableInt"] as! Int? @@ -3707,7 +3715,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableInt") } } - + public var intList: [Int] { get { return graphQLMap["intList"] as! [Int] @@ -3716,7 +3724,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "intList") } } - + public var intNullableList: [Int]? { get { return graphQLMap["intNullableList"] as! [Int]? @@ -3725,7 +3733,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "intNullableList") } } - + public var nullableIntList: [Int?] { get { return graphQLMap["nullableIntList"] as! [Int?] @@ -3734,7 +3742,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableIntList") } } - + public var nullableIntNullableList: [Int?]? { get { return graphQLMap["nullableIntNullableList"] as! [Int?]? @@ -3744,14 +3752,14 @@ public struct APISwift { } } } - + public struct ModelListIntContainerConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(test: ModelIntInput? = nil, nullableInt: ModelIntInput? = nil, intList: ModelIntInput? = nil, intNullableList: ModelIntInput? = nil, nullableIntList: ModelIntInput? = nil, nullableIntNullableList: ModelIntInput? = nil, and: [ModelListIntContainerConditionInput?]? = nil, or: [ModelListIntContainerConditionInput?]? = nil, not: ModelListIntContainerConditionInput? = nil) { - graphQLMap = ["test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList, "and": and, "or": or, "not": not] + self.graphQLMap = ["test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList, "and": and, "or": or, "not": not] } - + public var test: ModelIntInput? { get { return graphQLMap["test"] as! ModelIntInput? @@ -3760,7 +3768,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "test") } } - + public var nullableInt: ModelIntInput? { get { return graphQLMap["nullableInt"] as! ModelIntInput? @@ -3769,7 +3777,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableInt") } } - + public var intList: ModelIntInput? { get { return graphQLMap["intList"] as! ModelIntInput? @@ -3778,7 +3786,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "intList") } } - + public var intNullableList: ModelIntInput? { get { return graphQLMap["intNullableList"] as! ModelIntInput? @@ -3787,7 +3795,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "intNullableList") } } - + public var nullableIntList: ModelIntInput? { get { return graphQLMap["nullableIntList"] as! ModelIntInput? @@ -3796,7 +3804,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableIntList") } } - + public var nullableIntNullableList: ModelIntInput? { get { return graphQLMap["nullableIntNullableList"] as! ModelIntInput? @@ -3805,7 +3813,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableIntNullableList") } } - + public var and: [ModelListIntContainerConditionInput?]? { get { return graphQLMap["and"] as! [ModelListIntContainerConditionInput?]? @@ -3814,7 +3822,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelListIntContainerConditionInput?]? { get { return graphQLMap["or"] as! [ModelListIntContainerConditionInput?]? @@ -3823,7 +3831,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelListIntContainerConditionInput? { get { return graphQLMap["not"] as! ModelListIntContainerConditionInput? @@ -3833,14 +3841,14 @@ public struct APISwift { } } } - + public struct UpdateListIntContainerInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, test: Int? = nil, nullableInt: Int? = nil, intList: [Int]? = nil, intNullableList: [Int]? = nil, nullableIntList: [Int?]? = nil, nullableIntNullableList: [Int?]? = nil) { - graphQLMap = ["id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList] + self.graphQLMap = ["id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -3849,7 +3857,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var test: Int? { get { return graphQLMap["test"] as! Int? @@ -3858,7 +3866,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "test") } } - + public var nullableInt: Int? { get { return graphQLMap["nullableInt"] as! Int? @@ -3867,7 +3875,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableInt") } } - + public var intList: [Int]? { get { return graphQLMap["intList"] as! [Int]? @@ -3876,7 +3884,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "intList") } } - + public var intNullableList: [Int]? { get { return graphQLMap["intNullableList"] as! [Int]? @@ -3885,7 +3893,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "intNullableList") } } - + public var nullableIntList: [Int?]? { get { return graphQLMap["nullableIntList"] as! [Int?]? @@ -3894,7 +3902,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableIntList") } } - + public var nullableIntNullableList: [Int?]? { get { return graphQLMap["nullableIntNullableList"] as! [Int?]? @@ -3904,14 +3912,14 @@ public struct APISwift { } } } - + public struct DeleteListIntContainerInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -3921,14 +3929,14 @@ public struct APISwift { } } } - + public struct CreateListStringContainerInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, test: String, nullableString: String? = nil, stringList: [String], stringNullableList: [String]? = nil, nullableStringList: [String?], nullableStringNullableList: [String?]? = nil) { - graphQLMap = ["id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList] + self.graphQLMap = ["id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -3937,7 +3945,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var test: String { get { return graphQLMap["test"] as! String @@ -3946,7 +3954,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "test") } } - + public var nullableString: String? { get { return graphQLMap["nullableString"] as! String? @@ -3955,7 +3963,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableString") } } - + public var stringList: [String] { get { return graphQLMap["stringList"] as! [String] @@ -3964,7 +3972,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "stringList") } } - + public var stringNullableList: [String]? { get { return graphQLMap["stringNullableList"] as! [String]? @@ -3973,7 +3981,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "stringNullableList") } } - + public var nullableStringList: [String?] { get { return graphQLMap["nullableStringList"] as! [String?] @@ -3982,7 +3990,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableStringList") } } - + public var nullableStringNullableList: [String?]? { get { return graphQLMap["nullableStringNullableList"] as! [String?]? @@ -3992,14 +4000,14 @@ public struct APISwift { } } } - + public struct ModelListStringContainerConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(test: ModelStringInput? = nil, nullableString: ModelStringInput? = nil, stringList: ModelStringInput? = nil, stringNullableList: ModelStringInput? = nil, nullableStringList: ModelStringInput? = nil, nullableStringNullableList: ModelStringInput? = nil, and: [ModelListStringContainerConditionInput?]? = nil, or: [ModelListStringContainerConditionInput?]? = nil, not: ModelListStringContainerConditionInput? = nil) { - graphQLMap = ["test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList, "and": and, "or": or, "not": not] + self.graphQLMap = ["test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList, "and": and, "or": or, "not": not] } - + public var test: ModelStringInput? { get { return graphQLMap["test"] as! ModelStringInput? @@ -4008,7 +4016,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "test") } } - + public var nullableString: ModelStringInput? { get { return graphQLMap["nullableString"] as! ModelStringInput? @@ -4017,7 +4025,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableString") } } - + public var stringList: ModelStringInput? { get { return graphQLMap["stringList"] as! ModelStringInput? @@ -4026,7 +4034,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "stringList") } } - + public var stringNullableList: ModelStringInput? { get { return graphQLMap["stringNullableList"] as! ModelStringInput? @@ -4035,7 +4043,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "stringNullableList") } } - + public var nullableStringList: ModelStringInput? { get { return graphQLMap["nullableStringList"] as! ModelStringInput? @@ -4044,7 +4052,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableStringList") } } - + public var nullableStringNullableList: ModelStringInput? { get { return graphQLMap["nullableStringNullableList"] as! ModelStringInput? @@ -4053,7 +4061,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableStringNullableList") } } - + public var and: [ModelListStringContainerConditionInput?]? { get { return graphQLMap["and"] as! [ModelListStringContainerConditionInput?]? @@ -4062,7 +4070,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelListStringContainerConditionInput?]? { get { return graphQLMap["or"] as! [ModelListStringContainerConditionInput?]? @@ -4071,7 +4079,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelListStringContainerConditionInput? { get { return graphQLMap["not"] as! ModelListStringContainerConditionInput? @@ -4081,14 +4089,14 @@ public struct APISwift { } } } - + public struct UpdateListStringContainerInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, test: String? = nil, nullableString: String? = nil, stringList: [String]? = nil, stringNullableList: [String]? = nil, nullableStringList: [String?]? = nil, nullableStringNullableList: [String?]? = nil) { - graphQLMap = ["id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList] + self.graphQLMap = ["id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -4097,7 +4105,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var test: String? { get { return graphQLMap["test"] as! String? @@ -4106,7 +4114,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "test") } } - + public var nullableString: String? { get { return graphQLMap["nullableString"] as! String? @@ -4115,7 +4123,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableString") } } - + public var stringList: [String]? { get { return graphQLMap["stringList"] as! [String]? @@ -4124,7 +4132,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "stringList") } } - + public var stringNullableList: [String]? { get { return graphQLMap["stringNullableList"] as! [String]? @@ -4133,7 +4141,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "stringNullableList") } } - + public var nullableStringList: [String?]? { get { return graphQLMap["nullableStringList"] as! [String?]? @@ -4142,7 +4150,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableStringList") } } - + public var nullableStringNullableList: [String?]? { get { return graphQLMap["nullableStringNullableList"] as! [String?]? @@ -4152,14 +4160,14 @@ public struct APISwift { } } } - + public struct DeleteListStringContainerInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -4169,14 +4177,14 @@ public struct APISwift { } } } - + public struct CreateEnumTestModelInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, enumVal: TestEnum, nullableEnumVal: TestEnum? = nil, enumList: [TestEnum], enumNullableList: [TestEnum]? = nil, nullableEnumList: [TestEnum?], nullableEnumNullableList: [TestEnum?]? = nil) { - graphQLMap = ["id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList] + self.graphQLMap = ["id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -4185,7 +4193,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var enumVal: TestEnum { get { return graphQLMap["enumVal"] as! TestEnum @@ -4194,7 +4202,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "enumVal") } } - + public var nullableEnumVal: TestEnum? { get { return graphQLMap["nullableEnumVal"] as! TestEnum? @@ -4203,7 +4211,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableEnumVal") } } - + public var enumList: [TestEnum] { get { return graphQLMap["enumList"] as! [TestEnum] @@ -4212,7 +4220,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "enumList") } } - + public var enumNullableList: [TestEnum]? { get { return graphQLMap["enumNullableList"] as! [TestEnum]? @@ -4221,7 +4229,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "enumNullableList") } } - + public var nullableEnumList: [TestEnum?] { get { return graphQLMap["nullableEnumList"] as! [TestEnum?] @@ -4230,7 +4238,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableEnumList") } } - + public var nullableEnumNullableList: [TestEnum?]? { get { return graphQLMap["nullableEnumNullableList"] as! [TestEnum?]? @@ -4240,14 +4248,14 @@ public struct APISwift { } } } - + public enum TestEnum: RawRepresentable, Equatable, JSONDecodable, JSONEncodable { public typealias RawValue = String case valueOne case valueTwo /// Auto generated constant for unknown enum values case unknown(RawValue) - + public init?(rawValue: RawValue) { switch rawValue { case "VALUE_ONE": self = .valueOne @@ -4255,7 +4263,7 @@ public struct APISwift { default: self = .unknown(rawValue) } } - + public var rawValue: RawValue { switch self { case .valueOne: return "VALUE_ONE" @@ -4263,7 +4271,7 @@ public struct APISwift { case .unknown(let value): return value } } - + public static func == (lhs: TestEnum, rhs: TestEnum) -> Bool { switch (lhs, rhs) { case (.valueOne, .valueOne): return true @@ -4273,14 +4281,14 @@ public struct APISwift { } } } - + public struct ModelEnumTestModelConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(enumVal: ModelTestEnumInput? = nil, nullableEnumVal: ModelTestEnumInput? = nil, enumList: ModelTestEnumListInput? = nil, enumNullableList: ModelTestEnumListInput? = nil, nullableEnumList: ModelTestEnumListInput? = nil, nullableEnumNullableList: ModelTestEnumListInput? = nil, and: [ModelEnumTestModelConditionInput?]? = nil, or: [ModelEnumTestModelConditionInput?]? = nil, not: ModelEnumTestModelConditionInput? = nil) { - graphQLMap = ["enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList, "and": and, "or": or, "not": not] + self.graphQLMap = ["enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList, "and": and, "or": or, "not": not] } - + public var enumVal: ModelTestEnumInput? { get { return graphQLMap["enumVal"] as! ModelTestEnumInput? @@ -4289,7 +4297,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "enumVal") } } - + public var nullableEnumVal: ModelTestEnumInput? { get { return graphQLMap["nullableEnumVal"] as! ModelTestEnumInput? @@ -4298,7 +4306,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableEnumVal") } } - + public var enumList: ModelTestEnumListInput? { get { return graphQLMap["enumList"] as! ModelTestEnumListInput? @@ -4307,7 +4315,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "enumList") } } - + public var enumNullableList: ModelTestEnumListInput? { get { return graphQLMap["enumNullableList"] as! ModelTestEnumListInput? @@ -4316,7 +4324,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "enumNullableList") } } - + public var nullableEnumList: ModelTestEnumListInput? { get { return graphQLMap["nullableEnumList"] as! ModelTestEnumListInput? @@ -4325,7 +4333,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableEnumList") } } - + public var nullableEnumNullableList: ModelTestEnumListInput? { get { return graphQLMap["nullableEnumNullableList"] as! ModelTestEnumListInput? @@ -4334,7 +4342,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableEnumNullableList") } } - + public var and: [ModelEnumTestModelConditionInput?]? { get { return graphQLMap["and"] as! [ModelEnumTestModelConditionInput?]? @@ -4343,7 +4351,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelEnumTestModelConditionInput?]? { get { return graphQLMap["or"] as! [ModelEnumTestModelConditionInput?]? @@ -4352,7 +4360,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelEnumTestModelConditionInput? { get { return graphQLMap["not"] as! ModelEnumTestModelConditionInput? @@ -4362,14 +4370,14 @@ public struct APISwift { } } } - + public struct ModelTestEnumInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(eq: TestEnum? = nil, ne: TestEnum? = nil) { - graphQLMap = ["eq": eq, "ne": ne] + self.graphQLMap = ["eq": eq, "ne": ne] } - + public var eq: TestEnum? { get { return graphQLMap["eq"] as! TestEnum? @@ -4378,7 +4386,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var ne: TestEnum? { get { return graphQLMap["ne"] as! TestEnum? @@ -4388,14 +4396,14 @@ public struct APISwift { } } } - + public struct ModelTestEnumListInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(eq: [TestEnum?]? = nil, ne: [TestEnum?]? = nil, contains: TestEnum? = nil, notContains: TestEnum? = nil) { - graphQLMap = ["eq": eq, "ne": ne, "contains": contains, "notContains": notContains] + self.graphQLMap = ["eq": eq, "ne": ne, "contains": contains, "notContains": notContains] } - + public var eq: [TestEnum?]? { get { return graphQLMap["eq"] as! [TestEnum?]? @@ -4404,7 +4412,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var ne: [TestEnum?]? { get { return graphQLMap["ne"] as! [TestEnum?]? @@ -4413,7 +4421,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var contains: TestEnum? { get { return graphQLMap["contains"] as! TestEnum? @@ -4422,7 +4430,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "contains") } } - + public var notContains: TestEnum? { get { return graphQLMap["notContains"] as! TestEnum? @@ -4432,14 +4440,14 @@ public struct APISwift { } } } - + public struct UpdateEnumTestModelInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, enumVal: TestEnum? = nil, nullableEnumVal: TestEnum? = nil, enumList: [TestEnum]? = nil, enumNullableList: [TestEnum]? = nil, nullableEnumList: [TestEnum?]? = nil, nullableEnumNullableList: [TestEnum?]? = nil) { - graphQLMap = ["id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList] + self.graphQLMap = ["id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -4448,7 +4456,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var enumVal: TestEnum? { get { return graphQLMap["enumVal"] as! TestEnum? @@ -4457,7 +4465,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "enumVal") } } - + public var nullableEnumVal: TestEnum? { get { return graphQLMap["nullableEnumVal"] as! TestEnum? @@ -4466,7 +4474,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableEnumVal") } } - + public var enumList: [TestEnum]? { get { return graphQLMap["enumList"] as! [TestEnum]? @@ -4475,7 +4483,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "enumList") } } - + public var enumNullableList: [TestEnum]? { get { return graphQLMap["enumNullableList"] as! [TestEnum]? @@ -4484,7 +4492,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "enumNullableList") } } - + public var nullableEnumList: [TestEnum?]? { get { return graphQLMap["nullableEnumList"] as! [TestEnum?]? @@ -4493,7 +4501,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableEnumList") } } - + public var nullableEnumNullableList: [TestEnum?]? { get { return graphQLMap["nullableEnumNullableList"] as! [TestEnum?]? @@ -4503,14 +4511,14 @@ public struct APISwift { } } } - + public struct DeleteEnumTestModelInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -4520,14 +4528,14 @@ public struct APISwift { } } } - + public struct CreateNestedTypeTestModelInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, nestedVal: NestedInput, nullableNestedVal: NestedInput? = nil, nestedList: [NestedInput], nestedNullableList: [NestedInput]? = nil, nullableNestedList: [NestedInput?], nullableNestedNullableList: [NestedInput?]? = nil) { - graphQLMap = ["id": id, "nestedVal": nestedVal, "nullableNestedVal": nullableNestedVal, "nestedList": nestedList, "nestedNullableList": nestedNullableList, "nullableNestedList": nullableNestedList, "nullableNestedNullableList": nullableNestedNullableList] + self.graphQLMap = ["id": id, "nestedVal": nestedVal, "nullableNestedVal": nullableNestedVal, "nestedList": nestedList, "nestedNullableList": nestedNullableList, "nullableNestedList": nullableNestedList, "nullableNestedNullableList": nullableNestedNullableList] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -4536,7 +4544,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var nestedVal: NestedInput { get { return graphQLMap["nestedVal"] as! NestedInput @@ -4545,7 +4553,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nestedVal") } } - + public var nullableNestedVal: NestedInput? { get { return graphQLMap["nullableNestedVal"] as! NestedInput? @@ -4554,7 +4562,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableNestedVal") } } - + public var nestedList: [NestedInput] { get { return graphQLMap["nestedList"] as! [NestedInput] @@ -4563,7 +4571,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nestedList") } } - + public var nestedNullableList: [NestedInput]? { get { return graphQLMap["nestedNullableList"] as! [NestedInput]? @@ -4572,7 +4580,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nestedNullableList") } } - + public var nullableNestedList: [NestedInput?] { get { return graphQLMap["nullableNestedList"] as! [NestedInput?] @@ -4581,7 +4589,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableNestedList") } } - + public var nullableNestedNullableList: [NestedInput?]? { get { return graphQLMap["nullableNestedNullableList"] as! [NestedInput?]? @@ -4591,14 +4599,14 @@ public struct APISwift { } } } - + public struct NestedInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { - graphQLMap = ["valueOne": valueOne, "valueTwo": valueTwo] + self.graphQLMap = ["valueOne": valueOne, "valueTwo": valueTwo] } - + public var valueOne: Int? { get { return graphQLMap["valueOne"] as! Int? @@ -4607,7 +4615,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return graphQLMap["valueTwo"] as! String? @@ -4617,14 +4625,14 @@ public struct APISwift { } } } - + public struct ModelNestedTypeTestModelConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(and: [ModelNestedTypeTestModelConditionInput?]? = nil, or: [ModelNestedTypeTestModelConditionInput?]? = nil, not: ModelNestedTypeTestModelConditionInput? = nil) { - graphQLMap = ["and": and, "or": or, "not": not] + self.graphQLMap = ["and": and, "or": or, "not": not] } - + public var and: [ModelNestedTypeTestModelConditionInput?]? { get { return graphQLMap["and"] as! [ModelNestedTypeTestModelConditionInput?]? @@ -4633,7 +4641,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelNestedTypeTestModelConditionInput?]? { get { return graphQLMap["or"] as! [ModelNestedTypeTestModelConditionInput?]? @@ -4642,7 +4650,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelNestedTypeTestModelConditionInput? { get { return graphQLMap["not"] as! ModelNestedTypeTestModelConditionInput? @@ -4652,14 +4660,14 @@ public struct APISwift { } } } - + public struct UpdateNestedTypeTestModelInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, nestedVal: NestedInput? = nil, nullableNestedVal: NestedInput? = nil, nestedList: [NestedInput]? = nil, nestedNullableList: [NestedInput]? = nil, nullableNestedList: [NestedInput?]? = nil, nullableNestedNullableList: [NestedInput?]? = nil) { - graphQLMap = ["id": id, "nestedVal": nestedVal, "nullableNestedVal": nullableNestedVal, "nestedList": nestedList, "nestedNullableList": nestedNullableList, "nullableNestedList": nullableNestedList, "nullableNestedNullableList": nullableNestedNullableList] + self.graphQLMap = ["id": id, "nestedVal": nestedVal, "nullableNestedVal": nullableNestedVal, "nestedList": nestedList, "nestedNullableList": nestedNullableList, "nullableNestedList": nullableNestedList, "nullableNestedNullableList": nullableNestedNullableList] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -4668,7 +4676,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var nestedVal: NestedInput? { get { return graphQLMap["nestedVal"] as! NestedInput? @@ -4677,7 +4685,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nestedVal") } } - + public var nullableNestedVal: NestedInput? { get { return graphQLMap["nullableNestedVal"] as! NestedInput? @@ -4686,7 +4694,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableNestedVal") } } - + public var nestedList: [NestedInput]? { get { return graphQLMap["nestedList"] as! [NestedInput]? @@ -4695,7 +4703,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nestedList") } } - + public var nestedNullableList: [NestedInput]? { get { return graphQLMap["nestedNullableList"] as! [NestedInput]? @@ -4704,7 +4712,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nestedNullableList") } } - + public var nullableNestedList: [NestedInput?]? { get { return graphQLMap["nullableNestedList"] as! [NestedInput?]? @@ -4713,7 +4721,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableNestedList") } } - + public var nullableNestedNullableList: [NestedInput?]? { get { return graphQLMap["nullableNestedNullableList"] as! [NestedInput?]? @@ -4723,14 +4731,14 @@ public struct APISwift { } } } - + public struct DeleteNestedTypeTestModelInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -4740,14 +4748,14 @@ public struct APISwift { } } } - + public struct ModelPostFilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, title: ModelStringInput? = nil, content: ModelStringInput? = nil, createdAt: ModelStringInput? = nil, updatedAt: ModelStringInput? = nil, draft: ModelBooleanInput? = nil, rating: ModelFloatInput? = nil, status: ModelPostStatusInput? = nil, and: [ModelPostFilterInput?]? = nil, or: [ModelPostFilterInput?]? = nil, not: ModelPostFilterInput? = nil) { - graphQLMap = ["id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -4756,7 +4764,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: ModelStringInput? { get { return graphQLMap["title"] as! ModelStringInput? @@ -4765,7 +4773,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var content: ModelStringInput? { get { return graphQLMap["content"] as! ModelStringInput? @@ -4774,7 +4782,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var createdAt: ModelStringInput? { get { return graphQLMap["createdAt"] as! ModelStringInput? @@ -4783,7 +4791,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: ModelStringInput? { get { return graphQLMap["updatedAt"] as! ModelStringInput? @@ -4792,7 +4800,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: ModelBooleanInput? { get { return graphQLMap["draft"] as! ModelBooleanInput? @@ -4801,7 +4809,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "draft") } } - + public var rating: ModelFloatInput? { get { return graphQLMap["rating"] as! ModelFloatInput? @@ -4810,7 +4818,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "rating") } } - + public var status: ModelPostStatusInput? { get { return graphQLMap["status"] as! ModelPostStatusInput? @@ -4819,7 +4827,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "status") } } - + public var and: [ModelPostFilterInput?]? { get { return graphQLMap["and"] as! [ModelPostFilterInput?]? @@ -4828,7 +4836,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelPostFilterInput?]? { get { return graphQLMap["or"] as! [ModelPostFilterInput?]? @@ -4837,7 +4845,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelPostFilterInput? { get { return graphQLMap["not"] as! ModelPostFilterInput? @@ -4847,14 +4855,14 @@ public struct APISwift { } } } - + public struct ModelCommentFilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, content: ModelStringInput? = nil, createdAt: ModelStringInput? = nil, and: [ModelCommentFilterInput?]? = nil, or: [ModelCommentFilterInput?]? = nil, not: ModelCommentFilterInput? = nil) { - graphQLMap = ["id": id, "content": content, "createdAt": createdAt, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "content": content, "createdAt": createdAt, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -4863,7 +4871,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var content: ModelStringInput? { get { return graphQLMap["content"] as! ModelStringInput? @@ -4872,7 +4880,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var createdAt: ModelStringInput? { get { return graphQLMap["createdAt"] as! ModelStringInput? @@ -4881,7 +4889,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "createdAt") } } - + public var and: [ModelCommentFilterInput?]? { get { return graphQLMap["and"] as! [ModelCommentFilterInput?]? @@ -4890,7 +4898,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelCommentFilterInput?]? { get { return graphQLMap["or"] as! [ModelCommentFilterInput?]? @@ -4899,7 +4907,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelCommentFilterInput? { get { return graphQLMap["not"] as! ModelCommentFilterInput? @@ -4909,14 +4917,14 @@ public struct APISwift { } } } - + public struct ModelProject1FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, name: ModelStringInput? = nil, and: [ModelProject1FilterInput?]? = nil, or: [ModelProject1FilterInput?]? = nil, not: ModelProject1FilterInput? = nil) { - graphQLMap = ["id": id, "name": name, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "name": name, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -4925,7 +4933,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -4934,7 +4942,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var and: [ModelProject1FilterInput?]? { get { return graphQLMap["and"] as! [ModelProject1FilterInput?]? @@ -4943,7 +4951,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelProject1FilterInput?]? { get { return graphQLMap["or"] as! [ModelProject1FilterInput?]? @@ -4952,7 +4960,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelProject1FilterInput? { get { return graphQLMap["not"] as! ModelProject1FilterInput? @@ -4962,14 +4970,14 @@ public struct APISwift { } } } - + public struct ModelTeam1FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, name: ModelStringInput? = nil, and: [ModelTeam1FilterInput?]? = nil, or: [ModelTeam1FilterInput?]? = nil, not: ModelTeam1FilterInput? = nil) { - graphQLMap = ["id": id, "name": name, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "name": name, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -4978,7 +4986,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -4987,7 +4995,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var and: [ModelTeam1FilterInput?]? { get { return graphQLMap["and"] as! [ModelTeam1FilterInput?]? @@ -4996,7 +5004,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelTeam1FilterInput?]? { get { return graphQLMap["or"] as! [ModelTeam1FilterInput?]? @@ -5005,7 +5013,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelTeam1FilterInput? { get { return graphQLMap["not"] as! ModelTeam1FilterInput? @@ -5015,14 +5023,14 @@ public struct APISwift { } } } - + public struct ModelProject2FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, name: ModelStringInput? = nil, teamId: ModelIDInput? = nil, and: [ModelProject2FilterInput?]? = nil, or: [ModelProject2FilterInput?]? = nil, not: ModelProject2FilterInput? = nil) { - graphQLMap = ["id": id, "name": name, "teamID": teamId, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "name": name, "teamID": teamId, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5031,7 +5039,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -5040,7 +5048,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var teamId: ModelIDInput? { get { return graphQLMap["teamID"] as! ModelIDInput? @@ -5049,7 +5057,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "teamID") } } - + public var and: [ModelProject2FilterInput?]? { get { return graphQLMap["and"] as! [ModelProject2FilterInput?]? @@ -5058,7 +5066,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelProject2FilterInput?]? { get { return graphQLMap["or"] as! [ModelProject2FilterInput?]? @@ -5067,7 +5075,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelProject2FilterInput? { get { return graphQLMap["not"] as! ModelProject2FilterInput? @@ -5077,14 +5085,14 @@ public struct APISwift { } } } - + public struct ModelTeam2FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, name: ModelStringInput? = nil, and: [ModelTeam2FilterInput?]? = nil, or: [ModelTeam2FilterInput?]? = nil, not: ModelTeam2FilterInput? = nil) { - graphQLMap = ["id": id, "name": name, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "name": name, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5093,7 +5101,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -5102,7 +5110,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var and: [ModelTeam2FilterInput?]? { get { return graphQLMap["and"] as! [ModelTeam2FilterInput?]? @@ -5111,7 +5119,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelTeam2FilterInput?]? { get { return graphQLMap["or"] as! [ModelTeam2FilterInput?]? @@ -5120,7 +5128,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelTeam2FilterInput? { get { return graphQLMap["not"] as! ModelTeam2FilterInput? @@ -5130,14 +5138,14 @@ public struct APISwift { } } } - + public struct ModelPost3FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, title: ModelStringInput? = nil, and: [ModelPost3FilterInput?]? = nil, or: [ModelPost3FilterInput?]? = nil, not: ModelPost3FilterInput? = nil) { - graphQLMap = ["id": id, "title": title, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "title": title, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5146,7 +5154,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: ModelStringInput? { get { return graphQLMap["title"] as! ModelStringInput? @@ -5155,7 +5163,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var and: [ModelPost3FilterInput?]? { get { return graphQLMap["and"] as! [ModelPost3FilterInput?]? @@ -5164,7 +5172,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelPost3FilterInput?]? { get { return graphQLMap["or"] as! [ModelPost3FilterInput?]? @@ -5173,7 +5181,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelPost3FilterInput? { get { return graphQLMap["not"] as! ModelPost3FilterInput? @@ -5183,14 +5191,14 @@ public struct APISwift { } } } - + public struct ModelComment3FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, postId: ModelIDInput? = nil, content: ModelStringInput? = nil, and: [ModelComment3FilterInput?]? = nil, or: [ModelComment3FilterInput?]? = nil, not: ModelComment3FilterInput? = nil) { - graphQLMap = ["id": id, "postID": postId, "content": content, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "postID": postId, "content": content, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5199,7 +5207,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var postId: ModelIDInput? { get { return graphQLMap["postID"] as! ModelIDInput? @@ -5208,7 +5216,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var content: ModelStringInput? { get { return graphQLMap["content"] as! ModelStringInput? @@ -5217,7 +5225,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var and: [ModelComment3FilterInput?]? { get { return graphQLMap["and"] as! [ModelComment3FilterInput?]? @@ -5226,7 +5234,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelComment3FilterInput?]? { get { return graphQLMap["or"] as! [ModelComment3FilterInput?]? @@ -5235,7 +5243,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelComment3FilterInput? { get { return graphQLMap["not"] as! ModelComment3FilterInput? @@ -5245,14 +5253,14 @@ public struct APISwift { } } } - + public struct ModelPost4FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, title: ModelStringInput? = nil, and: [ModelPost4FilterInput?]? = nil, or: [ModelPost4FilterInput?]? = nil, not: ModelPost4FilterInput? = nil) { - graphQLMap = ["id": id, "title": title, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "title": title, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5261,7 +5269,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: ModelStringInput? { get { return graphQLMap["title"] as! ModelStringInput? @@ -5270,7 +5278,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var and: [ModelPost4FilterInput?]? { get { return graphQLMap["and"] as! [ModelPost4FilterInput?]? @@ -5279,7 +5287,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelPost4FilterInput?]? { get { return graphQLMap["or"] as! [ModelPost4FilterInput?]? @@ -5288,7 +5296,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelPost4FilterInput? { get { return graphQLMap["not"] as! ModelPost4FilterInput? @@ -5298,14 +5306,14 @@ public struct APISwift { } } } - + public struct ModelComment4FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, postId: ModelIDInput? = nil, content: ModelStringInput? = nil, and: [ModelComment4FilterInput?]? = nil, or: [ModelComment4FilterInput?]? = nil, not: ModelComment4FilterInput? = nil) { - graphQLMap = ["id": id, "postID": postId, "content": content, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "postID": postId, "content": content, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5314,7 +5322,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var postId: ModelIDInput? { get { return graphQLMap["postID"] as! ModelIDInput? @@ -5323,7 +5331,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var content: ModelStringInput? { get { return graphQLMap["content"] as! ModelStringInput? @@ -5332,7 +5340,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var and: [ModelComment4FilterInput?]? { get { return graphQLMap["and"] as! [ModelComment4FilterInput?]? @@ -5341,7 +5349,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelComment4FilterInput?]? { get { return graphQLMap["or"] as! [ModelComment4FilterInput?]? @@ -5350,7 +5358,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelComment4FilterInput? { get { return graphQLMap["not"] as! ModelComment4FilterInput? @@ -5360,14 +5368,14 @@ public struct APISwift { } } } - + public struct ModelPost5FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, title: ModelStringInput? = nil, and: [ModelPost5FilterInput?]? = nil, or: [ModelPost5FilterInput?]? = nil, not: ModelPost5FilterInput? = nil) { - graphQLMap = ["id": id, "title": title, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "title": title, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5376,7 +5384,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: ModelStringInput? { get { return graphQLMap["title"] as! ModelStringInput? @@ -5385,7 +5393,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var and: [ModelPost5FilterInput?]? { get { return graphQLMap["and"] as! [ModelPost5FilterInput?]? @@ -5394,7 +5402,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelPost5FilterInput?]? { get { return graphQLMap["or"] as! [ModelPost5FilterInput?]? @@ -5403,7 +5411,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelPost5FilterInput? { get { return graphQLMap["not"] as! ModelPost5FilterInput? @@ -5413,14 +5421,14 @@ public struct APISwift { } } } - + public struct ModelPostEditor5FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, postId: ModelIDInput? = nil, editorId: ModelIDInput? = nil, and: [ModelPostEditor5FilterInput?]? = nil, or: [ModelPostEditor5FilterInput?]? = nil, not: ModelPostEditor5FilterInput? = nil) { - graphQLMap = ["id": id, "postID": postId, "editorID": editorId, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "postID": postId, "editorID": editorId, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5429,7 +5437,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var postId: ModelIDInput? { get { return graphQLMap["postID"] as! ModelIDInput? @@ -5438,7 +5446,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var editorId: ModelIDInput? { get { return graphQLMap["editorID"] as! ModelIDInput? @@ -5447,7 +5455,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "editorID") } } - + public var and: [ModelPostEditor5FilterInput?]? { get { return graphQLMap["and"] as! [ModelPostEditor5FilterInput?]? @@ -5456,7 +5464,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelPostEditor5FilterInput?]? { get { return graphQLMap["or"] as! [ModelPostEditor5FilterInput?]? @@ -5465,7 +5473,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelPostEditor5FilterInput? { get { return graphQLMap["not"] as! ModelPostEditor5FilterInput? @@ -5475,14 +5483,14 @@ public struct APISwift { } } } - + public struct ModelUser5FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, username: ModelStringInput? = nil, and: [ModelUser5FilterInput?]? = nil, or: [ModelUser5FilterInput?]? = nil, not: ModelUser5FilterInput? = nil) { - graphQLMap = ["id": id, "username": username, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "username": username, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5491,7 +5499,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var username: ModelStringInput? { get { return graphQLMap["username"] as! ModelStringInput? @@ -5500,7 +5508,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "username") } } - + public var and: [ModelUser5FilterInput?]? { get { return graphQLMap["and"] as! [ModelUser5FilterInput?]? @@ -5509,7 +5517,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelUser5FilterInput?]? { get { return graphQLMap["or"] as! [ModelUser5FilterInput?]? @@ -5518,7 +5526,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelUser5FilterInput? { get { return graphQLMap["not"] as! ModelUser5FilterInput? @@ -5528,14 +5536,14 @@ public struct APISwift { } } } - + public struct ModelBlog6FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, name: ModelStringInput? = nil, and: [ModelBlog6FilterInput?]? = nil, or: [ModelBlog6FilterInput?]? = nil, not: ModelBlog6FilterInput? = nil) { - graphQLMap = ["id": id, "name": name, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "name": name, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5544,7 +5552,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -5553,7 +5561,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var and: [ModelBlog6FilterInput?]? { get { return graphQLMap["and"] as! [ModelBlog6FilterInput?]? @@ -5562,7 +5570,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelBlog6FilterInput?]? { get { return graphQLMap["or"] as! [ModelBlog6FilterInput?]? @@ -5571,7 +5579,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelBlog6FilterInput? { get { return graphQLMap["not"] as! ModelBlog6FilterInput? @@ -5581,14 +5589,14 @@ public struct APISwift { } } } - + public struct ModelPost6FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, title: ModelStringInput? = nil, blogId: ModelIDInput? = nil, and: [ModelPost6FilterInput?]? = nil, or: [ModelPost6FilterInput?]? = nil, not: ModelPost6FilterInput? = nil) { - graphQLMap = ["id": id, "title": title, "blogID": blogId, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "title": title, "blogID": blogId, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5597,7 +5605,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var title: ModelStringInput? { get { return graphQLMap["title"] as! ModelStringInput? @@ -5606,7 +5614,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "title") } } - + public var blogId: ModelIDInput? { get { return graphQLMap["blogID"] as! ModelIDInput? @@ -5615,7 +5623,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "blogID") } } - + public var and: [ModelPost6FilterInput?]? { get { return graphQLMap["and"] as! [ModelPost6FilterInput?]? @@ -5624,7 +5632,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelPost6FilterInput?]? { get { return graphQLMap["or"] as! [ModelPost6FilterInput?]? @@ -5633,7 +5641,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelPost6FilterInput? { get { return graphQLMap["not"] as! ModelPost6FilterInput? @@ -5643,14 +5651,14 @@ public struct APISwift { } } } - + public struct ModelComment6FilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, postId: ModelIDInput? = nil, content: ModelStringInput? = nil, and: [ModelComment6FilterInput?]? = nil, or: [ModelComment6FilterInput?]? = nil, not: ModelComment6FilterInput? = nil) { - graphQLMap = ["id": id, "postID": postId, "content": content, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "postID": postId, "content": content, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5659,7 +5667,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var postId: ModelIDInput? { get { return graphQLMap["postID"] as! ModelIDInput? @@ -5668,7 +5676,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "postID") } } - + public var content: ModelStringInput? { get { return graphQLMap["content"] as! ModelStringInput? @@ -5677,7 +5685,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "content") } } - + public var and: [ModelComment6FilterInput?]? { get { return graphQLMap["and"] as! [ModelComment6FilterInput?]? @@ -5686,7 +5694,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelComment6FilterInput?]? { get { return graphQLMap["or"] as! [ModelComment6FilterInput?]? @@ -5695,7 +5703,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelComment6FilterInput? { get { return graphQLMap["not"] as! ModelComment6FilterInput? @@ -5705,14 +5713,14 @@ public struct APISwift { } } } - + public struct ModelScalarContainerFilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, myString: ModelStringInput? = nil, myInt: ModelIntInput? = nil, myDouble: ModelFloatInput? = nil, myBool: ModelBooleanInput? = nil, myDate: ModelStringInput? = nil, myTime: ModelStringInput? = nil, myDateTime: ModelStringInput? = nil, myTimeStamp: ModelIntInput? = nil, myEmail: ModelStringInput? = nil, myJson: ModelStringInput? = nil, myPhone: ModelStringInput? = nil, myUrl: ModelStringInput? = nil, myIpAddress: ModelStringInput? = nil, and: [ModelScalarContainerFilterInput?]? = nil, or: [ModelScalarContainerFilterInput?]? = nil, not: ModelScalarContainerFilterInput? = nil) { - graphQLMap = ["id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5721,7 +5729,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var myString: ModelStringInput? { get { return graphQLMap["myString"] as! ModelStringInput? @@ -5730,7 +5738,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myString") } } - + public var myInt: ModelIntInput? { get { return graphQLMap["myInt"] as! ModelIntInput? @@ -5739,7 +5747,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myInt") } } - + public var myDouble: ModelFloatInput? { get { return graphQLMap["myDouble"] as! ModelFloatInput? @@ -5748,7 +5756,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myDouble") } } - + public var myBool: ModelBooleanInput? { get { return graphQLMap["myBool"] as! ModelBooleanInput? @@ -5757,7 +5765,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myBool") } } - + public var myDate: ModelStringInput? { get { return graphQLMap["myDate"] as! ModelStringInput? @@ -5766,7 +5774,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myDate") } } - + public var myTime: ModelStringInput? { get { return graphQLMap["myTime"] as! ModelStringInput? @@ -5775,7 +5783,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myTime") } } - + public var myDateTime: ModelStringInput? { get { return graphQLMap["myDateTime"] as! ModelStringInput? @@ -5784,7 +5792,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myDateTime") } } - + public var myTimeStamp: ModelIntInput? { get { return graphQLMap["myTimeStamp"] as! ModelIntInput? @@ -5793,7 +5801,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myTimeStamp") } } - + public var myEmail: ModelStringInput? { get { return graphQLMap["myEmail"] as! ModelStringInput? @@ -5802,7 +5810,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myEmail") } } - + public var myJson: ModelStringInput? { get { return graphQLMap["myJSON"] as! ModelStringInput? @@ -5811,7 +5819,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myJSON") } } - + public var myPhone: ModelStringInput? { get { return graphQLMap["myPhone"] as! ModelStringInput? @@ -5820,7 +5828,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myPhone") } } - + public var myUrl: ModelStringInput? { get { return graphQLMap["myURL"] as! ModelStringInput? @@ -5829,7 +5837,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myURL") } } - + public var myIpAddress: ModelStringInput? { get { return graphQLMap["myIPAddress"] as! ModelStringInput? @@ -5838,7 +5846,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "myIPAddress") } } - + public var and: [ModelScalarContainerFilterInput?]? { get { return graphQLMap["and"] as! [ModelScalarContainerFilterInput?]? @@ -5847,7 +5855,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelScalarContainerFilterInput?]? { get { return graphQLMap["or"] as! [ModelScalarContainerFilterInput?]? @@ -5856,7 +5864,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelScalarContainerFilterInput? { get { return graphQLMap["not"] as! ModelScalarContainerFilterInput? @@ -5866,14 +5874,14 @@ public struct APISwift { } } } - + public struct ModelListIntContainerFilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, test: ModelIntInput? = nil, nullableInt: ModelIntInput? = nil, intList: ModelIntInput? = nil, intNullableList: ModelIntInput? = nil, nullableIntList: ModelIntInput? = nil, nullableIntNullableList: ModelIntInput? = nil, and: [ModelListIntContainerFilterInput?]? = nil, or: [ModelListIntContainerFilterInput?]? = nil, not: ModelListIntContainerFilterInput? = nil) { - graphQLMap = ["id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5882,7 +5890,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var test: ModelIntInput? { get { return graphQLMap["test"] as! ModelIntInput? @@ -5891,7 +5899,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "test") } } - + public var nullableInt: ModelIntInput? { get { return graphQLMap["nullableInt"] as! ModelIntInput? @@ -5900,7 +5908,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableInt") } } - + public var intList: ModelIntInput? { get { return graphQLMap["intList"] as! ModelIntInput? @@ -5909,7 +5917,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "intList") } } - + public var intNullableList: ModelIntInput? { get { return graphQLMap["intNullableList"] as! ModelIntInput? @@ -5918,7 +5926,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "intNullableList") } } - + public var nullableIntList: ModelIntInput? { get { return graphQLMap["nullableIntList"] as! ModelIntInput? @@ -5927,7 +5935,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableIntList") } } - + public var nullableIntNullableList: ModelIntInput? { get { return graphQLMap["nullableIntNullableList"] as! ModelIntInput? @@ -5936,7 +5944,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableIntNullableList") } } - + public var and: [ModelListIntContainerFilterInput?]? { get { return graphQLMap["and"] as! [ModelListIntContainerFilterInput?]? @@ -5945,7 +5953,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelListIntContainerFilterInput?]? { get { return graphQLMap["or"] as! [ModelListIntContainerFilterInput?]? @@ -5954,7 +5962,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelListIntContainerFilterInput? { get { return graphQLMap["not"] as! ModelListIntContainerFilterInput? @@ -5964,14 +5972,14 @@ public struct APISwift { } } } - + public struct ModelListStringContainerFilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, test: ModelStringInput? = nil, nullableString: ModelStringInput? = nil, stringList: ModelStringInput? = nil, stringNullableList: ModelStringInput? = nil, nullableStringList: ModelStringInput? = nil, nullableStringNullableList: ModelStringInput? = nil, and: [ModelListStringContainerFilterInput?]? = nil, or: [ModelListStringContainerFilterInput?]? = nil, not: ModelListStringContainerFilterInput? = nil) { - graphQLMap = ["id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -5980,7 +5988,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var test: ModelStringInput? { get { return graphQLMap["test"] as! ModelStringInput? @@ -5989,7 +5997,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "test") } } - + public var nullableString: ModelStringInput? { get { return graphQLMap["nullableString"] as! ModelStringInput? @@ -5998,7 +6006,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableString") } } - + public var stringList: ModelStringInput? { get { return graphQLMap["stringList"] as! ModelStringInput? @@ -6007,7 +6015,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "stringList") } } - + public var stringNullableList: ModelStringInput? { get { return graphQLMap["stringNullableList"] as! ModelStringInput? @@ -6016,7 +6024,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "stringNullableList") } } - + public var nullableStringList: ModelStringInput? { get { return graphQLMap["nullableStringList"] as! ModelStringInput? @@ -6025,7 +6033,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableStringList") } } - + public var nullableStringNullableList: ModelStringInput? { get { return graphQLMap["nullableStringNullableList"] as! ModelStringInput? @@ -6034,7 +6042,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableStringNullableList") } } - + public var and: [ModelListStringContainerFilterInput?]? { get { return graphQLMap["and"] as! [ModelListStringContainerFilterInput?]? @@ -6043,7 +6051,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelListStringContainerFilterInput?]? { get { return graphQLMap["or"] as! [ModelListStringContainerFilterInput?]? @@ -6052,7 +6060,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelListStringContainerFilterInput? { get { return graphQLMap["not"] as! ModelListStringContainerFilterInput? @@ -6062,14 +6070,14 @@ public struct APISwift { } } } - + public struct ModelEnumTestModelFilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, enumVal: ModelTestEnumInput? = nil, nullableEnumVal: ModelTestEnumInput? = nil, enumList: ModelTestEnumListInput? = nil, enumNullableList: ModelTestEnumListInput? = nil, nullableEnumList: ModelTestEnumListInput? = nil, nullableEnumNullableList: ModelTestEnumListInput? = nil, and: [ModelEnumTestModelFilterInput?]? = nil, or: [ModelEnumTestModelFilterInput?]? = nil, not: ModelEnumTestModelFilterInput? = nil) { - graphQLMap = ["id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -6078,7 +6086,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var enumVal: ModelTestEnumInput? { get { return graphQLMap["enumVal"] as! ModelTestEnumInput? @@ -6087,7 +6095,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "enumVal") } } - + public var nullableEnumVal: ModelTestEnumInput? { get { return graphQLMap["nullableEnumVal"] as! ModelTestEnumInput? @@ -6096,7 +6104,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableEnumVal") } } - + public var enumList: ModelTestEnumListInput? { get { return graphQLMap["enumList"] as! ModelTestEnumListInput? @@ -6105,7 +6113,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "enumList") } } - + public var enumNullableList: ModelTestEnumListInput? { get { return graphQLMap["enumNullableList"] as! ModelTestEnumListInput? @@ -6114,7 +6122,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "enumNullableList") } } - + public var nullableEnumList: ModelTestEnumListInput? { get { return graphQLMap["nullableEnumList"] as! ModelTestEnumListInput? @@ -6123,7 +6131,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableEnumList") } } - + public var nullableEnumNullableList: ModelTestEnumListInput? { get { return graphQLMap["nullableEnumNullableList"] as! ModelTestEnumListInput? @@ -6132,7 +6140,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "nullableEnumNullableList") } } - + public var and: [ModelEnumTestModelFilterInput?]? { get { return graphQLMap["and"] as! [ModelEnumTestModelFilterInput?]? @@ -6141,7 +6149,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelEnumTestModelFilterInput?]? { get { return graphQLMap["or"] as! [ModelEnumTestModelFilterInput?]? @@ -6150,7 +6158,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelEnumTestModelFilterInput? { get { return graphQLMap["not"] as! ModelEnumTestModelFilterInput? @@ -6160,14 +6168,14 @@ public struct APISwift { } } } - + public struct ModelNestedTypeTestModelFilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, and: [ModelNestedTypeTestModelFilterInput?]? = nil, or: [ModelNestedTypeTestModelFilterInput?]? = nil, not: ModelNestedTypeTestModelFilterInput? = nil) { - graphQLMap = ["id": id, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -6176,7 +6184,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var and: [ModelNestedTypeTestModelFilterInput?]? { get { return graphQLMap["and"] as! [ModelNestedTypeTestModelFilterInput?]? @@ -6185,7 +6193,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelNestedTypeTestModelFilterInput?]? { get { return graphQLMap["or"] as! [ModelNestedTypeTestModelFilterInput?]? @@ -6194,7 +6202,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelNestedTypeTestModelFilterInput? { get { return graphQLMap["not"] as! ModelNestedTypeTestModelFilterInput? @@ -6204,40 +6212,40 @@ public struct APISwift { } } } - + public final class CreatePostMutation: GraphQLMutation { public static let operationString = "mutation CreatePost($input: CreatePostInput!, $condition: ModelPostConditionInput) {\n createPost(input: $input, condition: $condition) {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n items {\n __typename\n id\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n }\n}" - + public var input: CreatePostInput public var condition: ModelPostConditionInput? - + public init(input: CreatePostInput, condition: ModelPostConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createPost", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreatePost.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createPost: CreatePost? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createPost": createPost.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createPost": createPost.flatMap(\.snapshot)]) } - + public var createPost: CreatePost? { get { return (snapshot["createPost"] as? Snapshot).flatMap { CreatePost(snapshot: $0) } @@ -6246,10 +6254,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createPost") } } - + public struct CreatePost: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -6262,17 +6270,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -6281,7 +6289,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -6290,7 +6298,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -6299,7 +6307,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -6308,7 +6316,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -6317,7 +6325,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -6326,7 +6334,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -6335,7 +6343,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -6344,7 +6352,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -6353,7 +6361,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -6362,26 +6370,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -6390,16 +6398,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -6408,10 +6416,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -6419,17 +6427,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -6438,7 +6446,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -6447,7 +6455,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -6456,7 +6464,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -6465,7 +6473,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -6479,40 +6487,40 @@ public struct APISwift { } } } - + public final class UpdatePostMutation: GraphQLMutation { public static let operationString = "mutation UpdatePost($input: UpdatePostInput!, $condition: ModelPostConditionInput) {\n updatePost(input: $input, condition: $condition) {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n items {\n __typename\n id\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n }\n}" - + public var input: UpdatePostInput public var condition: ModelPostConditionInput? - + public init(input: UpdatePostInput, condition: ModelPostConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updatePost", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdatePost.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updatePost: UpdatePost? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updatePost": updatePost.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updatePost": updatePost.flatMap(\.snapshot)]) } - + public var updatePost: UpdatePost? { get { return (snapshot["updatePost"] as? Snapshot).flatMap { UpdatePost(snapshot: $0) } @@ -6521,10 +6529,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updatePost") } } - + public struct UpdatePost: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -6537,17 +6545,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -6556,7 +6564,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -6565,7 +6573,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -6574,7 +6582,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -6583,7 +6591,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -6592,7 +6600,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -6601,7 +6609,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -6610,7 +6618,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -6619,7 +6627,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -6628,7 +6636,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -6637,26 +6645,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -6665,16 +6673,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -6683,10 +6691,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -6694,17 +6702,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -6713,7 +6721,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -6722,7 +6730,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -6731,7 +6739,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -6740,7 +6748,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -6754,40 +6762,40 @@ public struct APISwift { } } } - + public final class DeletePostMutation: GraphQLMutation { public static let operationString = "mutation DeletePost($input: DeletePostInput!, $condition: ModelPostConditionInput) {\n deletePost(input: $input, condition: $condition) {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n items {\n __typename\n id\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n }\n}" - + public var input: DeletePostInput public var condition: ModelPostConditionInput? - + public init(input: DeletePostInput, condition: ModelPostConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deletePost", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeletePost.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deletePost: DeletePost? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deletePost": deletePost.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deletePost": deletePost.flatMap(\.snapshot)]) } - + public var deletePost: DeletePost? { get { return (snapshot["deletePost"] as? Snapshot).flatMap { DeletePost(snapshot: $0) } @@ -6796,10 +6804,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deletePost") } } - + public struct DeletePost: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -6812,17 +6820,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -6831,7 +6839,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -6840,7 +6848,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -6849,7 +6857,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -6858,7 +6866,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -6867,7 +6875,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -6876,7 +6884,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -6885,7 +6893,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -6894,7 +6902,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -6903,7 +6911,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -6912,26 +6920,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -6940,16 +6948,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -6958,10 +6966,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -6969,17 +6977,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -6988,7 +6996,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -6997,7 +7005,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -7006,7 +7014,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -7015,7 +7023,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -7029,40 +7037,40 @@ public struct APISwift { } } } - + public final class CreateCommentMutation: GraphQLMutation { public static let operationString = "mutation CreateComment($input: CreateCommentInput!, $condition: ModelCommentConditionInput) {\n createComment(input: $input, condition: $condition) {\n __typename\n id\n content\n createdAt\n post {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n nextToken\n }\n }\n updatedAt\n }\n}" - + public var input: CreateCommentInput public var condition: ModelCommentConditionInput? - + public init(input: CreateCommentInput, condition: ModelCommentConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createComment", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateComment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createComment: CreateComment? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createComment": createComment.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createComment": createComment.flatMap(\.snapshot)]) } - + public var createComment: CreateComment? { get { return (snapshot["createComment"] as? Snapshot).flatMap { CreateComment(snapshot: $0) } @@ -7071,10 +7079,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createComment") } } - + public struct CreateComment: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -7083,17 +7091,17 @@ public struct APISwift { GraphQLField("post", type: .object(Post.selections)), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, post: Post? = nil, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap { $0.snapshot }, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap(\.snapshot), "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -7102,7 +7110,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -7111,7 +7119,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -7120,7 +7128,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -7129,7 +7137,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -7138,7 +7146,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -7147,10 +7155,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -7163,17 +7171,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -7182,7 +7190,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -7191,7 +7199,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -7200,7 +7208,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -7209,7 +7217,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -7218,7 +7226,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -7227,7 +7235,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -7236,7 +7244,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -7245,7 +7253,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -7254,7 +7262,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -7263,25 +7271,25 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelCommentConnection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -7290,7 +7298,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -7304,40 +7312,40 @@ public struct APISwift { } } } - + public final class UpdateCommentMutation: GraphQLMutation { public static let operationString = "mutation UpdateComment($input: UpdateCommentInput!, $condition: ModelCommentConditionInput) {\n updateComment(input: $input, condition: $condition) {\n __typename\n id\n content\n createdAt\n post {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n nextToken\n }\n }\n updatedAt\n }\n}" - + public var input: UpdateCommentInput public var condition: ModelCommentConditionInput? - + public init(input: UpdateCommentInput, condition: ModelCommentConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateComment", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateComment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateComment: UpdateComment? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateComment": updateComment.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateComment": updateComment.flatMap(\.snapshot)]) } - + public var updateComment: UpdateComment? { get { return (snapshot["updateComment"] as? Snapshot).flatMap { UpdateComment(snapshot: $0) } @@ -7346,10 +7354,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateComment") } } - + public struct UpdateComment: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -7358,17 +7366,17 @@ public struct APISwift { GraphQLField("post", type: .object(Post.selections)), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, post: Post? = nil, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap { $0.snapshot }, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap(\.snapshot), "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -7377,7 +7385,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -7386,7 +7394,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -7395,7 +7403,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -7404,7 +7412,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -7413,7 +7421,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -7422,10 +7430,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -7438,17 +7446,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -7457,7 +7465,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -7466,7 +7474,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -7475,7 +7483,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -7484,7 +7492,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -7493,7 +7501,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -7502,7 +7510,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -7511,7 +7519,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -7520,7 +7528,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -7529,7 +7537,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -7538,25 +7546,25 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelCommentConnection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -7565,7 +7573,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -7579,40 +7587,40 @@ public struct APISwift { } } } - + public final class DeleteCommentMutation: GraphQLMutation { public static let operationString = "mutation DeleteComment($input: DeleteCommentInput!, $condition: ModelCommentConditionInput) {\n deleteComment(input: $input, condition: $condition) {\n __typename\n id\n content\n createdAt\n post {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n nextToken\n }\n }\n updatedAt\n }\n}" - + public var input: DeleteCommentInput public var condition: ModelCommentConditionInput? - + public init(input: DeleteCommentInput, condition: ModelCommentConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteComment", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteComment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteComment: DeleteComment? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteComment": deleteComment.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteComment": deleteComment.flatMap(\.snapshot)]) } - + public var deleteComment: DeleteComment? { get { return (snapshot["deleteComment"] as? Snapshot).flatMap { DeleteComment(snapshot: $0) } @@ -7621,10 +7629,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteComment") } } - + public struct DeleteComment: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -7633,17 +7641,17 @@ public struct APISwift { GraphQLField("post", type: .object(Post.selections)), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, post: Post? = nil, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap { $0.snapshot }, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap(\.snapshot), "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -7652,7 +7660,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -7661,7 +7669,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -7670,7 +7678,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -7679,7 +7687,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -7688,7 +7696,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -7697,10 +7705,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -7713,17 +7721,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -7732,7 +7740,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -7741,7 +7749,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -7750,7 +7758,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -7759,7 +7767,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -7768,7 +7776,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -7777,7 +7785,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -7786,7 +7794,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -7795,7 +7803,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -7804,7 +7812,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -7813,25 +7821,25 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelCommentConnection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -7840,7 +7848,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -7854,40 +7862,40 @@ public struct APISwift { } } } - + public final class CreateProject1Mutation: GraphQLMutation { public static let operationString = "mutation CreateProject1($input: CreateProject1Input!, $condition: ModelProject1ConditionInput) {\n createProject1(input: $input, condition: $condition) {\n __typename\n id\n name\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var input: CreateProject1Input public var condition: ModelProject1ConditionInput? - + public init(input: CreateProject1Input, condition: ModelProject1ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createProject1", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateProject1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createProject1: CreateProject1? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createProject1": createProject1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createProject1": createProject1.flatMap(\.snapshot)]) } - + public var createProject1: CreateProject1? { get { return (snapshot["createProject1"] as? Snapshot).flatMap { CreateProject1(snapshot: $0) } @@ -7896,10 +7904,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createProject1") } } - + public struct CreateProject1: GraphQLSelectionSet { public static let possibleTypes = ["Project1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -7908,17 +7916,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -7927,7 +7935,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -7936,7 +7944,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -7945,7 +7953,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -7954,7 +7962,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -7963,7 +7971,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -7972,10 +7980,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -7983,17 +7991,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -8002,7 +8010,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -8011,7 +8019,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -8020,7 +8028,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -8029,7 +8037,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -8042,40 +8050,40 @@ public struct APISwift { } } } - + public final class UpdateProject1Mutation: GraphQLMutation { public static let operationString = "mutation UpdateProject1($input: UpdateProject1Input!, $condition: ModelProject1ConditionInput) {\n updateProject1(input: $input, condition: $condition) {\n __typename\n id\n name\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateProject1Input public var condition: ModelProject1ConditionInput? - + public init(input: UpdateProject1Input, condition: ModelProject1ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateProject1", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateProject1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateProject1: UpdateProject1? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateProject1": updateProject1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateProject1": updateProject1.flatMap(\.snapshot)]) } - + public var updateProject1: UpdateProject1? { get { return (snapshot["updateProject1"] as? Snapshot).flatMap { UpdateProject1(snapshot: $0) } @@ -8084,10 +8092,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateProject1") } } - + public struct UpdateProject1: GraphQLSelectionSet { public static let possibleTypes = ["Project1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -8096,17 +8104,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -8115,7 +8123,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -8124,7 +8132,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -8133,7 +8141,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -8142,7 +8150,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -8151,7 +8159,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -8160,10 +8168,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -8171,17 +8179,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -8190,7 +8198,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -8199,7 +8207,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -8208,7 +8216,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -8217,7 +8225,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -8230,40 +8238,40 @@ public struct APISwift { } } } - + public final class DeleteProject1Mutation: GraphQLMutation { public static let operationString = "mutation DeleteProject1($input: DeleteProject1Input!, $condition: ModelProject1ConditionInput) {\n deleteProject1(input: $input, condition: $condition) {\n __typename\n id\n name\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteProject1Input public var condition: ModelProject1ConditionInput? - + public init(input: DeleteProject1Input, condition: ModelProject1ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteProject1", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteProject1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteProject1: DeleteProject1? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteProject1": deleteProject1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteProject1": deleteProject1.flatMap(\.snapshot)]) } - + public var deleteProject1: DeleteProject1? { get { return (snapshot["deleteProject1"] as? Snapshot).flatMap { DeleteProject1(snapshot: $0) } @@ -8272,10 +8280,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteProject1") } } - + public struct DeleteProject1: GraphQLSelectionSet { public static let possibleTypes = ["Project1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -8284,17 +8292,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -8303,7 +8311,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -8312,7 +8320,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -8321,7 +8329,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -8330,7 +8338,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -8339,7 +8347,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -8348,10 +8356,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -8359,17 +8367,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -8378,7 +8386,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -8387,7 +8395,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -8396,7 +8404,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -8405,7 +8413,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -8418,40 +8426,40 @@ public struct APISwift { } } } - + public final class CreateTeam1Mutation: GraphQLMutation { public static let operationString = "mutation CreateTeam1($input: CreateTeam1Input!, $condition: ModelTeam1ConditionInput) {\n createTeam1(input: $input, condition: $condition) {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public var input: CreateTeam1Input public var condition: ModelTeam1ConditionInput? - + public init(input: CreateTeam1Input, condition: ModelTeam1ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createTeam1", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateTeam1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createTeam1: CreateTeam1? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createTeam1": createTeam1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createTeam1": createTeam1.flatMap(\.snapshot)]) } - + public var createTeam1: CreateTeam1? { get { return (snapshot["createTeam1"] as? Snapshot).flatMap { CreateTeam1(snapshot: $0) } @@ -8460,10 +8468,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createTeam1") } } - + public struct CreateTeam1: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -8471,17 +8479,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -8490,7 +8498,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -8499,7 +8507,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -8508,7 +8516,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -8517,7 +8525,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -8529,40 +8537,40 @@ public struct APISwift { } } } - + public final class UpdateTeam1Mutation: GraphQLMutation { public static let operationString = "mutation UpdateTeam1($input: UpdateTeam1Input!, $condition: ModelTeam1ConditionInput) {\n updateTeam1(input: $input, condition: $condition) {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateTeam1Input public var condition: ModelTeam1ConditionInput? - + public init(input: UpdateTeam1Input, condition: ModelTeam1ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateTeam1", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateTeam1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateTeam1: UpdateTeam1? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateTeam1": updateTeam1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateTeam1": updateTeam1.flatMap(\.snapshot)]) } - + public var updateTeam1: UpdateTeam1? { get { return (snapshot["updateTeam1"] as? Snapshot).flatMap { UpdateTeam1(snapshot: $0) } @@ -8571,10 +8579,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateTeam1") } } - + public struct UpdateTeam1: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -8582,17 +8590,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -8601,7 +8609,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -8610,7 +8618,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -8619,7 +8627,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -8628,7 +8636,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -8640,40 +8648,40 @@ public struct APISwift { } } } - + public final class DeleteTeam1Mutation: GraphQLMutation { public static let operationString = "mutation DeleteTeam1($input: DeleteTeam1Input!, $condition: ModelTeam1ConditionInput) {\n deleteTeam1(input: $input, condition: $condition) {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteTeam1Input public var condition: ModelTeam1ConditionInput? - + public init(input: DeleteTeam1Input, condition: ModelTeam1ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteTeam1", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteTeam1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteTeam1: DeleteTeam1? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteTeam1": deleteTeam1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteTeam1": deleteTeam1.flatMap(\.snapshot)]) } - + public var deleteTeam1: DeleteTeam1? { get { return (snapshot["deleteTeam1"] as? Snapshot).flatMap { DeleteTeam1(snapshot: $0) } @@ -8682,10 +8690,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteTeam1") } } - + public struct DeleteTeam1: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -8693,17 +8701,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -8712,7 +8720,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -8721,7 +8729,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -8730,7 +8738,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -8739,7 +8747,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -8751,40 +8759,40 @@ public struct APISwift { } } } - + public final class CreateProject2Mutation: GraphQLMutation { public static let operationString = "mutation CreateProject2($input: CreateProject2Input!, $condition: ModelProject2ConditionInput) {\n createProject2(input: $input, condition: $condition) {\n __typename\n id\n name\n teamID\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var input: CreateProject2Input public var condition: ModelProject2ConditionInput? - + public init(input: CreateProject2Input, condition: ModelProject2ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createProject2", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateProject2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createProject2: CreateProject2? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createProject2": createProject2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createProject2": createProject2.flatMap(\.snapshot)]) } - + public var createProject2: CreateProject2? { get { return (snapshot["createProject2"] as? Snapshot).flatMap { CreateProject2(snapshot: $0) } @@ -8793,10 +8801,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createProject2") } } - + public struct CreateProject2: GraphQLSelectionSet { public static let possibleTypes = ["Project2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -8806,17 +8814,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, teamId: GraphQLID, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -8825,7 +8833,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -8834,7 +8842,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -8843,7 +8851,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var teamId: GraphQLID { get { return snapshot["teamID"]! as! GraphQLID @@ -8852,7 +8860,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "teamID") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -8861,7 +8869,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -8870,7 +8878,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -8879,10 +8887,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -8890,17 +8898,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -8909,7 +8917,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -8918,7 +8926,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -8927,7 +8935,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -8936,7 +8944,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -8949,40 +8957,40 @@ public struct APISwift { } } } - + public final class UpdateProject2Mutation: GraphQLMutation { public static let operationString = "mutation UpdateProject2($input: UpdateProject2Input!, $condition: ModelProject2ConditionInput) {\n updateProject2(input: $input, condition: $condition) {\n __typename\n id\n name\n teamID\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateProject2Input public var condition: ModelProject2ConditionInput? - + public init(input: UpdateProject2Input, condition: ModelProject2ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateProject2", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateProject2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateProject2: UpdateProject2? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateProject2": updateProject2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateProject2": updateProject2.flatMap(\.snapshot)]) } - + public var updateProject2: UpdateProject2? { get { return (snapshot["updateProject2"] as? Snapshot).flatMap { UpdateProject2(snapshot: $0) } @@ -8991,10 +8999,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateProject2") } } - + public struct UpdateProject2: GraphQLSelectionSet { public static let possibleTypes = ["Project2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -9004,17 +9012,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, teamId: GraphQLID, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -9023,7 +9031,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -9032,7 +9040,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -9041,7 +9049,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var teamId: GraphQLID { get { return snapshot["teamID"]! as! GraphQLID @@ -9050,7 +9058,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "teamID") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -9059,7 +9067,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -9068,7 +9076,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -9077,10 +9085,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -9088,17 +9096,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -9107,7 +9115,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -9116,7 +9124,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -9125,7 +9133,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -9134,7 +9142,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -9147,40 +9155,40 @@ public struct APISwift { } } } - + public final class DeleteProject2Mutation: GraphQLMutation { public static let operationString = "mutation DeleteProject2($input: DeleteProject2Input!, $condition: ModelProject2ConditionInput) {\n deleteProject2(input: $input, condition: $condition) {\n __typename\n id\n name\n teamID\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteProject2Input public var condition: ModelProject2ConditionInput? - + public init(input: DeleteProject2Input, condition: ModelProject2ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteProject2", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteProject2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteProject2: DeleteProject2? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteProject2": deleteProject2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteProject2": deleteProject2.flatMap(\.snapshot)]) } - + public var deleteProject2: DeleteProject2? { get { return (snapshot["deleteProject2"] as? Snapshot).flatMap { DeleteProject2(snapshot: $0) } @@ -9189,10 +9197,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteProject2") } } - + public struct DeleteProject2: GraphQLSelectionSet { public static let possibleTypes = ["Project2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -9202,17 +9210,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, teamId: GraphQLID, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -9221,7 +9229,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -9230,7 +9238,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -9239,7 +9247,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var teamId: GraphQLID { get { return snapshot["teamID"]! as! GraphQLID @@ -9248,7 +9256,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "teamID") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -9257,7 +9265,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -9266,7 +9274,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -9275,10 +9283,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -9286,17 +9294,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -9305,7 +9313,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -9314,7 +9322,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -9323,7 +9331,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -9332,7 +9340,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -9345,40 +9353,40 @@ public struct APISwift { } } } - + public final class CreateTeam2Mutation: GraphQLMutation { public static let operationString = "mutation CreateTeam2($input: CreateTeam2Input!, $condition: ModelTeam2ConditionInput) {\n createTeam2(input: $input, condition: $condition) {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public var input: CreateTeam2Input public var condition: ModelTeam2ConditionInput? - + public init(input: CreateTeam2Input, condition: ModelTeam2ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createTeam2", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateTeam2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createTeam2: CreateTeam2? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createTeam2": createTeam2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createTeam2": createTeam2.flatMap(\.snapshot)]) } - + public var createTeam2: CreateTeam2? { get { return (snapshot["createTeam2"] as? Snapshot).flatMap { CreateTeam2(snapshot: $0) } @@ -9387,10 +9395,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createTeam2") } } - + public struct CreateTeam2: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -9398,17 +9406,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -9417,7 +9425,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -9426,7 +9434,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -9435,7 +9443,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -9444,7 +9452,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -9456,40 +9464,40 @@ public struct APISwift { } } } - + public final class UpdateTeam2Mutation: GraphQLMutation { public static let operationString = "mutation UpdateTeam2($input: UpdateTeam2Input!, $condition: ModelTeam2ConditionInput) {\n updateTeam2(input: $input, condition: $condition) {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateTeam2Input public var condition: ModelTeam2ConditionInput? - + public init(input: UpdateTeam2Input, condition: ModelTeam2ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateTeam2", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateTeam2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateTeam2: UpdateTeam2? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateTeam2": updateTeam2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateTeam2": updateTeam2.flatMap(\.snapshot)]) } - + public var updateTeam2: UpdateTeam2? { get { return (snapshot["updateTeam2"] as? Snapshot).flatMap { UpdateTeam2(snapshot: $0) } @@ -9498,10 +9506,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateTeam2") } } - + public struct UpdateTeam2: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -9509,17 +9517,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -9528,7 +9536,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -9537,7 +9545,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -9546,7 +9554,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -9555,7 +9563,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -9567,40 +9575,40 @@ public struct APISwift { } } } - + public final class DeleteTeam2Mutation: GraphQLMutation { public static let operationString = "mutation DeleteTeam2($input: DeleteTeam2Input!, $condition: ModelTeam2ConditionInput) {\n deleteTeam2(input: $input, condition: $condition) {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteTeam2Input public var condition: ModelTeam2ConditionInput? - + public init(input: DeleteTeam2Input, condition: ModelTeam2ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteTeam2", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteTeam2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteTeam2: DeleteTeam2? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteTeam2": deleteTeam2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteTeam2": deleteTeam2.flatMap(\.snapshot)]) } - + public var deleteTeam2: DeleteTeam2? { get { return (snapshot["deleteTeam2"] as? Snapshot).flatMap { DeleteTeam2(snapshot: $0) } @@ -9609,10 +9617,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteTeam2") } } - + public struct DeleteTeam2: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -9620,17 +9628,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -9639,7 +9647,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -9648,7 +9656,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -9657,7 +9665,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -9666,7 +9674,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -9678,40 +9686,40 @@ public struct APISwift { } } } - + public final class CreatePost3Mutation: GraphQLMutation { public static let operationString = "mutation CreatePost3($input: CreatePost3Input!, $condition: ModelPost3ConditionInput) {\n createPost3(input: $input, condition: $condition) {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: CreatePost3Input public var condition: ModelPost3ConditionInput? - + public init(input: CreatePost3Input, condition: ModelPost3ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createPost3", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreatePost3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createPost3: CreatePost3? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createPost3": createPost3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createPost3": createPost3.flatMap(\.snapshot)]) } - + public var createPost3: CreatePost3? { get { return (snapshot["createPost3"] as? Snapshot).flatMap { CreatePost3(snapshot: $0) } @@ -9720,10 +9728,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createPost3") } } - + public struct CreatePost3: GraphQLSelectionSet { public static let possibleTypes = ["Post3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -9732,17 +9740,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -9751,7 +9759,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -9760,7 +9768,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -9769,7 +9777,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -9778,7 +9786,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -9787,7 +9795,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -9796,26 +9804,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment3Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -9824,16 +9832,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -9842,10 +9850,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -9854,17 +9862,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -9873,7 +9881,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -9882,7 +9890,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -9891,7 +9899,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -9900,7 +9908,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -9909,7 +9917,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -9923,40 +9931,40 @@ public struct APISwift { } } } - + public final class UpdatePost3Mutation: GraphQLMutation { public static let operationString = "mutation UpdatePost3($input: UpdatePost3Input!, $condition: ModelPost3ConditionInput) {\n updatePost3(input: $input, condition: $condition) {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: UpdatePost3Input public var condition: ModelPost3ConditionInput? - + public init(input: UpdatePost3Input, condition: ModelPost3ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updatePost3", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdatePost3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updatePost3: UpdatePost3? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updatePost3": updatePost3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updatePost3": updatePost3.flatMap(\.snapshot)]) } - + public var updatePost3: UpdatePost3? { get { return (snapshot["updatePost3"] as? Snapshot).flatMap { UpdatePost3(snapshot: $0) } @@ -9965,10 +9973,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updatePost3") } } - + public struct UpdatePost3: GraphQLSelectionSet { public static let possibleTypes = ["Post3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -9977,17 +9985,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -9996,7 +10004,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -10005,7 +10013,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -10014,7 +10022,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -10023,7 +10031,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -10032,7 +10040,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -10041,26 +10049,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment3Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -10069,16 +10077,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -10087,10 +10095,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -10099,17 +10107,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -10118,7 +10126,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -10127,7 +10135,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -10136,7 +10144,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -10145,7 +10153,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -10154,7 +10162,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -10168,40 +10176,40 @@ public struct APISwift { } } } - + public final class DeletePost3Mutation: GraphQLMutation { public static let operationString = "mutation DeletePost3($input: DeletePost3Input!, $condition: ModelPost3ConditionInput) {\n deletePost3(input: $input, condition: $condition) {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: DeletePost3Input public var condition: ModelPost3ConditionInput? - + public init(input: DeletePost3Input, condition: ModelPost3ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deletePost3", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeletePost3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deletePost3: DeletePost3? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deletePost3": deletePost3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deletePost3": deletePost3.flatMap(\.snapshot)]) } - + public var deletePost3: DeletePost3? { get { return (snapshot["deletePost3"] as? Snapshot).flatMap { DeletePost3(snapshot: $0) } @@ -10210,10 +10218,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deletePost3") } } - + public struct DeletePost3: GraphQLSelectionSet { public static let possibleTypes = ["Post3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -10222,17 +10230,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -10241,7 +10249,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -10250,7 +10258,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -10259,7 +10267,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -10268,7 +10276,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -10277,7 +10285,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -10286,26 +10294,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment3Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -10314,16 +10322,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -10332,10 +10340,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -10344,17 +10352,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -10363,7 +10371,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -10372,7 +10380,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -10381,7 +10389,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -10390,7 +10398,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -10399,7 +10407,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -10413,40 +10421,40 @@ public struct APISwift { } } } - + public final class CreateComment3Mutation: GraphQLMutation { public static let operationString = "mutation CreateComment3($input: CreateComment3Input!, $condition: ModelComment3ConditionInput) {\n createComment3(input: $input, condition: $condition) {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n}" - + public var input: CreateComment3Input public var condition: ModelComment3ConditionInput? - + public init(input: CreateComment3Input, condition: ModelComment3ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createComment3", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateComment3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createComment3: CreateComment3? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createComment3": createComment3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createComment3": createComment3.flatMap(\.snapshot)]) } - + public var createComment3: CreateComment3? { get { return (snapshot["createComment3"] as? Snapshot).flatMap { CreateComment3(snapshot: $0) } @@ -10455,10 +10463,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createComment3") } } - + public struct CreateComment3: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -10467,17 +10475,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -10486,7 +10494,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -10495,7 +10503,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -10504,7 +10512,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -10513,7 +10521,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -10522,7 +10530,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -10534,40 +10542,40 @@ public struct APISwift { } } } - + public final class UpdateComment3Mutation: GraphQLMutation { public static let operationString = "mutation UpdateComment3($input: UpdateComment3Input!, $condition: ModelComment3ConditionInput) {\n updateComment3(input: $input, condition: $condition) {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateComment3Input public var condition: ModelComment3ConditionInput? - + public init(input: UpdateComment3Input, condition: ModelComment3ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateComment3", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateComment3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateComment3: UpdateComment3? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateComment3": updateComment3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateComment3": updateComment3.flatMap(\.snapshot)]) } - + public var updateComment3: UpdateComment3? { get { return (snapshot["updateComment3"] as? Snapshot).flatMap { UpdateComment3(snapshot: $0) } @@ -10576,10 +10584,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateComment3") } } - + public struct UpdateComment3: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -10588,17 +10596,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -10607,7 +10615,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -10616,7 +10624,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -10625,7 +10633,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -10634,7 +10642,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -10643,7 +10651,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -10655,40 +10663,40 @@ public struct APISwift { } } } - + public final class DeleteComment3Mutation: GraphQLMutation { public static let operationString = "mutation DeleteComment3($input: DeleteComment3Input!, $condition: ModelComment3ConditionInput) {\n deleteComment3(input: $input, condition: $condition) {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteComment3Input public var condition: ModelComment3ConditionInput? - + public init(input: DeleteComment3Input, condition: ModelComment3ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteComment3", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteComment3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteComment3: DeleteComment3? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteComment3": deleteComment3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteComment3": deleteComment3.flatMap(\.snapshot)]) } - + public var deleteComment3: DeleteComment3? { get { return (snapshot["deleteComment3"] as? Snapshot).flatMap { DeleteComment3(snapshot: $0) } @@ -10697,10 +10705,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteComment3") } } - + public struct DeleteComment3: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -10709,17 +10717,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -10728,7 +10736,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -10737,7 +10745,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -10746,7 +10754,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -10755,7 +10763,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -10764,7 +10772,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -10776,40 +10784,40 @@ public struct APISwift { } } } - + public final class CreatePost4Mutation: GraphQLMutation { public static let operationString = "mutation CreatePost4($input: CreatePost4Input!, $condition: ModelPost4ConditionInput) {\n createPost4(input: $input, condition: $condition) {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: CreatePost4Input public var condition: ModelPost4ConditionInput? - + public init(input: CreatePost4Input, condition: ModelPost4ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createPost4", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreatePost4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createPost4: CreatePost4? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createPost4": createPost4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createPost4": createPost4.flatMap(\.snapshot)]) } - + public var createPost4: CreatePost4? { get { return (snapshot["createPost4"] as? Snapshot).flatMap { CreatePost4(snapshot: $0) } @@ -10818,10 +10826,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createPost4") } } - + public struct CreatePost4: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -10830,17 +10838,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -10849,7 +10857,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -10858,7 +10866,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -10867,7 +10875,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -10876,7 +10884,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -10885,7 +10893,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -10894,26 +10902,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -10922,16 +10930,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -10940,10 +10948,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -10952,17 +10960,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -10971,7 +10979,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -10980,7 +10988,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -10989,7 +10997,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -10998,7 +11006,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -11007,7 +11015,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -11021,40 +11029,40 @@ public struct APISwift { } } } - + public final class UpdatePost4Mutation: GraphQLMutation { public static let operationString = "mutation UpdatePost4($input: UpdatePost4Input!, $condition: ModelPost4ConditionInput) {\n updatePost4(input: $input, condition: $condition) {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: UpdatePost4Input public var condition: ModelPost4ConditionInput? - + public init(input: UpdatePost4Input, condition: ModelPost4ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updatePost4", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdatePost4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updatePost4: UpdatePost4? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updatePost4": updatePost4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updatePost4": updatePost4.flatMap(\.snapshot)]) } - + public var updatePost4: UpdatePost4? { get { return (snapshot["updatePost4"] as? Snapshot).flatMap { UpdatePost4(snapshot: $0) } @@ -11063,10 +11071,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updatePost4") } } - + public struct UpdatePost4: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -11075,17 +11083,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -11094,7 +11102,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -11103,7 +11111,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -11112,7 +11120,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -11121,7 +11129,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -11130,7 +11138,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -11139,26 +11147,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -11167,16 +11175,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -11185,10 +11193,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -11197,17 +11205,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -11216,7 +11224,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -11225,7 +11233,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -11234,7 +11242,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -11243,7 +11251,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -11252,7 +11260,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -11266,40 +11274,40 @@ public struct APISwift { } } } - + public final class DeletePost4Mutation: GraphQLMutation { public static let operationString = "mutation DeletePost4($input: DeletePost4Input!, $condition: ModelPost4ConditionInput) {\n deletePost4(input: $input, condition: $condition) {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: DeletePost4Input public var condition: ModelPost4ConditionInput? - + public init(input: DeletePost4Input, condition: ModelPost4ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deletePost4", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeletePost4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deletePost4: DeletePost4? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deletePost4": deletePost4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deletePost4": deletePost4.flatMap(\.snapshot)]) } - + public var deletePost4: DeletePost4? { get { return (snapshot["deletePost4"] as? Snapshot).flatMap { DeletePost4(snapshot: $0) } @@ -11308,10 +11316,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deletePost4") } } - + public struct DeletePost4: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -11320,17 +11328,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -11339,7 +11347,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -11348,7 +11356,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -11357,7 +11365,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -11366,7 +11374,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -11375,7 +11383,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -11384,26 +11392,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -11412,16 +11420,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -11430,10 +11438,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -11442,17 +11450,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -11461,7 +11469,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -11470,7 +11478,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -11479,7 +11487,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -11488,7 +11496,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -11497,7 +11505,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -11511,40 +11519,40 @@ public struct APISwift { } } } - + public final class CreateComment4Mutation: GraphQLMutation { public static let operationString = "mutation CreateComment4($input: CreateComment4Input!, $condition: ModelComment4ConditionInput) {\n createComment4(input: $input, condition: $condition) {\n __typename\n id\n postID\n content\n post {\n __typename\n id\n title\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var input: CreateComment4Input public var condition: ModelComment4ConditionInput? - + public init(input: CreateComment4Input, condition: ModelComment4ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createComment4", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateComment4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createComment4: CreateComment4? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createComment4": createComment4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createComment4": createComment4.flatMap(\.snapshot)]) } - + public var createComment4: CreateComment4? { get { return (snapshot["createComment4"] as? Snapshot).flatMap { CreateComment4(snapshot: $0) } @@ -11553,10 +11561,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createComment4") } } - + public struct CreateComment4: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -11566,17 +11574,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, post: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -11585,7 +11593,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -11594,7 +11602,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -11603,7 +11611,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -11612,7 +11620,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -11621,7 +11629,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -11630,7 +11638,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -11639,10 +11647,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -11651,17 +11659,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -11670,7 +11678,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -11679,7 +11687,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -11688,7 +11696,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -11697,7 +11705,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -11706,7 +11714,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -11715,25 +11723,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment4Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -11742,7 +11750,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -11756,40 +11764,40 @@ public struct APISwift { } } } - + public final class UpdateComment4Mutation: GraphQLMutation { public static let operationString = "mutation UpdateComment4($input: UpdateComment4Input!, $condition: ModelComment4ConditionInput) {\n updateComment4(input: $input, condition: $condition) {\n __typename\n id\n postID\n content\n post {\n __typename\n id\n title\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateComment4Input public var condition: ModelComment4ConditionInput? - + public init(input: UpdateComment4Input, condition: ModelComment4ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateComment4", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateComment4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateComment4: UpdateComment4? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateComment4": updateComment4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateComment4": updateComment4.flatMap(\.snapshot)]) } - + public var updateComment4: UpdateComment4? { get { return (snapshot["updateComment4"] as? Snapshot).flatMap { UpdateComment4(snapshot: $0) } @@ -11798,10 +11806,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateComment4") } } - + public struct UpdateComment4: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -11811,17 +11819,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, post: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -11830,7 +11838,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -11839,7 +11847,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -11848,7 +11856,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -11857,7 +11865,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -11866,7 +11874,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -11875,7 +11883,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -11884,10 +11892,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -11896,17 +11904,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -11915,7 +11923,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -11924,7 +11932,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -11933,7 +11941,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -11942,7 +11950,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -11951,7 +11959,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -11960,25 +11968,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment4Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -11987,7 +11995,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -12001,40 +12009,40 @@ public struct APISwift { } } } - + public final class DeleteComment4Mutation: GraphQLMutation { public static let operationString = "mutation DeleteComment4($input: DeleteComment4Input!, $condition: ModelComment4ConditionInput) {\n deleteComment4(input: $input, condition: $condition) {\n __typename\n id\n postID\n content\n post {\n __typename\n id\n title\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteComment4Input public var condition: ModelComment4ConditionInput? - + public init(input: DeleteComment4Input, condition: ModelComment4ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteComment4", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteComment4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteComment4: DeleteComment4? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteComment4": deleteComment4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteComment4": deleteComment4.flatMap(\.snapshot)]) } - + public var deleteComment4: DeleteComment4? { get { return (snapshot["deleteComment4"] as? Snapshot).flatMap { DeleteComment4(snapshot: $0) } @@ -12043,10 +12051,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteComment4") } } - + public struct DeleteComment4: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -12056,17 +12064,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, post: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -12075,7 +12083,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -12084,7 +12092,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -12093,7 +12101,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -12102,7 +12110,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -12111,7 +12119,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -12120,7 +12128,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -12129,10 +12137,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -12141,17 +12149,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -12160,7 +12168,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -12169,7 +12177,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -12178,7 +12186,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -12187,7 +12195,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -12196,7 +12204,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -12205,25 +12213,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment4Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -12232,7 +12240,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -12246,40 +12254,40 @@ public struct APISwift { } } } - + public final class CreatePost5Mutation: GraphQLMutation { public static let operationString = "mutation CreatePost5($input: CreatePost5Input!, $condition: ModelPost5ConditionInput) {\n createPost5(input: $input, condition: $condition) {\n __typename\n id\n title\n editors {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: CreatePost5Input public var condition: ModelPost5ConditionInput? - + public init(input: CreatePost5Input, condition: ModelPost5ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createPost5", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreatePost5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createPost5: CreatePost5? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createPost5": createPost5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createPost5": createPost5.flatMap(\.snapshot)]) } - + public var createPost5: CreatePost5? { get { return (snapshot["createPost5"] as? Snapshot).flatMap { CreatePost5(snapshot: $0) } @@ -12288,10 +12296,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createPost5") } } - + public struct CreatePost5: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -12300,17 +12308,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -12319,7 +12327,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -12328,7 +12336,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -12337,7 +12345,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -12346,7 +12354,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -12355,7 +12363,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -12364,26 +12372,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -12392,16 +12400,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -12410,10 +12418,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -12422,17 +12430,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -12441,7 +12449,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -12450,7 +12458,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -12459,7 +12467,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -12468,7 +12476,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -12477,7 +12485,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -12491,40 +12499,40 @@ public struct APISwift { } } } - + public final class UpdatePost5Mutation: GraphQLMutation { public static let operationString = "mutation UpdatePost5($input: UpdatePost5Input!, $condition: ModelPost5ConditionInput) {\n updatePost5(input: $input, condition: $condition) {\n __typename\n id\n title\n editors {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: UpdatePost5Input public var condition: ModelPost5ConditionInput? - + public init(input: UpdatePost5Input, condition: ModelPost5ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updatePost5", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdatePost5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updatePost5: UpdatePost5? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updatePost5": updatePost5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updatePost5": updatePost5.flatMap(\.snapshot)]) } - + public var updatePost5: UpdatePost5? { get { return (snapshot["updatePost5"] as? Snapshot).flatMap { UpdatePost5(snapshot: $0) } @@ -12533,10 +12541,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updatePost5") } } - + public struct UpdatePost5: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -12545,17 +12553,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -12564,7 +12572,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -12573,7 +12581,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -12582,7 +12590,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -12591,7 +12599,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -12600,7 +12608,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -12609,26 +12617,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -12637,16 +12645,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -12655,10 +12663,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -12667,17 +12675,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -12686,7 +12694,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -12695,7 +12703,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -12704,7 +12712,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -12713,7 +12721,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -12722,7 +12730,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -12736,40 +12744,40 @@ public struct APISwift { } } } - + public final class DeletePost5Mutation: GraphQLMutation { public static let operationString = "mutation DeletePost5($input: DeletePost5Input!, $condition: ModelPost5ConditionInput) {\n deletePost5(input: $input, condition: $condition) {\n __typename\n id\n title\n editors {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: DeletePost5Input public var condition: ModelPost5ConditionInput? - + public init(input: DeletePost5Input, condition: ModelPost5ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deletePost5", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeletePost5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deletePost5: DeletePost5? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deletePost5": deletePost5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deletePost5": deletePost5.flatMap(\.snapshot)]) } - + public var deletePost5: DeletePost5? { get { return (snapshot["deletePost5"] as? Snapshot).flatMap { DeletePost5(snapshot: $0) } @@ -12778,10 +12786,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deletePost5") } } - + public struct DeletePost5: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -12790,17 +12798,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -12809,7 +12817,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -12818,7 +12826,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -12827,7 +12835,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -12836,7 +12844,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -12845,7 +12853,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -12854,26 +12862,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -12882,16 +12890,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -12900,10 +12908,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -12912,17 +12920,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -12931,7 +12939,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -12940,7 +12948,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -12949,7 +12957,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -12958,7 +12966,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -12967,7 +12975,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -12981,40 +12989,40 @@ public struct APISwift { } } } - + public final class CreatePostEditor5Mutation: GraphQLMutation { public static let operationString = "mutation CreatePostEditor5($input: CreatePostEditor5Input!, $condition: ModelPostEditor5ConditionInput) {\n createPostEditor5(input: $input, condition: $condition) {\n __typename\n id\n postID\n editorID\n post {\n __typename\n id\n title\n editors {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n editor {\n __typename\n id\n username\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var input: CreatePostEditor5Input public var condition: ModelPostEditor5ConditionInput? - + public init(input: CreatePostEditor5Input, condition: ModelPostEditor5ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createPostEditor5", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreatePostEditor5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createPostEditor5: CreatePostEditor5? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createPostEditor5": createPostEditor5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createPostEditor5": createPostEditor5.flatMap(\.snapshot)]) } - + public var createPostEditor5: CreatePostEditor5? { get { return (snapshot["createPostEditor5"] as? Snapshot).flatMap { CreatePostEditor5(snapshot: $0) } @@ -13023,10 +13031,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createPostEditor5") } } - + public struct CreatePostEditor5: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -13037,17 +13045,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, post: Post, editor: Editor, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "post": post.snapshot, "editor": editor.snapshot, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13056,7 +13064,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -13065,7 +13073,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -13074,7 +13082,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -13083,7 +13091,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var post: Post { get { return Post(snapshot: snapshot["post"]! as! Snapshot) @@ -13092,7 +13100,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "post") } } - + public var editor: Editor { get { return Editor(snapshot: snapshot["editor"]! as! Snapshot) @@ -13101,7 +13109,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "editor") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -13110,7 +13118,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -13119,10 +13127,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -13131,17 +13139,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13150,7 +13158,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -13159,7 +13167,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -13168,7 +13176,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -13177,7 +13185,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -13186,7 +13194,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -13195,25 +13203,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13222,7 +13230,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -13233,10 +13241,10 @@ public struct APISwift { } } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -13245,17 +13253,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13264,7 +13272,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -13273,7 +13281,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -13282,7 +13290,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -13291,7 +13299,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -13300,7 +13308,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -13309,25 +13317,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13336,7 +13344,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -13350,40 +13358,40 @@ public struct APISwift { } } } - + public final class UpdatePostEditor5Mutation: GraphQLMutation { public static let operationString = "mutation UpdatePostEditor5($input: UpdatePostEditor5Input!, $condition: ModelPostEditor5ConditionInput) {\n updatePostEditor5(input: $input, condition: $condition) {\n __typename\n id\n postID\n editorID\n post {\n __typename\n id\n title\n editors {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n editor {\n __typename\n id\n username\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var input: UpdatePostEditor5Input public var condition: ModelPostEditor5ConditionInput? - + public init(input: UpdatePostEditor5Input, condition: ModelPostEditor5ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updatePostEditor5", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdatePostEditor5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updatePostEditor5: UpdatePostEditor5? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updatePostEditor5": updatePostEditor5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updatePostEditor5": updatePostEditor5.flatMap(\.snapshot)]) } - + public var updatePostEditor5: UpdatePostEditor5? { get { return (snapshot["updatePostEditor5"] as? Snapshot).flatMap { UpdatePostEditor5(snapshot: $0) } @@ -13392,10 +13400,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updatePostEditor5") } } - + public struct UpdatePostEditor5: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -13406,17 +13414,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, post: Post, editor: Editor, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "post": post.snapshot, "editor": editor.snapshot, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13425,7 +13433,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -13434,7 +13442,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -13443,7 +13451,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -13452,7 +13460,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var post: Post { get { return Post(snapshot: snapshot["post"]! as! Snapshot) @@ -13461,7 +13469,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "post") } } - + public var editor: Editor { get { return Editor(snapshot: snapshot["editor"]! as! Snapshot) @@ -13470,7 +13478,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "editor") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -13479,7 +13487,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -13488,10 +13496,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -13500,17 +13508,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13519,7 +13527,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -13528,7 +13536,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -13537,7 +13545,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -13546,7 +13554,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -13555,7 +13563,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -13564,25 +13572,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13591,7 +13599,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -13602,10 +13610,10 @@ public struct APISwift { } } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -13614,17 +13622,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13633,7 +13641,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -13642,7 +13650,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -13651,7 +13659,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -13660,7 +13668,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -13669,7 +13677,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -13678,25 +13686,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13705,7 +13713,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -13719,40 +13727,40 @@ public struct APISwift { } } } - + public final class DeletePostEditor5Mutation: GraphQLMutation { public static let operationString = "mutation DeletePostEditor5($input: DeletePostEditor5Input!, $condition: ModelPostEditor5ConditionInput) {\n deletePostEditor5(input: $input, condition: $condition) {\n __typename\n id\n postID\n editorID\n post {\n __typename\n id\n title\n editors {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n editor {\n __typename\n id\n username\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var input: DeletePostEditor5Input public var condition: ModelPostEditor5ConditionInput? - + public init(input: DeletePostEditor5Input, condition: ModelPostEditor5ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deletePostEditor5", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeletePostEditor5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deletePostEditor5: DeletePostEditor5? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deletePostEditor5": deletePostEditor5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deletePostEditor5": deletePostEditor5.flatMap(\.snapshot)]) } - + public var deletePostEditor5: DeletePostEditor5? { get { return (snapshot["deletePostEditor5"] as? Snapshot).flatMap { DeletePostEditor5(snapshot: $0) } @@ -13761,10 +13769,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deletePostEditor5") } } - + public struct DeletePostEditor5: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -13775,17 +13783,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, post: Post, editor: Editor, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "post": post.snapshot, "editor": editor.snapshot, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13794,7 +13802,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -13803,7 +13811,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -13812,7 +13820,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -13821,7 +13829,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var post: Post { get { return Post(snapshot: snapshot["post"]! as! Snapshot) @@ -13830,7 +13838,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "post") } } - + public var editor: Editor { get { return Editor(snapshot: snapshot["editor"]! as! Snapshot) @@ -13839,7 +13847,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "editor") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -13848,7 +13856,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -13857,10 +13865,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -13869,17 +13877,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13888,7 +13896,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -13897,7 +13905,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -13906,7 +13914,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -13915,7 +13923,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -13924,7 +13932,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -13933,25 +13941,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -13960,7 +13968,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -13971,10 +13979,10 @@ public struct APISwift { } } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -13983,17 +13991,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14002,7 +14010,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -14011,7 +14019,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -14020,7 +14028,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -14029,7 +14037,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -14038,7 +14046,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -14047,25 +14055,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14074,7 +14082,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -14088,40 +14096,40 @@ public struct APISwift { } } } - + public final class CreateUser5Mutation: GraphQLMutation { public static let operationString = "mutation CreateUser5($input: CreateUser5Input!, $condition: ModelUser5ConditionInput) {\n createUser5(input: $input, condition: $condition) {\n __typename\n id\n username\n posts {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: CreateUser5Input public var condition: ModelUser5ConditionInput? - + public init(input: CreateUser5Input, condition: ModelUser5ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createUser5", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateUser5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createUser5: CreateUser5? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createUser5": createUser5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createUser5": createUser5.flatMap(\.snapshot)]) } - + public var createUser5: CreateUser5? { get { return (snapshot["createUser5"] as? Snapshot).flatMap { CreateUser5(snapshot: $0) } @@ -14130,10 +14138,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createUser5") } } - + public struct CreateUser5: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -14142,17 +14150,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14161,7 +14169,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -14170,7 +14178,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -14179,7 +14187,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -14188,7 +14196,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -14197,7 +14205,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -14206,26 +14214,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14234,16 +14242,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -14252,10 +14260,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -14264,17 +14272,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14283,7 +14291,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -14292,7 +14300,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -14301,7 +14309,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -14310,7 +14318,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -14319,7 +14327,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -14333,40 +14341,40 @@ public struct APISwift { } } } - + public final class UpdateUser5Mutation: GraphQLMutation { public static let operationString = "mutation UpdateUser5($input: UpdateUser5Input!, $condition: ModelUser5ConditionInput) {\n updateUser5(input: $input, condition: $condition) {\n __typename\n id\n username\n posts {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateUser5Input public var condition: ModelUser5ConditionInput? - + public init(input: UpdateUser5Input, condition: ModelUser5ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateUser5", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateUser5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateUser5: UpdateUser5? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateUser5": updateUser5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateUser5": updateUser5.flatMap(\.snapshot)]) } - + public var updateUser5: UpdateUser5? { get { return (snapshot["updateUser5"] as? Snapshot).flatMap { UpdateUser5(snapshot: $0) } @@ -14375,10 +14383,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateUser5") } } - + public struct UpdateUser5: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -14387,17 +14395,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14406,7 +14414,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -14415,7 +14423,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -14424,7 +14432,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -14433,7 +14441,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -14442,7 +14450,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -14451,26 +14459,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14479,16 +14487,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -14497,10 +14505,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -14509,17 +14517,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14528,7 +14536,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -14537,7 +14545,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -14546,7 +14554,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -14555,7 +14563,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -14564,7 +14572,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -14578,40 +14586,40 @@ public struct APISwift { } } } - + public final class DeleteUser5Mutation: GraphQLMutation { public static let operationString = "mutation DeleteUser5($input: DeleteUser5Input!, $condition: ModelUser5ConditionInput) {\n deleteUser5(input: $input, condition: $condition) {\n __typename\n id\n username\n posts {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteUser5Input public var condition: ModelUser5ConditionInput? - + public init(input: DeleteUser5Input, condition: ModelUser5ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteUser5", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteUser5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteUser5: DeleteUser5? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteUser5": deleteUser5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteUser5": deleteUser5.flatMap(\.snapshot)]) } - + public var deleteUser5: DeleteUser5? { get { return (snapshot["deleteUser5"] as? Snapshot).flatMap { DeleteUser5(snapshot: $0) } @@ -14620,10 +14628,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteUser5") } } - + public struct DeleteUser5: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -14632,17 +14640,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14651,7 +14659,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -14660,7 +14668,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -14669,7 +14677,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -14678,7 +14686,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -14687,7 +14695,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -14696,26 +14704,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14724,16 +14732,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -14742,10 +14750,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -14754,17 +14762,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14773,7 +14781,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -14782,7 +14790,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -14791,7 +14799,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -14800,7 +14808,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -14809,7 +14817,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -14823,40 +14831,40 @@ public struct APISwift { } } } - + public final class CreateBlog6Mutation: GraphQLMutation { public static let operationString = "mutation CreateBlog6($input: CreateBlog6Input!, $condition: ModelBlog6ConditionInput) {\n createBlog6(input: $input, condition: $condition) {\n __typename\n id\n name\n posts {\n __typename\n items {\n __typename\n id\n title\n blogID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: CreateBlog6Input public var condition: ModelBlog6ConditionInput? - + public init(input: CreateBlog6Input, condition: ModelBlog6ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createBlog6", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateBlog6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createBlog6: CreateBlog6? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createBlog6": createBlog6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createBlog6": createBlog6.flatMap(\.snapshot)]) } - + public var createBlog6: CreateBlog6? { get { return (snapshot["createBlog6"] as? Snapshot).flatMap { CreateBlog6(snapshot: $0) } @@ -14865,10 +14873,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createBlog6") } } - + public struct CreateBlog6: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -14877,17 +14885,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14896,7 +14904,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -14905,7 +14913,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -14914,7 +14922,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -14923,7 +14931,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -14932,7 +14940,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -14941,26 +14949,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -14969,16 +14977,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -14987,10 +14995,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -14999,17 +15007,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -15018,7 +15026,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -15027,7 +15035,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -15036,7 +15044,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -15045,7 +15053,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -15054,7 +15062,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -15068,40 +15076,40 @@ public struct APISwift { } } } - + public final class UpdateBlog6Mutation: GraphQLMutation { public static let operationString = "mutation UpdateBlog6($input: UpdateBlog6Input!, $condition: ModelBlog6ConditionInput) {\n updateBlog6(input: $input, condition: $condition) {\n __typename\n id\n name\n posts {\n __typename\n items {\n __typename\n id\n title\n blogID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateBlog6Input public var condition: ModelBlog6ConditionInput? - + public init(input: UpdateBlog6Input, condition: ModelBlog6ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateBlog6", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateBlog6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateBlog6: UpdateBlog6? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateBlog6": updateBlog6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateBlog6": updateBlog6.flatMap(\.snapshot)]) } - + public var updateBlog6: UpdateBlog6? { get { return (snapshot["updateBlog6"] as? Snapshot).flatMap { UpdateBlog6(snapshot: $0) } @@ -15110,10 +15118,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateBlog6") } } - + public struct UpdateBlog6: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -15122,17 +15130,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -15141,7 +15149,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -15150,7 +15158,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -15159,7 +15167,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -15168,7 +15176,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -15177,7 +15185,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -15186,26 +15194,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -15214,16 +15222,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -15232,10 +15240,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -15244,17 +15252,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -15263,7 +15271,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -15272,7 +15280,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -15281,7 +15289,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -15290,7 +15298,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -15299,7 +15307,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -15313,40 +15321,40 @@ public struct APISwift { } } } - + public final class DeleteBlog6Mutation: GraphQLMutation { public static let operationString = "mutation DeleteBlog6($input: DeleteBlog6Input!, $condition: ModelBlog6ConditionInput) {\n deleteBlog6(input: $input, condition: $condition) {\n __typename\n id\n name\n posts {\n __typename\n items {\n __typename\n id\n title\n blogID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteBlog6Input public var condition: ModelBlog6ConditionInput? - + public init(input: DeleteBlog6Input, condition: ModelBlog6ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteBlog6", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteBlog6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteBlog6: DeleteBlog6? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteBlog6": deleteBlog6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteBlog6": deleteBlog6.flatMap(\.snapshot)]) } - + public var deleteBlog6: DeleteBlog6? { get { return (snapshot["deleteBlog6"] as? Snapshot).flatMap { DeleteBlog6(snapshot: $0) } @@ -15355,10 +15363,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteBlog6") } } - + public struct DeleteBlog6: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -15367,17 +15375,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -15386,7 +15394,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -15395,7 +15403,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -15404,7 +15412,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -15413,7 +15421,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -15422,7 +15430,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -15431,26 +15439,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -15459,16 +15467,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -15477,10 +15485,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -15489,17 +15497,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -15508,7 +15516,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -15517,7 +15525,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -15526,7 +15534,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -15535,7 +15543,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -15544,7 +15552,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -15558,40 +15566,40 @@ public struct APISwift { } } } - + public final class CreatePost6Mutation: GraphQLMutation { public static let operationString = "mutation CreatePost6($input: CreatePost6Input!, $condition: ModelPost6ConditionInput) {\n createPost6(input: $input, condition: $condition) {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: CreatePost6Input public var condition: ModelPost6ConditionInput? - + public init(input: CreatePost6Input, condition: ModelPost6ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createPost6", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreatePost6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createPost6: CreatePost6? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createPost6": createPost6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createPost6": createPost6.flatMap(\.snapshot)]) } - + public var createPost6: CreatePost6? { get { return (snapshot["createPost6"] as? Snapshot).flatMap { CreatePost6(snapshot: $0) } @@ -15600,10 +15608,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createPost6") } } - + public struct CreatePost6: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -15614,17 +15622,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -15633,7 +15641,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -15642,7 +15650,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -15651,7 +15659,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -15660,7 +15668,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -15669,7 +15677,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -15678,7 +15686,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -15687,7 +15695,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -15696,10 +15704,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -15708,17 +15716,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -15727,7 +15735,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -15736,7 +15744,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -15745,7 +15753,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -15754,7 +15762,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -15763,7 +15771,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -15772,25 +15780,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPost6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -15799,7 +15807,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -15810,26 +15818,26 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -15838,16 +15846,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -15856,10 +15864,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -15868,17 +15876,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -15887,7 +15895,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -15896,7 +15904,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -15905,7 +15913,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -15914,7 +15922,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -15923,7 +15931,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -15937,40 +15945,40 @@ public struct APISwift { } } } - + public final class UpdatePost6Mutation: GraphQLMutation { public static let operationString = "mutation UpdatePost6($input: UpdatePost6Input!, $condition: ModelPost6ConditionInput) {\n updatePost6(input: $input, condition: $condition) {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: UpdatePost6Input public var condition: ModelPost6ConditionInput? - + public init(input: UpdatePost6Input, condition: ModelPost6ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updatePost6", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdatePost6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updatePost6: UpdatePost6? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updatePost6": updatePost6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updatePost6": updatePost6.flatMap(\.snapshot)]) } - + public var updatePost6: UpdatePost6? { get { return (snapshot["updatePost6"] as? Snapshot).flatMap { UpdatePost6(snapshot: $0) } @@ -15979,10 +15987,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updatePost6") } } - + public struct UpdatePost6: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -15993,17 +16001,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16012,7 +16020,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -16021,7 +16029,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -16030,7 +16038,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -16039,7 +16047,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -16048,7 +16056,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -16057,7 +16065,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -16066,7 +16074,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -16075,10 +16083,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -16087,17 +16095,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16106,7 +16114,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -16115,7 +16123,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -16124,7 +16132,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -16133,7 +16141,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -16142,7 +16150,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -16151,25 +16159,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPost6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16178,7 +16186,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -16189,26 +16197,26 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16217,16 +16225,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -16235,10 +16243,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -16247,17 +16255,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16266,7 +16274,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -16275,7 +16283,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -16284,7 +16292,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -16293,7 +16301,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -16302,7 +16310,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -16316,40 +16324,40 @@ public struct APISwift { } } } - + public final class DeletePost6Mutation: GraphQLMutation { public static let operationString = "mutation DeletePost6($input: DeletePost6Input!, $condition: ModelPost6ConditionInput) {\n deletePost6(input: $input, condition: $condition) {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var input: DeletePost6Input public var condition: ModelPost6ConditionInput? - + public init(input: DeletePost6Input, condition: ModelPost6ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deletePost6", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeletePost6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deletePost6: DeletePost6? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deletePost6": deletePost6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deletePost6": deletePost6.flatMap(\.snapshot)]) } - + public var deletePost6: DeletePost6? { get { return (snapshot["deletePost6"] as? Snapshot).flatMap { DeletePost6(snapshot: $0) } @@ -16358,10 +16366,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deletePost6") } } - + public struct DeletePost6: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -16372,17 +16380,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16391,7 +16399,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -16400,7 +16408,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -16409,7 +16417,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -16418,7 +16426,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -16427,7 +16435,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -16436,7 +16444,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -16445,7 +16453,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -16454,10 +16462,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -16466,17 +16474,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16485,7 +16493,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -16494,7 +16502,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -16503,7 +16511,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -16512,7 +16520,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -16521,7 +16529,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -16530,25 +16538,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPost6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16557,7 +16565,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -16568,26 +16576,26 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16596,16 +16604,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -16614,10 +16622,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -16626,17 +16634,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16645,7 +16653,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -16654,7 +16662,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -16663,7 +16671,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -16672,7 +16680,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -16681,7 +16689,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -16695,40 +16703,40 @@ public struct APISwift { } } } - + public final class CreateComment6Mutation: GraphQLMutation { public static let operationString = "mutation CreateComment6($input: CreateComment6Input!, $condition: ModelComment6ConditionInput) {\n createComment6(input: $input, condition: $condition) {\n __typename\n id\n postID\n post {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n content\n createdAt\n updatedAt\n }\n}" - + public var input: CreateComment6Input public var condition: ModelComment6ConditionInput? - + public init(input: CreateComment6Input, condition: ModelComment6ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createComment6", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateComment6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createComment6: CreateComment6? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createComment6": createComment6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createComment6": createComment6.flatMap(\.snapshot)]) } - + public var createComment6: CreateComment6? { get { return (snapshot["createComment6"] as? Snapshot).flatMap { CreateComment6(snapshot: $0) } @@ -16737,10 +16745,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createComment6") } } - + public struct CreateComment6: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -16750,17 +16758,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, post: Post? = nil, content: String, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap { $0.snapshot }, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap(\.snapshot), "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16769,7 +16777,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -16778,7 +16786,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -16787,7 +16795,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -16796,7 +16804,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -16805,7 +16813,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -16814,7 +16822,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -16823,10 +16831,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -16837,17 +16845,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16856,7 +16864,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -16865,7 +16873,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -16874,7 +16882,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -16883,7 +16891,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -16892,7 +16900,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -16901,7 +16909,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -16910,7 +16918,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -16919,10 +16927,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -16930,17 +16938,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -16949,7 +16957,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -16958,7 +16966,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -16967,7 +16975,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -16976,7 +16984,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -16986,25 +16994,25 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -17013,7 +17021,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -17027,40 +17035,40 @@ public struct APISwift { } } } - + public final class UpdateComment6Mutation: GraphQLMutation { public static let operationString = "mutation UpdateComment6($input: UpdateComment6Input!, $condition: ModelComment6ConditionInput) {\n updateComment6(input: $input, condition: $condition) {\n __typename\n id\n postID\n post {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n content\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateComment6Input public var condition: ModelComment6ConditionInput? - + public init(input: UpdateComment6Input, condition: ModelComment6ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateComment6", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateComment6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateComment6: UpdateComment6? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateComment6": updateComment6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateComment6": updateComment6.flatMap(\.snapshot)]) } - + public var updateComment6: UpdateComment6? { get { return (snapshot["updateComment6"] as? Snapshot).flatMap { UpdateComment6(snapshot: $0) } @@ -17069,10 +17077,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateComment6") } } - + public struct UpdateComment6: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -17082,17 +17090,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, post: Post? = nil, content: String, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap { $0.snapshot }, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap(\.snapshot), "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -17101,7 +17109,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -17110,7 +17118,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -17119,7 +17127,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -17128,7 +17136,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -17137,7 +17145,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -17146,7 +17154,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -17155,10 +17163,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -17169,17 +17177,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -17188,7 +17196,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -17197,7 +17205,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -17206,7 +17214,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -17215,7 +17223,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -17224,7 +17232,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -17233,7 +17241,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -17242,7 +17250,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -17251,10 +17259,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -17262,17 +17270,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -17281,7 +17289,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -17290,7 +17298,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -17299,7 +17307,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -17308,7 +17316,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -17318,25 +17326,25 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -17345,7 +17353,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -17359,40 +17367,40 @@ public struct APISwift { } } } - + public final class DeleteComment6Mutation: GraphQLMutation { public static let operationString = "mutation DeleteComment6($input: DeleteComment6Input!, $condition: ModelComment6ConditionInput) {\n deleteComment6(input: $input, condition: $condition) {\n __typename\n id\n postID\n post {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n content\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteComment6Input public var condition: ModelComment6ConditionInput? - + public init(input: DeleteComment6Input, condition: ModelComment6ConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteComment6", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteComment6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteComment6: DeleteComment6? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteComment6": deleteComment6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteComment6": deleteComment6.flatMap(\.snapshot)]) } - + public var deleteComment6: DeleteComment6? { get { return (snapshot["deleteComment6"] as? Snapshot).flatMap { DeleteComment6(snapshot: $0) } @@ -17401,10 +17409,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteComment6") } } - + public struct DeleteComment6: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -17414,17 +17422,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, post: Post? = nil, content: String, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap { $0.snapshot }, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap(\.snapshot), "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -17433,7 +17441,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -17442,7 +17450,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -17451,7 +17459,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -17460,7 +17468,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -17469,7 +17477,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -17478,7 +17486,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -17487,10 +17495,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -17501,17 +17509,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -17520,7 +17528,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -17529,7 +17537,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -17538,7 +17546,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -17547,7 +17555,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -17556,7 +17564,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -17565,7 +17573,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -17574,7 +17582,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -17583,10 +17591,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -17594,17 +17602,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -17613,7 +17621,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -17622,7 +17630,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -17631,7 +17639,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -17640,7 +17648,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -17650,25 +17658,25 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -17677,7 +17685,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -17691,40 +17699,40 @@ public struct APISwift { } } } - + public final class CreateScalarContainerMutation: GraphQLMutation { public static let operationString = "mutation CreateScalarContainer($input: CreateScalarContainerInput!, $condition: ModelScalarContainerConditionInput) {\n createScalarContainer(input: $input, condition: $condition) {\n __typename\n id\n myString\n myInt\n myDouble\n myBool\n myDate\n myTime\n myDateTime\n myTimeStamp\n myEmail\n myJSON\n myPhone\n myURL\n myIPAddress\n createdAt\n updatedAt\n }\n}" - + public var input: CreateScalarContainerInput public var condition: ModelScalarContainerConditionInput? - + public init(input: CreateScalarContainerInput, condition: ModelScalarContainerConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createScalarContainer", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateScalarContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createScalarContainer: CreateScalarContainer? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createScalarContainer": createScalarContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createScalarContainer": createScalarContainer.flatMap(\.snapshot)]) } - + public var createScalarContainer: CreateScalarContainer? { get { return (snapshot["createScalarContainer"] as? Snapshot).flatMap { CreateScalarContainer(snapshot: $0) } @@ -17733,10 +17741,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createScalarContainer") } } - + public struct CreateScalarContainer: GraphQLSelectionSet { public static let possibleTypes = ["ScalarContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -17756,17 +17764,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, myString: String? = nil, myInt: Int? = nil, myDouble: Double? = nil, myBool: Bool? = nil, myDate: String? = nil, myTime: String? = nil, myDateTime: String? = nil, myTimeStamp: Int? = nil, myEmail: String? = nil, myJson: String? = nil, myPhone: String? = nil, myUrl: String? = nil, myIpAddress: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ScalarContainer", "id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -17775,7 +17783,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -17784,7 +17792,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var myString: String? { get { return snapshot["myString"] as? String @@ -17793,7 +17801,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myString") } } - + public var myInt: Int? { get { return snapshot["myInt"] as? Int @@ -17802,7 +17810,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myInt") } } - + public var myDouble: Double? { get { return snapshot["myDouble"] as? Double @@ -17811,7 +17819,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDouble") } } - + public var myBool: Bool? { get { return snapshot["myBool"] as? Bool @@ -17820,7 +17828,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myBool") } } - + public var myDate: String? { get { return snapshot["myDate"] as? String @@ -17829,7 +17837,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDate") } } - + public var myTime: String? { get { return snapshot["myTime"] as? String @@ -17838,7 +17846,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTime") } } - + public var myDateTime: String? { get { return snapshot["myDateTime"] as? String @@ -17847,7 +17855,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDateTime") } } - + public var myTimeStamp: Int? { get { return snapshot["myTimeStamp"] as? Int @@ -17856,7 +17864,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTimeStamp") } } - + public var myEmail: String? { get { return snapshot["myEmail"] as? String @@ -17865,7 +17873,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myEmail") } } - + public var myJson: String? { get { return snapshot["myJSON"] as? String @@ -17874,7 +17882,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myJSON") } } - + public var myPhone: String? { get { return snapshot["myPhone"] as? String @@ -17883,7 +17891,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myPhone") } } - + public var myUrl: String? { get { return snapshot["myURL"] as? String @@ -17892,7 +17900,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myURL") } } - + public var myIpAddress: String? { get { return snapshot["myIPAddress"] as? String @@ -17901,7 +17909,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myIPAddress") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -17910,7 +17918,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -17922,40 +17930,40 @@ public struct APISwift { } } } - + public final class UpdateScalarContainerMutation: GraphQLMutation { public static let operationString = "mutation UpdateScalarContainer($input: UpdateScalarContainerInput!, $condition: ModelScalarContainerConditionInput) {\n updateScalarContainer(input: $input, condition: $condition) {\n __typename\n id\n myString\n myInt\n myDouble\n myBool\n myDate\n myTime\n myDateTime\n myTimeStamp\n myEmail\n myJSON\n myPhone\n myURL\n myIPAddress\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateScalarContainerInput public var condition: ModelScalarContainerConditionInput? - + public init(input: UpdateScalarContainerInput, condition: ModelScalarContainerConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateScalarContainer", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateScalarContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateScalarContainer: UpdateScalarContainer? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateScalarContainer": updateScalarContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateScalarContainer": updateScalarContainer.flatMap(\.snapshot)]) } - + public var updateScalarContainer: UpdateScalarContainer? { get { return (snapshot["updateScalarContainer"] as? Snapshot).flatMap { UpdateScalarContainer(snapshot: $0) } @@ -17964,10 +17972,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateScalarContainer") } } - + public struct UpdateScalarContainer: GraphQLSelectionSet { public static let possibleTypes = ["ScalarContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -17987,17 +17995,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, myString: String? = nil, myInt: Int? = nil, myDouble: Double? = nil, myBool: Bool? = nil, myDate: String? = nil, myTime: String? = nil, myDateTime: String? = nil, myTimeStamp: Int? = nil, myEmail: String? = nil, myJson: String? = nil, myPhone: String? = nil, myUrl: String? = nil, myIpAddress: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ScalarContainer", "id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -18006,7 +18014,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -18015,7 +18023,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var myString: String? { get { return snapshot["myString"] as? String @@ -18024,7 +18032,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myString") } } - + public var myInt: Int? { get { return snapshot["myInt"] as? Int @@ -18033,7 +18041,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myInt") } } - + public var myDouble: Double? { get { return snapshot["myDouble"] as? Double @@ -18042,7 +18050,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDouble") } } - + public var myBool: Bool? { get { return snapshot["myBool"] as? Bool @@ -18051,7 +18059,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myBool") } } - + public var myDate: String? { get { return snapshot["myDate"] as? String @@ -18060,7 +18068,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDate") } } - + public var myTime: String? { get { return snapshot["myTime"] as? String @@ -18069,7 +18077,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTime") } } - + public var myDateTime: String? { get { return snapshot["myDateTime"] as? String @@ -18078,7 +18086,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDateTime") } } - + public var myTimeStamp: Int? { get { return snapshot["myTimeStamp"] as? Int @@ -18087,7 +18095,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTimeStamp") } } - + public var myEmail: String? { get { return snapshot["myEmail"] as? String @@ -18096,7 +18104,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myEmail") } } - + public var myJson: String? { get { return snapshot["myJSON"] as? String @@ -18105,7 +18113,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myJSON") } } - + public var myPhone: String? { get { return snapshot["myPhone"] as? String @@ -18114,7 +18122,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myPhone") } } - + public var myUrl: String? { get { return snapshot["myURL"] as? String @@ -18123,7 +18131,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myURL") } } - + public var myIpAddress: String? { get { return snapshot["myIPAddress"] as? String @@ -18132,7 +18140,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myIPAddress") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -18141,7 +18149,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -18153,40 +18161,40 @@ public struct APISwift { } } } - + public final class DeleteScalarContainerMutation: GraphQLMutation { public static let operationString = "mutation DeleteScalarContainer($input: DeleteScalarContainerInput!, $condition: ModelScalarContainerConditionInput) {\n deleteScalarContainer(input: $input, condition: $condition) {\n __typename\n id\n myString\n myInt\n myDouble\n myBool\n myDate\n myTime\n myDateTime\n myTimeStamp\n myEmail\n myJSON\n myPhone\n myURL\n myIPAddress\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteScalarContainerInput public var condition: ModelScalarContainerConditionInput? - + public init(input: DeleteScalarContainerInput, condition: ModelScalarContainerConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteScalarContainer", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteScalarContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteScalarContainer: DeleteScalarContainer? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteScalarContainer": deleteScalarContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteScalarContainer": deleteScalarContainer.flatMap(\.snapshot)]) } - + public var deleteScalarContainer: DeleteScalarContainer? { get { return (snapshot["deleteScalarContainer"] as? Snapshot).flatMap { DeleteScalarContainer(snapshot: $0) } @@ -18195,10 +18203,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteScalarContainer") } } - + public struct DeleteScalarContainer: GraphQLSelectionSet { public static let possibleTypes = ["ScalarContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -18218,17 +18226,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, myString: String? = nil, myInt: Int? = nil, myDouble: Double? = nil, myBool: Bool? = nil, myDate: String? = nil, myTime: String? = nil, myDateTime: String? = nil, myTimeStamp: Int? = nil, myEmail: String? = nil, myJson: String? = nil, myPhone: String? = nil, myUrl: String? = nil, myIpAddress: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ScalarContainer", "id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -18237,7 +18245,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -18246,7 +18254,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var myString: String? { get { return snapshot["myString"] as? String @@ -18255,7 +18263,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myString") } } - + public var myInt: Int? { get { return snapshot["myInt"] as? Int @@ -18264,7 +18272,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myInt") } } - + public var myDouble: Double? { get { return snapshot["myDouble"] as? Double @@ -18273,7 +18281,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDouble") } } - + public var myBool: Bool? { get { return snapshot["myBool"] as? Bool @@ -18282,7 +18290,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myBool") } } - + public var myDate: String? { get { return snapshot["myDate"] as? String @@ -18291,7 +18299,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDate") } } - + public var myTime: String? { get { return snapshot["myTime"] as? String @@ -18300,7 +18308,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTime") } } - + public var myDateTime: String? { get { return snapshot["myDateTime"] as? String @@ -18309,7 +18317,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDateTime") } } - + public var myTimeStamp: Int? { get { return snapshot["myTimeStamp"] as? Int @@ -18318,7 +18326,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTimeStamp") } } - + public var myEmail: String? { get { return snapshot["myEmail"] as? String @@ -18327,7 +18335,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myEmail") } } - + public var myJson: String? { get { return snapshot["myJSON"] as? String @@ -18336,7 +18344,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myJSON") } } - + public var myPhone: String? { get { return snapshot["myPhone"] as? String @@ -18345,7 +18353,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myPhone") } } - + public var myUrl: String? { get { return snapshot["myURL"] as? String @@ -18354,7 +18362,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myURL") } } - + public var myIpAddress: String? { get { return snapshot["myIPAddress"] as? String @@ -18363,7 +18371,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myIPAddress") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -18372,7 +18380,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -18384,40 +18392,40 @@ public struct APISwift { } } } - + public final class CreateListIntContainerMutation: GraphQLMutation { public static let operationString = "mutation CreateListIntContainer($input: CreateListIntContainerInput!, $condition: ModelListIntContainerConditionInput) {\n createListIntContainer(input: $input, condition: $condition) {\n __typename\n id\n test\n nullableInt\n intList\n intNullableList\n nullableIntList\n nullableIntNullableList\n createdAt\n updatedAt\n }\n}" - + public var input: CreateListIntContainerInput public var condition: ModelListIntContainerConditionInput? - + public init(input: CreateListIntContainerInput, condition: ModelListIntContainerConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createListIntContainer", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateListIntContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createListIntContainer: CreateListIntContainer? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createListIntContainer": createListIntContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createListIntContainer": createListIntContainer.flatMap(\.snapshot)]) } - + public var createListIntContainer: CreateListIntContainer? { get { return (snapshot["createListIntContainer"] as? Snapshot).flatMap { CreateListIntContainer(snapshot: $0) } @@ -18426,10 +18434,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createListIntContainer") } } - + public struct CreateListIntContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListIntContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -18442,17 +18450,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: Int, nullableInt: Int? = nil, intList: [Int], intNullableList: [Int]? = nil, nullableIntList: [Int?], nullableIntNullableList: [Int?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListIntContainer", "id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -18461,7 +18469,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -18470,7 +18478,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: Int { get { return snapshot["test"]! as! Int @@ -18479,7 +18487,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableInt: Int? { get { return snapshot["nullableInt"] as? Int @@ -18488,7 +18496,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableInt") } } - + public var intList: [Int] { get { return snapshot["intList"]! as! [Int] @@ -18497,7 +18505,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intList") } } - + public var intNullableList: [Int]? { get { return snapshot["intNullableList"] as? [Int] @@ -18506,7 +18514,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intNullableList") } } - + public var nullableIntList: [Int?] { get { return snapshot["nullableIntList"]! as! [Int?] @@ -18515,7 +18523,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntList") } } - + public var nullableIntNullableList: [Int?]? { get { return snapshot["nullableIntNullableList"] as? [Int?] @@ -18524,7 +18532,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -18533,7 +18541,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -18545,40 +18553,40 @@ public struct APISwift { } } } - + public final class UpdateListIntContainerMutation: GraphQLMutation { public static let operationString = "mutation UpdateListIntContainer($input: UpdateListIntContainerInput!, $condition: ModelListIntContainerConditionInput) {\n updateListIntContainer(input: $input, condition: $condition) {\n __typename\n id\n test\n nullableInt\n intList\n intNullableList\n nullableIntList\n nullableIntNullableList\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateListIntContainerInput public var condition: ModelListIntContainerConditionInput? - + public init(input: UpdateListIntContainerInput, condition: ModelListIntContainerConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateListIntContainer", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateListIntContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateListIntContainer: UpdateListIntContainer? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateListIntContainer": updateListIntContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateListIntContainer": updateListIntContainer.flatMap(\.snapshot)]) } - + public var updateListIntContainer: UpdateListIntContainer? { get { return (snapshot["updateListIntContainer"] as? Snapshot).flatMap { UpdateListIntContainer(snapshot: $0) } @@ -18587,10 +18595,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateListIntContainer") } } - + public struct UpdateListIntContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListIntContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -18603,17 +18611,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: Int, nullableInt: Int? = nil, intList: [Int], intNullableList: [Int]? = nil, nullableIntList: [Int?], nullableIntNullableList: [Int?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListIntContainer", "id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -18622,7 +18630,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -18631,7 +18639,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: Int { get { return snapshot["test"]! as! Int @@ -18640,7 +18648,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableInt: Int? { get { return snapshot["nullableInt"] as? Int @@ -18649,7 +18657,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableInt") } } - + public var intList: [Int] { get { return snapshot["intList"]! as! [Int] @@ -18658,7 +18666,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intList") } } - + public var intNullableList: [Int]? { get { return snapshot["intNullableList"] as? [Int] @@ -18667,7 +18675,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intNullableList") } } - + public var nullableIntList: [Int?] { get { return snapshot["nullableIntList"]! as! [Int?] @@ -18676,7 +18684,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntList") } } - + public var nullableIntNullableList: [Int?]? { get { return snapshot["nullableIntNullableList"] as? [Int?] @@ -18685,7 +18693,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -18694,7 +18702,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -18706,40 +18714,40 @@ public struct APISwift { } } } - + public final class DeleteListIntContainerMutation: GraphQLMutation { public static let operationString = "mutation DeleteListIntContainer($input: DeleteListIntContainerInput!, $condition: ModelListIntContainerConditionInput) {\n deleteListIntContainer(input: $input, condition: $condition) {\n __typename\n id\n test\n nullableInt\n intList\n intNullableList\n nullableIntList\n nullableIntNullableList\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteListIntContainerInput public var condition: ModelListIntContainerConditionInput? - + public init(input: DeleteListIntContainerInput, condition: ModelListIntContainerConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteListIntContainer", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteListIntContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteListIntContainer: DeleteListIntContainer? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteListIntContainer": deleteListIntContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteListIntContainer": deleteListIntContainer.flatMap(\.snapshot)]) } - + public var deleteListIntContainer: DeleteListIntContainer? { get { return (snapshot["deleteListIntContainer"] as? Snapshot).flatMap { DeleteListIntContainer(snapshot: $0) } @@ -18748,10 +18756,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteListIntContainer") } } - + public struct DeleteListIntContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListIntContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -18764,17 +18772,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: Int, nullableInt: Int? = nil, intList: [Int], intNullableList: [Int]? = nil, nullableIntList: [Int?], nullableIntNullableList: [Int?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListIntContainer", "id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -18783,7 +18791,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -18792,7 +18800,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: Int { get { return snapshot["test"]! as! Int @@ -18801,7 +18809,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableInt: Int? { get { return snapshot["nullableInt"] as? Int @@ -18810,7 +18818,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableInt") } } - + public var intList: [Int] { get { return snapshot["intList"]! as! [Int] @@ -18819,7 +18827,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intList") } } - + public var intNullableList: [Int]? { get { return snapshot["intNullableList"] as? [Int] @@ -18828,7 +18836,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intNullableList") } } - + public var nullableIntList: [Int?] { get { return snapshot["nullableIntList"]! as! [Int?] @@ -18837,7 +18845,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntList") } } - + public var nullableIntNullableList: [Int?]? { get { return snapshot["nullableIntNullableList"] as? [Int?] @@ -18846,7 +18854,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -18855,7 +18863,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -18867,40 +18875,40 @@ public struct APISwift { } } } - + public final class CreateListStringContainerMutation: GraphQLMutation { public static let operationString = "mutation CreateListStringContainer($input: CreateListStringContainerInput!, $condition: ModelListStringContainerConditionInput) {\n createListStringContainer(input: $input, condition: $condition) {\n __typename\n id\n test\n nullableString\n stringList\n stringNullableList\n nullableStringList\n nullableStringNullableList\n createdAt\n updatedAt\n }\n}" - + public var input: CreateListStringContainerInput public var condition: ModelListStringContainerConditionInput? - + public init(input: CreateListStringContainerInput, condition: ModelListStringContainerConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createListStringContainer", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateListStringContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createListStringContainer: CreateListStringContainer? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createListStringContainer": createListStringContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createListStringContainer": createListStringContainer.flatMap(\.snapshot)]) } - + public var createListStringContainer: CreateListStringContainer? { get { return (snapshot["createListStringContainer"] as? Snapshot).flatMap { CreateListStringContainer(snapshot: $0) } @@ -18909,10 +18917,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createListStringContainer") } } - + public struct CreateListStringContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListStringContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -18925,17 +18933,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: String, nullableString: String? = nil, stringList: [String], stringNullableList: [String]? = nil, nullableStringList: [String?], nullableStringNullableList: [String?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListStringContainer", "id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -18944,7 +18952,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -18953,7 +18961,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: String { get { return snapshot["test"]! as! String @@ -18962,7 +18970,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableString: String? { get { return snapshot["nullableString"] as? String @@ -18971,7 +18979,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableString") } } - + public var stringList: [String] { get { return snapshot["stringList"]! as! [String] @@ -18980,7 +18988,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringList") } } - + public var stringNullableList: [String]? { get { return snapshot["stringNullableList"] as? [String] @@ -18989,7 +18997,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringNullableList") } } - + public var nullableStringList: [String?] { get { return snapshot["nullableStringList"]! as! [String?] @@ -18998,7 +19006,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringList") } } - + public var nullableStringNullableList: [String?]? { get { return snapshot["nullableStringNullableList"] as? [String?] @@ -19007,7 +19015,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -19016,7 +19024,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -19028,40 +19036,40 @@ public struct APISwift { } } } - + public final class UpdateListStringContainerMutation: GraphQLMutation { public static let operationString = "mutation UpdateListStringContainer($input: UpdateListStringContainerInput!, $condition: ModelListStringContainerConditionInput) {\n updateListStringContainer(input: $input, condition: $condition) {\n __typename\n id\n test\n nullableString\n stringList\n stringNullableList\n nullableStringList\n nullableStringNullableList\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateListStringContainerInput public var condition: ModelListStringContainerConditionInput? - + public init(input: UpdateListStringContainerInput, condition: ModelListStringContainerConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateListStringContainer", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateListStringContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateListStringContainer: UpdateListStringContainer? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateListStringContainer": updateListStringContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateListStringContainer": updateListStringContainer.flatMap(\.snapshot)]) } - + public var updateListStringContainer: UpdateListStringContainer? { get { return (snapshot["updateListStringContainer"] as? Snapshot).flatMap { UpdateListStringContainer(snapshot: $0) } @@ -19070,10 +19078,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateListStringContainer") } } - + public struct UpdateListStringContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListStringContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -19086,17 +19094,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: String, nullableString: String? = nil, stringList: [String], stringNullableList: [String]? = nil, nullableStringList: [String?], nullableStringNullableList: [String?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListStringContainer", "id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -19105,7 +19113,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -19114,7 +19122,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: String { get { return snapshot["test"]! as! String @@ -19123,7 +19131,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableString: String? { get { return snapshot["nullableString"] as? String @@ -19132,7 +19140,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableString") } } - + public var stringList: [String] { get { return snapshot["stringList"]! as! [String] @@ -19141,7 +19149,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringList") } } - + public var stringNullableList: [String]? { get { return snapshot["stringNullableList"] as? [String] @@ -19150,7 +19158,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringNullableList") } } - + public var nullableStringList: [String?] { get { return snapshot["nullableStringList"]! as! [String?] @@ -19159,7 +19167,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringList") } } - + public var nullableStringNullableList: [String?]? { get { return snapshot["nullableStringNullableList"] as? [String?] @@ -19168,7 +19176,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -19177,7 +19185,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -19189,40 +19197,40 @@ public struct APISwift { } } } - + public final class DeleteListStringContainerMutation: GraphQLMutation { public static let operationString = "mutation DeleteListStringContainer($input: DeleteListStringContainerInput!, $condition: ModelListStringContainerConditionInput) {\n deleteListStringContainer(input: $input, condition: $condition) {\n __typename\n id\n test\n nullableString\n stringList\n stringNullableList\n nullableStringList\n nullableStringNullableList\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteListStringContainerInput public var condition: ModelListStringContainerConditionInput? - + public init(input: DeleteListStringContainerInput, condition: ModelListStringContainerConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteListStringContainer", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteListStringContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteListStringContainer: DeleteListStringContainer? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteListStringContainer": deleteListStringContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteListStringContainer": deleteListStringContainer.flatMap(\.snapshot)]) } - + public var deleteListStringContainer: DeleteListStringContainer? { get { return (snapshot["deleteListStringContainer"] as? Snapshot).flatMap { DeleteListStringContainer(snapshot: $0) } @@ -19231,10 +19239,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteListStringContainer") } } - + public struct DeleteListStringContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListStringContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -19247,17 +19255,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: String, nullableString: String? = nil, stringList: [String], stringNullableList: [String]? = nil, nullableStringList: [String?], nullableStringNullableList: [String?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListStringContainer", "id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -19266,7 +19274,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -19275,7 +19283,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: String { get { return snapshot["test"]! as! String @@ -19284,7 +19292,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableString: String? { get { return snapshot["nullableString"] as? String @@ -19293,7 +19301,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableString") } } - + public var stringList: [String] { get { return snapshot["stringList"]! as! [String] @@ -19302,7 +19310,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringList") } } - + public var stringNullableList: [String]? { get { return snapshot["stringNullableList"] as? [String] @@ -19311,7 +19319,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringNullableList") } } - + public var nullableStringList: [String?] { get { return snapshot["nullableStringList"]! as! [String?] @@ -19320,7 +19328,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringList") } } - + public var nullableStringNullableList: [String?]? { get { return snapshot["nullableStringNullableList"] as? [String?] @@ -19329,7 +19337,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -19338,7 +19346,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -19350,40 +19358,40 @@ public struct APISwift { } } } - + public final class CreateEnumTestModelMutation: GraphQLMutation { public static let operationString = "mutation CreateEnumTestModel($input: CreateEnumTestModelInput!, $condition: ModelEnumTestModelConditionInput) {\n createEnumTestModel(input: $input, condition: $condition) {\n __typename\n id\n enumVal\n nullableEnumVal\n enumList\n enumNullableList\n nullableEnumList\n nullableEnumNullableList\n createdAt\n updatedAt\n }\n}" - + public var input: CreateEnumTestModelInput public var condition: ModelEnumTestModelConditionInput? - + public init(input: CreateEnumTestModelInput, condition: ModelEnumTestModelConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createEnumTestModel", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateEnumTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createEnumTestModel: CreateEnumTestModel? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createEnumTestModel": createEnumTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createEnumTestModel": createEnumTestModel.flatMap(\.snapshot)]) } - + public var createEnumTestModel: CreateEnumTestModel? { get { return (snapshot["createEnumTestModel"] as? Snapshot).flatMap { CreateEnumTestModel(snapshot: $0) } @@ -19392,10 +19400,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createEnumTestModel") } } - + public struct CreateEnumTestModel: GraphQLSelectionSet { public static let possibleTypes = ["EnumTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -19408,17 +19416,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, enumVal: TestEnum, nullableEnumVal: TestEnum? = nil, enumList: [TestEnum], enumNullableList: [TestEnum]? = nil, nullableEnumList: [TestEnum?], nullableEnumNullableList: [TestEnum?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "EnumTestModel", "id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -19427,7 +19435,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -19436,7 +19444,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var enumVal: TestEnum { get { return snapshot["enumVal"]! as! TestEnum @@ -19445,7 +19453,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumVal") } } - + public var nullableEnumVal: TestEnum? { get { return snapshot["nullableEnumVal"] as? TestEnum @@ -19454,7 +19462,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumVal") } } - + public var enumList: [TestEnum] { get { return snapshot["enumList"]! as! [TestEnum] @@ -19463,7 +19471,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumList") } } - + public var enumNullableList: [TestEnum]? { get { return snapshot["enumNullableList"] as? [TestEnum] @@ -19472,7 +19480,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumNullableList") } } - + public var nullableEnumList: [TestEnum?] { get { return snapshot["nullableEnumList"]! as! [TestEnum?] @@ -19481,7 +19489,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumList") } } - + public var nullableEnumNullableList: [TestEnum?]? { get { return snapshot["nullableEnumNullableList"] as? [TestEnum?] @@ -19490,7 +19498,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -19499,7 +19507,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -19511,40 +19519,40 @@ public struct APISwift { } } } - + public final class UpdateEnumTestModelMutation: GraphQLMutation { public static let operationString = "mutation UpdateEnumTestModel($input: UpdateEnumTestModelInput!, $condition: ModelEnumTestModelConditionInput) {\n updateEnumTestModel(input: $input, condition: $condition) {\n __typename\n id\n enumVal\n nullableEnumVal\n enumList\n enumNullableList\n nullableEnumList\n nullableEnumNullableList\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateEnumTestModelInput public var condition: ModelEnumTestModelConditionInput? - + public init(input: UpdateEnumTestModelInput, condition: ModelEnumTestModelConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateEnumTestModel", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateEnumTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateEnumTestModel: UpdateEnumTestModel? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateEnumTestModel": updateEnumTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateEnumTestModel": updateEnumTestModel.flatMap(\.snapshot)]) } - + public var updateEnumTestModel: UpdateEnumTestModel? { get { return (snapshot["updateEnumTestModel"] as? Snapshot).flatMap { UpdateEnumTestModel(snapshot: $0) } @@ -19553,10 +19561,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateEnumTestModel") } } - + public struct UpdateEnumTestModel: GraphQLSelectionSet { public static let possibleTypes = ["EnumTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -19569,17 +19577,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, enumVal: TestEnum, nullableEnumVal: TestEnum? = nil, enumList: [TestEnum], enumNullableList: [TestEnum]? = nil, nullableEnumList: [TestEnum?], nullableEnumNullableList: [TestEnum?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "EnumTestModel", "id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -19588,7 +19596,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -19597,7 +19605,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var enumVal: TestEnum { get { return snapshot["enumVal"]! as! TestEnum @@ -19606,7 +19614,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumVal") } } - + public var nullableEnumVal: TestEnum? { get { return snapshot["nullableEnumVal"] as? TestEnum @@ -19615,7 +19623,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumVal") } } - + public var enumList: [TestEnum] { get { return snapshot["enumList"]! as! [TestEnum] @@ -19624,7 +19632,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumList") } } - + public var enumNullableList: [TestEnum]? { get { return snapshot["enumNullableList"] as? [TestEnum] @@ -19633,7 +19641,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumNullableList") } } - + public var nullableEnumList: [TestEnum?] { get { return snapshot["nullableEnumList"]! as! [TestEnum?] @@ -19642,7 +19650,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumList") } } - + public var nullableEnumNullableList: [TestEnum?]? { get { return snapshot["nullableEnumNullableList"] as? [TestEnum?] @@ -19651,7 +19659,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -19660,7 +19668,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -19672,40 +19680,40 @@ public struct APISwift { } } } - + public final class DeleteEnumTestModelMutation: GraphQLMutation { public static let operationString = "mutation DeleteEnumTestModel($input: DeleteEnumTestModelInput!, $condition: ModelEnumTestModelConditionInput) {\n deleteEnumTestModel(input: $input, condition: $condition) {\n __typename\n id\n enumVal\n nullableEnumVal\n enumList\n enumNullableList\n nullableEnumList\n nullableEnumNullableList\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteEnumTestModelInput public var condition: ModelEnumTestModelConditionInput? - + public init(input: DeleteEnumTestModelInput, condition: ModelEnumTestModelConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteEnumTestModel", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteEnumTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteEnumTestModel: DeleteEnumTestModel? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteEnumTestModel": deleteEnumTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteEnumTestModel": deleteEnumTestModel.flatMap(\.snapshot)]) } - + public var deleteEnumTestModel: DeleteEnumTestModel? { get { return (snapshot["deleteEnumTestModel"] as? Snapshot).flatMap { DeleteEnumTestModel(snapshot: $0) } @@ -19714,10 +19722,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteEnumTestModel") } } - + public struct DeleteEnumTestModel: GraphQLSelectionSet { public static let possibleTypes = ["EnumTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -19730,17 +19738,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, enumVal: TestEnum, nullableEnumVal: TestEnum? = nil, enumList: [TestEnum], enumNullableList: [TestEnum]? = nil, nullableEnumList: [TestEnum?], nullableEnumNullableList: [TestEnum?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "EnumTestModel", "id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -19749,7 +19757,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -19758,7 +19766,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var enumVal: TestEnum { get { return snapshot["enumVal"]! as! TestEnum @@ -19767,7 +19775,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumVal") } } - + public var nullableEnumVal: TestEnum? { get { return snapshot["nullableEnumVal"] as? TestEnum @@ -19776,7 +19784,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumVal") } } - + public var enumList: [TestEnum] { get { return snapshot["enumList"]! as! [TestEnum] @@ -19785,7 +19793,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumList") } } - + public var enumNullableList: [TestEnum]? { get { return snapshot["enumNullableList"] as? [TestEnum] @@ -19794,7 +19802,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumNullableList") } } - + public var nullableEnumList: [TestEnum?] { get { return snapshot["nullableEnumList"]! as! [TestEnum?] @@ -19803,7 +19811,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumList") } } - + public var nullableEnumNullableList: [TestEnum?]? { get { return snapshot["nullableEnumNullableList"] as? [TestEnum?] @@ -19812,7 +19820,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -19821,7 +19829,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -19833,40 +19841,40 @@ public struct APISwift { } } } - + public final class CreateNestedTypeTestModelMutation: GraphQLMutation { public static let operationString = "mutation CreateNestedTypeTestModel($input: CreateNestedTypeTestModelInput!, $condition: ModelNestedTypeTestModelConditionInput) {\n createNestedTypeTestModel(input: $input, condition: $condition) {\n __typename\n id\n nestedVal {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedVal {\n __typename\n valueOne\n valueTwo\n }\n nestedList {\n __typename\n valueOne\n valueTwo\n }\n nestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n createdAt\n updatedAt\n }\n}" - + public var input: CreateNestedTypeTestModelInput public var condition: ModelNestedTypeTestModelConditionInput? - + public init(input: CreateNestedTypeTestModelInput, condition: ModelNestedTypeTestModelConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createNestedTypeTestModel", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateNestedTypeTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createNestedTypeTestModel: CreateNestedTypeTestModel? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createNestedTypeTestModel": createNestedTypeTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createNestedTypeTestModel": createNestedTypeTestModel.flatMap(\.snapshot)]) } - + public var createNestedTypeTestModel: CreateNestedTypeTestModel? { get { return (snapshot["createNestedTypeTestModel"] as? Snapshot).flatMap { CreateNestedTypeTestModel(snapshot: $0) } @@ -19875,10 +19883,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createNestedTypeTestModel") } } - + public struct CreateNestedTypeTestModel: GraphQLSelectionSet { public static let possibleTypes = ["NestedTypeTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -19891,17 +19899,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, nestedVal: NestedVal, nullableNestedVal: NullableNestedVal? = nil, nestedList: [NestedList], nestedNullableList: [NestedNullableList]? = nil, nullableNestedList: [NullableNestedList?], nullableNestedNullableList: [NullableNestedNullableList?]? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap { $0.snapshot }, "nestedList": nestedList.map { $0.snapshot }, "nestedNullableList": nestedNullableList.flatMap { $0.map { $0.snapshot } }, "nullableNestedList": nullableNestedList.map { $0.flatMap { $0.snapshot } }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap(\.snapshot), "nestedList": nestedList.map(\.snapshot), "nestedNullableList": nestedNullableList.flatMap { $0.map(\.snapshot) }, "nullableNestedList": nullableNestedList.map { $0.flatMap(\.snapshot) }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap(\.snapshot) } }, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -19910,7 +19918,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -19919,7 +19927,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var nestedVal: NestedVal { get { return NestedVal(snapshot: snapshot["nestedVal"]! as! Snapshot) @@ -19928,7 +19936,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "nestedVal") } } - + public var nullableNestedVal: NullableNestedVal? { get { return (snapshot["nullableNestedVal"] as? Snapshot).flatMap { NullableNestedVal(snapshot: $0) } @@ -19937,43 +19945,43 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "nullableNestedVal") } } - + public var nestedList: [NestedList] { get { return (snapshot["nestedList"] as! [Snapshot]).map { NestedList(snapshot: $0) } } set { - snapshot.updateValue(newValue.map { $0.snapshot }, forKey: "nestedList") + snapshot.updateValue(newValue.map(\.snapshot), forKey: "nestedList") } } - + public var nestedNullableList: [NestedNullableList]? { get { return (snapshot["nestedNullableList"] as? [Snapshot]).flatMap { $0.map { NestedNullableList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.snapshot } }, forKey: "nestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map(\.snapshot) }, forKey: "nestedNullableList") } } - + public var nullableNestedList: [NullableNestedList?] { get { return (snapshot["nullableNestedList"] as! [Snapshot?]).map { $0.flatMap { NullableNestedList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "nullableNestedList") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "nullableNestedList") } } - + public var nullableNestedNullableList: [NullableNestedNullableList?]? { get { return (snapshot["nullableNestedNullableList"] as? [Snapshot?]).flatMap { $0.map { $0.flatMap { NullableNestedNullableList(snapshot: $0) } } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, forKey: "nullableNestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap(\.snapshot) } }, forKey: "nullableNestedNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -19982,7 +19990,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -19991,26 +19999,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct NestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20019,7 +20027,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20028,7 +20036,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20038,26 +20046,26 @@ public struct APISwift { } } } - + public struct NullableNestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20066,7 +20074,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20075,7 +20083,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20085,26 +20093,26 @@ public struct APISwift { } } } - + public struct NestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20113,7 +20121,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20122,7 +20130,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20132,26 +20140,26 @@ public struct APISwift { } } } - + public struct NestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20160,7 +20168,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20169,7 +20177,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20179,26 +20187,26 @@ public struct APISwift { } } } - + public struct NullableNestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20207,7 +20215,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20216,7 +20224,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20226,26 +20234,26 @@ public struct APISwift { } } } - + public struct NullableNestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20254,7 +20262,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20263,7 +20271,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20276,40 +20284,40 @@ public struct APISwift { } } } - + public final class UpdateNestedTypeTestModelMutation: GraphQLMutation { public static let operationString = "mutation UpdateNestedTypeTestModel($input: UpdateNestedTypeTestModelInput!, $condition: ModelNestedTypeTestModelConditionInput) {\n updateNestedTypeTestModel(input: $input, condition: $condition) {\n __typename\n id\n nestedVal {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedVal {\n __typename\n valueOne\n valueTwo\n }\n nestedList {\n __typename\n valueOne\n valueTwo\n }\n nestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateNestedTypeTestModelInput public var condition: ModelNestedTypeTestModelConditionInput? - + public init(input: UpdateNestedTypeTestModelInput, condition: ModelNestedTypeTestModelConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateNestedTypeTestModel", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateNestedTypeTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateNestedTypeTestModel: UpdateNestedTypeTestModel? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateNestedTypeTestModel": updateNestedTypeTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateNestedTypeTestModel": updateNestedTypeTestModel.flatMap(\.snapshot)]) } - + public var updateNestedTypeTestModel: UpdateNestedTypeTestModel? { get { return (snapshot["updateNestedTypeTestModel"] as? Snapshot).flatMap { UpdateNestedTypeTestModel(snapshot: $0) } @@ -20318,10 +20326,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateNestedTypeTestModel") } } - + public struct UpdateNestedTypeTestModel: GraphQLSelectionSet { public static let possibleTypes = ["NestedTypeTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -20334,17 +20342,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, nestedVal: NestedVal, nullableNestedVal: NullableNestedVal? = nil, nestedList: [NestedList], nestedNullableList: [NestedNullableList]? = nil, nullableNestedList: [NullableNestedList?], nullableNestedNullableList: [NullableNestedNullableList?]? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap { $0.snapshot }, "nestedList": nestedList.map { $0.snapshot }, "nestedNullableList": nestedNullableList.flatMap { $0.map { $0.snapshot } }, "nullableNestedList": nullableNestedList.map { $0.flatMap { $0.snapshot } }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap(\.snapshot), "nestedList": nestedList.map(\.snapshot), "nestedNullableList": nestedNullableList.flatMap { $0.map(\.snapshot) }, "nullableNestedList": nullableNestedList.map { $0.flatMap(\.snapshot) }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap(\.snapshot) } }, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20353,7 +20361,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -20362,7 +20370,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var nestedVal: NestedVal { get { return NestedVal(snapshot: snapshot["nestedVal"]! as! Snapshot) @@ -20371,7 +20379,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "nestedVal") } } - + public var nullableNestedVal: NullableNestedVal? { get { return (snapshot["nullableNestedVal"] as? Snapshot).flatMap { NullableNestedVal(snapshot: $0) } @@ -20380,43 +20388,43 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "nullableNestedVal") } } - + public var nestedList: [NestedList] { get { return (snapshot["nestedList"] as! [Snapshot]).map { NestedList(snapshot: $0) } } set { - snapshot.updateValue(newValue.map { $0.snapshot }, forKey: "nestedList") + snapshot.updateValue(newValue.map(\.snapshot), forKey: "nestedList") } } - + public var nestedNullableList: [NestedNullableList]? { get { return (snapshot["nestedNullableList"] as? [Snapshot]).flatMap { $0.map { NestedNullableList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.snapshot } }, forKey: "nestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map(\.snapshot) }, forKey: "nestedNullableList") } } - + public var nullableNestedList: [NullableNestedList?] { get { return (snapshot["nullableNestedList"] as! [Snapshot?]).map { $0.flatMap { NullableNestedList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "nullableNestedList") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "nullableNestedList") } } - + public var nullableNestedNullableList: [NullableNestedNullableList?]? { get { return (snapshot["nullableNestedNullableList"] as? [Snapshot?]).flatMap { $0.map { $0.flatMap { NullableNestedNullableList(snapshot: $0) } } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, forKey: "nullableNestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap(\.snapshot) } }, forKey: "nullableNestedNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -20425,7 +20433,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -20434,26 +20442,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct NestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20462,7 +20470,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20471,7 +20479,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20481,26 +20489,26 @@ public struct APISwift { } } } - + public struct NullableNestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20509,7 +20517,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20518,7 +20526,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20528,26 +20536,26 @@ public struct APISwift { } } } - + public struct NestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20556,7 +20564,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20565,7 +20573,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20575,26 +20583,26 @@ public struct APISwift { } } } - + public struct NestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20603,7 +20611,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20612,7 +20620,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20622,26 +20630,26 @@ public struct APISwift { } } } - + public struct NullableNestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20650,7 +20658,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20659,7 +20667,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20669,26 +20677,26 @@ public struct APISwift { } } } - + public struct NullableNestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20697,7 +20705,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20706,7 +20714,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20719,40 +20727,40 @@ public struct APISwift { } } } - + public final class DeleteNestedTypeTestModelMutation: GraphQLMutation { public static let operationString = "mutation DeleteNestedTypeTestModel($input: DeleteNestedTypeTestModelInput!, $condition: ModelNestedTypeTestModelConditionInput) {\n deleteNestedTypeTestModel(input: $input, condition: $condition) {\n __typename\n id\n nestedVal {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedVal {\n __typename\n valueOne\n valueTwo\n }\n nestedList {\n __typename\n valueOne\n valueTwo\n }\n nestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteNestedTypeTestModelInput public var condition: ModelNestedTypeTestModelConditionInput? - + public init(input: DeleteNestedTypeTestModelInput, condition: ModelNestedTypeTestModelConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteNestedTypeTestModel", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteNestedTypeTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteNestedTypeTestModel: DeleteNestedTypeTestModel? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteNestedTypeTestModel": deleteNestedTypeTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteNestedTypeTestModel": deleteNestedTypeTestModel.flatMap(\.snapshot)]) } - + public var deleteNestedTypeTestModel: DeleteNestedTypeTestModel? { get { return (snapshot["deleteNestedTypeTestModel"] as? Snapshot).flatMap { DeleteNestedTypeTestModel(snapshot: $0) } @@ -20761,10 +20769,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteNestedTypeTestModel") } } - + public struct DeleteNestedTypeTestModel: GraphQLSelectionSet { public static let possibleTypes = ["NestedTypeTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -20777,17 +20785,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, nestedVal: NestedVal, nullableNestedVal: NullableNestedVal? = nil, nestedList: [NestedList], nestedNullableList: [NestedNullableList]? = nil, nullableNestedList: [NullableNestedList?], nullableNestedNullableList: [NullableNestedNullableList?]? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap { $0.snapshot }, "nestedList": nestedList.map { $0.snapshot }, "nestedNullableList": nestedNullableList.flatMap { $0.map { $0.snapshot } }, "nullableNestedList": nullableNestedList.map { $0.flatMap { $0.snapshot } }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap(\.snapshot), "nestedList": nestedList.map(\.snapshot), "nestedNullableList": nestedNullableList.flatMap { $0.map(\.snapshot) }, "nullableNestedList": nullableNestedList.map { $0.flatMap(\.snapshot) }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap(\.snapshot) } }, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20796,7 +20804,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -20805,7 +20813,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var nestedVal: NestedVal { get { return NestedVal(snapshot: snapshot["nestedVal"]! as! Snapshot) @@ -20814,7 +20822,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "nestedVal") } } - + public var nullableNestedVal: NullableNestedVal? { get { return (snapshot["nullableNestedVal"] as? Snapshot).flatMap { NullableNestedVal(snapshot: $0) } @@ -20823,43 +20831,43 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "nullableNestedVal") } } - + public var nestedList: [NestedList] { get { return (snapshot["nestedList"] as! [Snapshot]).map { NestedList(snapshot: $0) } } set { - snapshot.updateValue(newValue.map { $0.snapshot }, forKey: "nestedList") + snapshot.updateValue(newValue.map(\.snapshot), forKey: "nestedList") } } - + public var nestedNullableList: [NestedNullableList]? { get { return (snapshot["nestedNullableList"] as? [Snapshot]).flatMap { $0.map { NestedNullableList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.snapshot } }, forKey: "nestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map(\.snapshot) }, forKey: "nestedNullableList") } } - + public var nullableNestedList: [NullableNestedList?] { get { return (snapshot["nullableNestedList"] as! [Snapshot?]).map { $0.flatMap { NullableNestedList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "nullableNestedList") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "nullableNestedList") } } - + public var nullableNestedNullableList: [NullableNestedNullableList?]? { get { return (snapshot["nullableNestedNullableList"] as? [Snapshot?]).flatMap { $0.map { $0.flatMap { NullableNestedNullableList(snapshot: $0) } } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, forKey: "nullableNestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap(\.snapshot) } }, forKey: "nullableNestedNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -20868,7 +20876,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -20877,26 +20885,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct NestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20905,7 +20913,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20914,7 +20922,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20924,26 +20932,26 @@ public struct APISwift { } } } - + public struct NullableNestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20952,7 +20960,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -20961,7 +20969,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -20971,26 +20979,26 @@ public struct APISwift { } } } - + public struct NestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -20999,7 +21007,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -21008,7 +21016,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -21018,26 +21026,26 @@ public struct APISwift { } } } - + public struct NestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -21046,7 +21054,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -21055,7 +21063,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -21065,26 +21073,26 @@ public struct APISwift { } } } - + public struct NullableNestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -21093,7 +21101,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -21102,7 +21110,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -21112,26 +21120,26 @@ public struct APISwift { } } } - + public struct NullableNestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -21140,7 +21148,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -21149,7 +21157,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -21162,38 +21170,38 @@ public struct APISwift { } } } - + public final class GetPostQuery: GraphQLQuery { public static let operationString = "query GetPost($id: ID!) {\n getPost(id: $id) {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n items {\n __typename\n id\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getPost", arguments: ["id": GraphQLVariable("id")], type: .object(GetPost.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getPost: GetPost? = nil) { - self.init(snapshot: ["__typename": "Query", "getPost": getPost.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getPost": getPost.flatMap(\.snapshot)]) } - + public var getPost: GetPost? { get { return (snapshot["getPost"] as? Snapshot).flatMap { GetPost(snapshot: $0) } @@ -21202,10 +21210,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getPost") } } - + public struct GetPost: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -21218,17 +21226,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -21237,7 +21245,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -21246,7 +21254,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -21255,7 +21263,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -21264,7 +21272,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -21273,7 +21281,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -21282,7 +21290,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -21291,7 +21299,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -21300,7 +21308,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -21309,7 +21317,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -21318,26 +21326,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -21346,16 +21354,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -21364,10 +21372,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -21375,17 +21383,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -21394,7 +21402,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -21403,7 +21411,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -21412,7 +21420,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -21421,7 +21429,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -21435,42 +21443,42 @@ public struct APISwift { } } } - + public final class ListPostsQuery: GraphQLQuery { public static let operationString = "query ListPosts($filter: ModelPostFilterInput, $limit: Int, $nextToken: String) {\n listPosts(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n nextToken\n }\n }\n nextToken\n }\n}" - + public var filter: ModelPostFilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelPostFilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listPosts", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListPost.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listPosts: ListPost? = nil) { - self.init(snapshot: ["__typename": "Query", "listPosts": listPosts.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listPosts": listPosts.flatMap(\.snapshot)]) } - + public var listPosts: ListPost? { get { return (snapshot["listPosts"] as? Snapshot).flatMap { ListPost(snapshot: $0) } @@ -21479,26 +21487,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listPosts") } } - + public struct ListPost: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -21507,16 +21515,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -21525,10 +21533,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -21541,17 +21549,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -21560,7 +21568,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -21569,7 +21577,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -21578,7 +21586,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -21587,7 +21595,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -21596,7 +21604,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -21605,7 +21613,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -21614,7 +21622,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -21623,7 +21631,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -21632,7 +21640,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -21641,25 +21649,25 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelCommentConnection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -21668,7 +21676,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -21682,38 +21690,38 @@ public struct APISwift { } } } - + public final class GetCommentQuery: GraphQLQuery { public static let operationString = "query GetComment($id: ID!) {\n getComment(id: $id) {\n __typename\n id\n content\n createdAt\n post {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n nextToken\n }\n }\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getComment", arguments: ["id": GraphQLVariable("id")], type: .object(GetComment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getComment: GetComment? = nil) { - self.init(snapshot: ["__typename": "Query", "getComment": getComment.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getComment": getComment.flatMap(\.snapshot)]) } - + public var getComment: GetComment? { get { return (snapshot["getComment"] as? Snapshot).flatMap { GetComment(snapshot: $0) } @@ -21722,10 +21730,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getComment") } } - + public struct GetComment: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -21734,17 +21742,17 @@ public struct APISwift { GraphQLField("post", type: .object(Post.selections)), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, post: Post? = nil, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap { $0.snapshot }, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap(\.snapshot), "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -21753,7 +21761,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -21762,7 +21770,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -21771,7 +21779,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -21780,7 +21788,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -21789,7 +21797,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -21798,10 +21806,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -21814,17 +21822,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -21833,7 +21841,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -21842,7 +21850,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -21851,7 +21859,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -21860,7 +21868,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -21869,7 +21877,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -21878,7 +21886,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -21887,7 +21895,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -21896,7 +21904,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -21905,7 +21913,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -21914,25 +21922,25 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelCommentConnection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -21941,7 +21949,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -21955,42 +21963,42 @@ public struct APISwift { } } } - + public final class ListCommentsQuery: GraphQLQuery { public static let operationString = "query ListComments($filter: ModelCommentFilterInput, $limit: Int, $nextToken: String) {\n listComments(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n content\n createdAt\n post {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n }\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelCommentFilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelCommentFilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listComments", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListComment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listComments: ListComment? = nil) { - self.init(snapshot: ["__typename": "Query", "listComments": listComments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listComments": listComments.flatMap(\.snapshot)]) } - + public var listComments: ListComment? { get { return (snapshot["listComments"] as? Snapshot).flatMap { ListComment(snapshot: $0) } @@ -21999,26 +22007,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listComments") } } - + public struct ListComment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -22027,16 +22035,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -22045,10 +22053,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -22057,17 +22065,17 @@ public struct APISwift { GraphQLField("post", type: .object(Post.selections)), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, post: Post? = nil, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap { $0.snapshot }, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap(\.snapshot), "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -22076,7 +22084,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -22085,7 +22093,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -22094,7 +22102,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -22103,7 +22111,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -22112,7 +22120,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -22121,10 +22129,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -22136,17 +22144,17 @@ public struct APISwift { GraphQLField("rating", type: .scalar(Double.self)), GraphQLField("status", type: .scalar(PostStatus.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil) { self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -22155,7 +22163,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -22164,7 +22172,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -22173,7 +22181,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -22182,7 +22190,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -22191,7 +22199,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -22200,7 +22208,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -22209,7 +22217,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -22218,7 +22226,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -22232,38 +22240,38 @@ public struct APISwift { } } } - + public final class GetProject1Query: GraphQLQuery { public static let operationString = "query GetProject1($id: ID!) {\n getProject1(id: $id) {\n __typename\n id\n name\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getProject1", arguments: ["id": GraphQLVariable("id")], type: .object(GetProject1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getProject1: GetProject1? = nil) { - self.init(snapshot: ["__typename": "Query", "getProject1": getProject1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getProject1": getProject1.flatMap(\.snapshot)]) } - + public var getProject1: GetProject1? { get { return (snapshot["getProject1"] as? Snapshot).flatMap { GetProject1(snapshot: $0) } @@ -22272,10 +22280,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getProject1") } } - + public struct GetProject1: GraphQLSelectionSet { public static let possibleTypes = ["Project1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -22284,17 +22292,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -22303,7 +22311,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -22312,7 +22320,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -22321,7 +22329,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -22330,7 +22338,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -22339,7 +22347,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -22348,10 +22356,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -22359,17 +22367,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -22378,7 +22386,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -22387,7 +22395,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -22396,7 +22404,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -22405,7 +22413,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -22418,42 +22426,42 @@ public struct APISwift { } } } - + public final class ListProject1sQuery: GraphQLQuery { public static let operationString = "query ListProject1s($filter: ModelProject1FilterInput, $limit: Int, $nextToken: String) {\n listProject1s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n name\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelProject1FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelProject1FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listProject1s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListProject1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listProject1s: ListProject1? = nil) { - self.init(snapshot: ["__typename": "Query", "listProject1s": listProject1s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listProject1s": listProject1s.flatMap(\.snapshot)]) } - + public var listProject1s: ListProject1? { get { return (snapshot["listProject1s"] as? Snapshot).flatMap { ListProject1(snapshot: $0) } @@ -22462,26 +22470,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listProject1s") } } - + public struct ListProject1: GraphQLSelectionSet { public static let possibleTypes = ["ModelProject1Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelProject1Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelProject1Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -22490,16 +22498,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -22508,10 +22516,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Project1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -22520,17 +22528,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -22539,7 +22547,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -22548,7 +22556,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -22557,7 +22565,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -22566,7 +22574,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -22575,7 +22583,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -22584,10 +22592,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -22595,17 +22603,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -22614,7 +22622,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -22623,7 +22631,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -22632,7 +22640,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -22641,7 +22649,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -22655,38 +22663,38 @@ public struct APISwift { } } } - + public final class GetTeam1Query: GraphQLQuery { public static let operationString = "query GetTeam1($id: ID!) {\n getTeam1(id: $id) {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getTeam1", arguments: ["id": GraphQLVariable("id")], type: .object(GetTeam1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getTeam1: GetTeam1? = nil) { - self.init(snapshot: ["__typename": "Query", "getTeam1": getTeam1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getTeam1": getTeam1.flatMap(\.snapshot)]) } - + public var getTeam1: GetTeam1? { get { return (snapshot["getTeam1"] as? Snapshot).flatMap { GetTeam1(snapshot: $0) } @@ -22695,10 +22703,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getTeam1") } } - + public struct GetTeam1: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -22706,17 +22714,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -22725,7 +22733,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -22734,7 +22742,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -22743,7 +22751,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -22752,7 +22760,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -22764,42 +22772,42 @@ public struct APISwift { } } } - + public final class ListTeam1sQuery: GraphQLQuery { public static let operationString = "query ListTeam1s($filter: ModelTeam1FilterInput, $limit: Int, $nextToken: String) {\n listTeam1s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelTeam1FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelTeam1FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listTeam1s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListTeam1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listTeam1s: ListTeam1? = nil) { - self.init(snapshot: ["__typename": "Query", "listTeam1s": listTeam1s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listTeam1s": listTeam1s.flatMap(\.snapshot)]) } - + public var listTeam1s: ListTeam1? { get { return (snapshot["listTeam1s"] as? Snapshot).flatMap { ListTeam1(snapshot: $0) } @@ -22808,26 +22816,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listTeam1s") } } - + public struct ListTeam1: GraphQLSelectionSet { public static let possibleTypes = ["ModelTeam1Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelTeam1Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelTeam1Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -22836,16 +22844,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -22854,10 +22862,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -22865,17 +22873,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -22884,7 +22892,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -22893,7 +22901,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -22902,7 +22910,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -22911,7 +22919,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -22924,38 +22932,38 @@ public struct APISwift { } } } - + public final class GetProject2Query: GraphQLQuery { public static let operationString = "query GetProject2($id: ID!) {\n getProject2(id: $id) {\n __typename\n id\n name\n teamID\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getProject2", arguments: ["id": GraphQLVariable("id")], type: .object(GetProject2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getProject2: GetProject2? = nil) { - self.init(snapshot: ["__typename": "Query", "getProject2": getProject2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getProject2": getProject2.flatMap(\.snapshot)]) } - + public var getProject2: GetProject2? { get { return (snapshot["getProject2"] as? Snapshot).flatMap { GetProject2(snapshot: $0) } @@ -22964,10 +22972,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getProject2") } } - + public struct GetProject2: GraphQLSelectionSet { public static let possibleTypes = ["Project2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -22977,17 +22985,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, teamId: GraphQLID, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -22996,7 +23004,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -23005,7 +23013,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -23014,7 +23022,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var teamId: GraphQLID { get { return snapshot["teamID"]! as! GraphQLID @@ -23023,7 +23031,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "teamID") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -23032,7 +23040,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -23041,7 +23049,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -23050,10 +23058,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -23061,17 +23069,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -23080,7 +23088,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -23089,7 +23097,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -23098,7 +23106,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -23107,7 +23115,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -23120,42 +23128,42 @@ public struct APISwift { } } } - + public final class ListProject2sQuery: GraphQLQuery { public static let operationString = "query ListProject2s($filter: ModelProject2FilterInput, $limit: Int, $nextToken: String) {\n listProject2s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n name\n teamID\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelProject2FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelProject2FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listProject2s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListProject2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listProject2s: ListProject2? = nil) { - self.init(snapshot: ["__typename": "Query", "listProject2s": listProject2s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listProject2s": listProject2s.flatMap(\.snapshot)]) } - + public var listProject2s: ListProject2? { get { return (snapshot["listProject2s"] as? Snapshot).flatMap { ListProject2(snapshot: $0) } @@ -23164,26 +23172,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listProject2s") } } - + public struct ListProject2: GraphQLSelectionSet { public static let possibleTypes = ["ModelProject2Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelProject2Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelProject2Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -23192,16 +23200,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -23210,10 +23218,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Project2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -23223,17 +23231,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, teamId: GraphQLID, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -23242,7 +23250,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -23251,7 +23259,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -23260,7 +23268,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var teamId: GraphQLID { get { return snapshot["teamID"]! as! GraphQLID @@ -23269,7 +23277,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "teamID") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -23278,7 +23286,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -23287,7 +23295,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -23296,10 +23304,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -23307,17 +23315,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -23326,7 +23334,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -23335,7 +23343,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -23344,7 +23352,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -23353,7 +23361,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -23367,38 +23375,38 @@ public struct APISwift { } } } - + public final class GetTeam2Query: GraphQLQuery { public static let operationString = "query GetTeam2($id: ID!) {\n getTeam2(id: $id) {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getTeam2", arguments: ["id": GraphQLVariable("id")], type: .object(GetTeam2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getTeam2: GetTeam2? = nil) { - self.init(snapshot: ["__typename": "Query", "getTeam2": getTeam2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getTeam2": getTeam2.flatMap(\.snapshot)]) } - + public var getTeam2: GetTeam2? { get { return (snapshot["getTeam2"] as? Snapshot).flatMap { GetTeam2(snapshot: $0) } @@ -23407,10 +23415,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getTeam2") } } - + public struct GetTeam2: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -23418,17 +23426,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -23437,7 +23445,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -23446,7 +23454,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -23455,7 +23463,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -23464,7 +23472,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -23476,42 +23484,42 @@ public struct APISwift { } } } - + public final class ListTeam2sQuery: GraphQLQuery { public static let operationString = "query ListTeam2s($filter: ModelTeam2FilterInput, $limit: Int, $nextToken: String) {\n listTeam2s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelTeam2FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelTeam2FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listTeam2s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListTeam2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listTeam2s: ListTeam2? = nil) { - self.init(snapshot: ["__typename": "Query", "listTeam2s": listTeam2s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listTeam2s": listTeam2s.flatMap(\.snapshot)]) } - + public var listTeam2s: ListTeam2? { get { return (snapshot["listTeam2s"] as? Snapshot).flatMap { ListTeam2(snapshot: $0) } @@ -23520,26 +23528,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listTeam2s") } } - + public struct ListTeam2: GraphQLSelectionSet { public static let possibleTypes = ["ModelTeam2Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelTeam2Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelTeam2Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -23548,16 +23556,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -23566,10 +23574,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -23577,17 +23585,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -23596,7 +23604,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -23605,7 +23613,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -23614,7 +23622,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -23623,7 +23631,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -23636,38 +23644,38 @@ public struct APISwift { } } } - + public final class GetPost3Query: GraphQLQuery { public static let operationString = "query GetPost3($id: ID!) {\n getPost3(id: $id) {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getPost3", arguments: ["id": GraphQLVariable("id")], type: .object(GetPost3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getPost3: GetPost3? = nil) { - self.init(snapshot: ["__typename": "Query", "getPost3": getPost3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getPost3": getPost3.flatMap(\.snapshot)]) } - + public var getPost3: GetPost3? { get { return (snapshot["getPost3"] as? Snapshot).flatMap { GetPost3(snapshot: $0) } @@ -23676,10 +23684,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getPost3") } } - + public struct GetPost3: GraphQLSelectionSet { public static let possibleTypes = ["Post3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -23688,17 +23696,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -23707,7 +23715,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -23716,7 +23724,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -23725,7 +23733,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -23734,7 +23742,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -23743,7 +23751,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -23752,26 +23760,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment3Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -23780,16 +23788,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -23798,10 +23806,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -23810,17 +23818,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -23829,7 +23837,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -23838,7 +23846,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -23847,7 +23855,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -23856,7 +23864,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -23865,7 +23873,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -23879,42 +23887,42 @@ public struct APISwift { } } } - + public final class ListPost3sQuery: GraphQLQuery { public static let operationString = "query ListPost3s($filter: ModelPost3FilterInput, $limit: Int, $nextToken: String) {\n listPost3s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n title\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelPost3FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelPost3FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listPost3s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListPost3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listPost3s: ListPost3? = nil) { - self.init(snapshot: ["__typename": "Query", "listPost3s": listPost3s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listPost3s": listPost3s.flatMap(\.snapshot)]) } - + public var listPost3s: ListPost3? { get { return (snapshot["listPost3s"] as? Snapshot).flatMap { ListPost3(snapshot: $0) } @@ -23923,26 +23931,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listPost3s") } } - + public struct ListPost3: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost3Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPost3Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPost3Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -23951,16 +23959,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -23969,10 +23977,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Post3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -23981,17 +23989,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24000,7 +24008,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -24009,7 +24017,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -24018,7 +24026,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -24027,7 +24035,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -24036,7 +24044,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -24045,25 +24053,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment3Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment3Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24072,7 +24080,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -24086,38 +24094,38 @@ public struct APISwift { } } } - + public final class GetComment3Query: GraphQLQuery { public static let operationString = "query GetComment3($id: ID!) {\n getComment3(id: $id) {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getComment3", arguments: ["id": GraphQLVariable("id")], type: .object(GetComment3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getComment3: GetComment3? = nil) { - self.init(snapshot: ["__typename": "Query", "getComment3": getComment3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getComment3": getComment3.flatMap(\.snapshot)]) } - + public var getComment3: GetComment3? { get { return (snapshot["getComment3"] as? Snapshot).flatMap { GetComment3(snapshot: $0) } @@ -24126,10 +24134,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getComment3") } } - + public struct GetComment3: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -24138,17 +24146,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24157,7 +24165,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -24166,7 +24174,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -24175,7 +24183,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -24184,7 +24192,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -24193,7 +24201,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -24205,42 +24213,42 @@ public struct APISwift { } } } - + public final class ListComment3sQuery: GraphQLQuery { public static let operationString = "query ListComment3s($filter: ModelComment3FilterInput, $limit: Int, $nextToken: String) {\n listComment3s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelComment3FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelComment3FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listComment3s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListComment3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listComment3s: ListComment3? = nil) { - self.init(snapshot: ["__typename": "Query", "listComment3s": listComment3s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listComment3s": listComment3s.flatMap(\.snapshot)]) } - + public var listComment3s: ListComment3? { get { return (snapshot["listComment3s"] as? Snapshot).flatMap { ListComment3(snapshot: $0) } @@ -24249,26 +24257,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listComment3s") } } - + public struct ListComment3: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment3Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24277,16 +24285,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -24295,10 +24303,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -24307,17 +24315,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24326,7 +24334,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -24335,7 +24343,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -24344,7 +24352,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -24353,7 +24361,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -24362,7 +24370,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -24375,38 +24383,38 @@ public struct APISwift { } } } - + public final class GetPost4Query: GraphQLQuery { public static let operationString = "query GetPost4($id: ID!) {\n getPost4(id: $id) {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getPost4", arguments: ["id": GraphQLVariable("id")], type: .object(GetPost4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getPost4: GetPost4? = nil) { - self.init(snapshot: ["__typename": "Query", "getPost4": getPost4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getPost4": getPost4.flatMap(\.snapshot)]) } - + public var getPost4: GetPost4? { get { return (snapshot["getPost4"] as? Snapshot).flatMap { GetPost4(snapshot: $0) } @@ -24415,10 +24423,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getPost4") } } - + public struct GetPost4: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -24427,17 +24435,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24446,7 +24454,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -24455,7 +24463,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -24464,7 +24472,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -24473,7 +24481,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -24482,7 +24490,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -24491,26 +24499,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24519,16 +24527,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -24537,10 +24545,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -24549,17 +24557,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24568,7 +24576,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -24577,7 +24585,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -24586,7 +24594,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -24595,7 +24603,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -24604,7 +24612,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -24618,42 +24626,42 @@ public struct APISwift { } } } - + public final class ListPost4sQuery: GraphQLQuery { public static let operationString = "query ListPost4s($filter: ModelPost4FilterInput, $limit: Int, $nextToken: String) {\n listPost4s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n title\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelPost4FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelPost4FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listPost4s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListPost4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listPost4s: ListPost4? = nil) { - self.init(snapshot: ["__typename": "Query", "listPost4s": listPost4s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listPost4s": listPost4s.flatMap(\.snapshot)]) } - + public var listPost4s: ListPost4? { get { return (snapshot["listPost4s"] as? Snapshot).flatMap { ListPost4(snapshot: $0) } @@ -24662,26 +24670,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listPost4s") } } - + public struct ListPost4: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPost4Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPost4Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24690,16 +24698,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -24708,10 +24716,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -24720,17 +24728,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24739,7 +24747,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -24748,7 +24756,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -24757,7 +24765,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -24766,7 +24774,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -24775,7 +24783,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -24784,25 +24792,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment4Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24811,7 +24819,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -24825,38 +24833,38 @@ public struct APISwift { } } } - + public final class GetComment4Query: GraphQLQuery { public static let operationString = "query GetComment4($id: ID!) {\n getComment4(id: $id) {\n __typename\n id\n postID\n content\n post {\n __typename\n id\n title\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getComment4", arguments: ["id": GraphQLVariable("id")], type: .object(GetComment4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getComment4: GetComment4? = nil) { - self.init(snapshot: ["__typename": "Query", "getComment4": getComment4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getComment4": getComment4.flatMap(\.snapshot)]) } - + public var getComment4: GetComment4? { get { return (snapshot["getComment4"] as? Snapshot).flatMap { GetComment4(snapshot: $0) } @@ -24865,10 +24873,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getComment4") } } - + public struct GetComment4: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -24878,17 +24886,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, post: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24897,7 +24905,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -24906,7 +24914,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -24915,7 +24923,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -24924,7 +24932,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -24933,7 +24941,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -24942,7 +24950,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -24951,10 +24959,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -24963,17 +24971,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -24982,7 +24990,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -24991,7 +24999,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -25000,7 +25008,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -25009,7 +25017,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -25018,7 +25026,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -25027,25 +25035,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment4Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -25054,7 +25062,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -25068,42 +25076,42 @@ public struct APISwift { } } } - + public final class ListComment4sQuery: GraphQLQuery { public static let operationString = "query ListComment4s($filter: ModelComment4FilterInput, $limit: Int, $nextToken: String) {\n listComment4s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n postID\n content\n post {\n __typename\n id\n title\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelComment4FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelComment4FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listComment4s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListComment4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listComment4s: ListComment4? = nil) { - self.init(snapshot: ["__typename": "Query", "listComment4s": listComment4s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listComment4s": listComment4s.flatMap(\.snapshot)]) } - + public var listComment4s: ListComment4? { get { return (snapshot["listComment4s"] as? Snapshot).flatMap { ListComment4(snapshot: $0) } @@ -25112,26 +25120,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listComment4s") } } - + public struct ListComment4: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -25140,16 +25148,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -25158,10 +25166,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -25171,17 +25179,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, post: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -25190,7 +25198,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -25199,7 +25207,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -25208,7 +25216,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -25217,7 +25225,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -25226,7 +25234,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -25235,7 +25243,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -25244,10 +25252,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -25255,17 +25263,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -25274,7 +25282,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -25283,7 +25291,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -25292,7 +25300,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -25301,7 +25309,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -25315,38 +25323,38 @@ public struct APISwift { } } } - + public final class GetPost5Query: GraphQLQuery { public static let operationString = "query GetPost5($id: ID!) {\n getPost5(id: $id) {\n __typename\n id\n title\n editors {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getPost5", arguments: ["id": GraphQLVariable("id")], type: .object(GetPost5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getPost5: GetPost5? = nil) { - self.init(snapshot: ["__typename": "Query", "getPost5": getPost5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getPost5": getPost5.flatMap(\.snapshot)]) } - + public var getPost5: GetPost5? { get { return (snapshot["getPost5"] as? Snapshot).flatMap { GetPost5(snapshot: $0) } @@ -25355,10 +25363,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getPost5") } } - + public struct GetPost5: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -25367,17 +25375,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -25386,7 +25394,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -25395,7 +25403,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -25404,7 +25412,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -25413,7 +25421,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -25422,7 +25430,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -25431,26 +25439,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -25459,16 +25467,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -25477,10 +25485,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -25489,17 +25497,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -25508,7 +25516,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -25517,7 +25525,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -25526,7 +25534,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -25535,7 +25543,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -25544,7 +25552,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -25558,42 +25566,42 @@ public struct APISwift { } } } - + public final class ListPost5sQuery: GraphQLQuery { public static let operationString = "query ListPost5s($filter: ModelPost5FilterInput, $limit: Int, $nextToken: String) {\n listPost5s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n title\n editors {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelPost5FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelPost5FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listPost5s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListPost5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listPost5s: ListPost5? = nil) { - self.init(snapshot: ["__typename": "Query", "listPost5s": listPost5s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listPost5s": listPost5s.flatMap(\.snapshot)]) } - + public var listPost5s: ListPost5? { get { return (snapshot["listPost5s"] as? Snapshot).flatMap { ListPost5(snapshot: $0) } @@ -25602,26 +25610,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listPost5s") } } - + public struct ListPost5: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPost5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPost5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -25630,16 +25638,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -25648,10 +25656,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -25660,17 +25668,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -25679,7 +25687,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -25688,7 +25696,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -25697,7 +25705,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -25706,7 +25714,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -25715,7 +25723,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -25724,25 +25732,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -25751,7 +25759,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -25765,38 +25773,38 @@ public struct APISwift { } } } - + public final class GetPostEditor5Query: GraphQLQuery { public static let operationString = "query GetPostEditor5($id: ID!) {\n getPostEditor5(id: $id) {\n __typename\n id\n postID\n editorID\n post {\n __typename\n id\n title\n editors {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n editor {\n __typename\n id\n username\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getPostEditor5", arguments: ["id": GraphQLVariable("id")], type: .object(GetPostEditor5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getPostEditor5: GetPostEditor5? = nil) { - self.init(snapshot: ["__typename": "Query", "getPostEditor5": getPostEditor5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getPostEditor5": getPostEditor5.flatMap(\.snapshot)]) } - + public var getPostEditor5: GetPostEditor5? { get { return (snapshot["getPostEditor5"] as? Snapshot).flatMap { GetPostEditor5(snapshot: $0) } @@ -25805,10 +25813,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getPostEditor5") } } - + public struct GetPostEditor5: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -25819,17 +25827,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, post: Post, editor: Editor, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "post": post.snapshot, "editor": editor.snapshot, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -25838,7 +25846,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -25847,7 +25855,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -25856,7 +25864,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -25865,7 +25873,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var post: Post { get { return Post(snapshot: snapshot["post"]! as! Snapshot) @@ -25874,7 +25882,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "post") } } - + public var editor: Editor { get { return Editor(snapshot: snapshot["editor"]! as! Snapshot) @@ -25883,7 +25891,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "editor") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -25892,7 +25900,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -25901,10 +25909,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -25913,17 +25921,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -25932,7 +25940,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -25941,7 +25949,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -25950,7 +25958,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -25959,7 +25967,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -25968,7 +25976,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -25977,25 +25985,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26004,7 +26012,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -26015,10 +26023,10 @@ public struct APISwift { } } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -26027,17 +26035,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26046,7 +26054,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -26055,7 +26063,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -26064,7 +26072,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -26073,7 +26081,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -26082,7 +26090,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -26091,25 +26099,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26118,7 +26126,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -26132,42 +26140,42 @@ public struct APISwift { } } } - + public final class ListPostEditor5sQuery: GraphQLQuery { public static let operationString = "query ListPostEditor5s($filter: ModelPostEditor5FilterInput, $limit: Int, $nextToken: String) {\n listPostEditor5s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n postID\n editorID\n post {\n __typename\n id\n title\n createdAt\n updatedAt\n }\n editor {\n __typename\n id\n username\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelPostEditor5FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelPostEditor5FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listPostEditor5s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListPostEditor5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listPostEditor5s: ListPostEditor5? = nil) { - self.init(snapshot: ["__typename": "Query", "listPostEditor5s": listPostEditor5s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listPostEditor5s": listPostEditor5s.flatMap(\.snapshot)]) } - + public var listPostEditor5s: ListPostEditor5? { get { return (snapshot["listPostEditor5s"] as? Snapshot).flatMap { ListPostEditor5(snapshot: $0) } @@ -26176,26 +26184,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listPostEditor5s") } } - + public struct ListPostEditor5: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26204,16 +26212,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -26222,10 +26230,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -26236,17 +26244,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, post: Post, editor: Editor, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "post": post.snapshot, "editor": editor.snapshot, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26255,7 +26263,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -26264,7 +26272,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -26273,7 +26281,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -26282,7 +26290,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var post: Post { get { return Post(snapshot: snapshot["post"]! as! Snapshot) @@ -26291,7 +26299,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "post") } } - + public var editor: Editor { get { return Editor(snapshot: snapshot["editor"]! as! Snapshot) @@ -26300,7 +26308,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "editor") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -26309,7 +26317,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -26318,10 +26326,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -26329,17 +26337,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26348,7 +26356,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -26357,7 +26365,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -26366,7 +26374,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -26375,7 +26383,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -26385,10 +26393,10 @@ public struct APISwift { } } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -26396,17 +26404,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26415,7 +26423,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -26424,7 +26432,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -26433,7 +26441,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -26442,7 +26450,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -26456,38 +26464,38 @@ public struct APISwift { } } } - + public final class GetUser5Query: GraphQLQuery { public static let operationString = "query GetUser5($id: ID!) {\n getUser5(id: $id) {\n __typename\n id\n username\n posts {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getUser5", arguments: ["id": GraphQLVariable("id")], type: .object(GetUser5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getUser5: GetUser5? = nil) { - self.init(snapshot: ["__typename": "Query", "getUser5": getUser5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getUser5": getUser5.flatMap(\.snapshot)]) } - + public var getUser5: GetUser5? { get { return (snapshot["getUser5"] as? Snapshot).flatMap { GetUser5(snapshot: $0) } @@ -26496,10 +26504,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getUser5") } } - + public struct GetUser5: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -26508,17 +26516,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26527,7 +26535,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -26536,7 +26544,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -26545,7 +26553,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -26554,7 +26562,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -26563,7 +26571,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -26572,26 +26580,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26600,16 +26608,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -26618,10 +26626,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -26630,17 +26638,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26649,7 +26657,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -26658,7 +26666,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -26667,7 +26675,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -26676,7 +26684,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -26685,7 +26693,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -26699,42 +26707,42 @@ public struct APISwift { } } } - + public final class ListUser5sQuery: GraphQLQuery { public static let operationString = "query ListUser5s($filter: ModelUser5FilterInput, $limit: Int, $nextToken: String) {\n listUser5s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n username\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelUser5FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelUser5FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listUser5s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListUser5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listUser5s: ListUser5? = nil) { - self.init(snapshot: ["__typename": "Query", "listUser5s": listUser5s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listUser5s": listUser5s.flatMap(\.snapshot)]) } - + public var listUser5s: ListUser5? { get { return (snapshot["listUser5s"] as? Snapshot).flatMap { ListUser5(snapshot: $0) } @@ -26743,26 +26751,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listUser5s") } } - + public struct ListUser5: GraphQLSelectionSet { public static let possibleTypes = ["ModelUser5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelUser5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelUser5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26771,16 +26779,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -26789,10 +26797,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -26801,17 +26809,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26820,7 +26828,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -26829,7 +26837,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -26838,7 +26846,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -26847,7 +26855,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -26856,7 +26864,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -26865,25 +26873,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26892,7 +26900,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -26906,38 +26914,38 @@ public struct APISwift { } } } - + public final class GetBlog6Query: GraphQLQuery { public static let operationString = "query GetBlog6($id: ID!) {\n getBlog6(id: $id) {\n __typename\n id\n name\n posts {\n __typename\n items {\n __typename\n id\n title\n blogID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getBlog6", arguments: ["id": GraphQLVariable("id")], type: .object(GetBlog6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getBlog6: GetBlog6? = nil) { - self.init(snapshot: ["__typename": "Query", "getBlog6": getBlog6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getBlog6": getBlog6.flatMap(\.snapshot)]) } - + public var getBlog6: GetBlog6? { get { return (snapshot["getBlog6"] as? Snapshot).flatMap { GetBlog6(snapshot: $0) } @@ -26946,10 +26954,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getBlog6") } } - + public struct GetBlog6: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -26958,17 +26966,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -26977,7 +26985,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -26986,7 +26994,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -26995,7 +27003,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -27004,7 +27012,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -27013,7 +27021,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -27022,26 +27030,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27050,16 +27058,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -27068,10 +27076,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -27080,17 +27088,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27099,7 +27107,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -27108,7 +27116,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -27117,7 +27125,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -27126,7 +27134,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -27135,7 +27143,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -27149,42 +27157,42 @@ public struct APISwift { } } } - + public final class ListBlog6sQuery: GraphQLQuery { public static let operationString = "query ListBlog6s($filter: ModelBlog6FilterInput, $limit: Int, $nextToken: String) {\n listBlog6s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n name\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelBlog6FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelBlog6FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listBlog6s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListBlog6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listBlog6s: ListBlog6? = nil) { - self.init(snapshot: ["__typename": "Query", "listBlog6s": listBlog6s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listBlog6s": listBlog6s.flatMap(\.snapshot)]) } - + public var listBlog6s: ListBlog6? { get { return (snapshot["listBlog6s"] as? Snapshot).flatMap { ListBlog6(snapshot: $0) } @@ -27193,26 +27201,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listBlog6s") } } - + public struct ListBlog6: GraphQLSelectionSet { public static let possibleTypes = ["ModelBlog6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelBlog6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelBlog6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27221,16 +27229,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -27239,10 +27247,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -27251,17 +27259,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27270,7 +27278,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -27279,7 +27287,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -27288,7 +27296,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -27297,7 +27305,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -27306,7 +27314,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -27315,25 +27323,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPost6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27342,7 +27350,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -27356,38 +27364,38 @@ public struct APISwift { } } } - + public final class GetPost6Query: GraphQLQuery { public static let operationString = "query GetPost6($id: ID!) {\n getPost6(id: $id) {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getPost6", arguments: ["id": GraphQLVariable("id")], type: .object(GetPost6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getPost6: GetPost6? = nil) { - self.init(snapshot: ["__typename": "Query", "getPost6": getPost6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getPost6": getPost6.flatMap(\.snapshot)]) } - + public var getPost6: GetPost6? { get { return (snapshot["getPost6"] as? Snapshot).flatMap { GetPost6(snapshot: $0) } @@ -27396,10 +27404,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getPost6") } } - + public struct GetPost6: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -27410,17 +27418,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27429,7 +27437,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -27438,7 +27446,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -27447,7 +27455,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -27456,7 +27464,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -27465,7 +27473,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -27474,7 +27482,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -27483,7 +27491,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -27492,10 +27500,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -27504,17 +27512,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27523,7 +27531,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -27532,7 +27540,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -27541,7 +27549,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -27550,7 +27558,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -27559,7 +27567,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -27568,25 +27576,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPost6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27595,7 +27603,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -27606,26 +27614,26 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27634,16 +27642,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -27652,10 +27660,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -27664,17 +27672,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27683,7 +27691,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -27692,7 +27700,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -27701,7 +27709,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -27710,7 +27718,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -27719,7 +27727,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -27733,42 +27741,42 @@ public struct APISwift { } } } - + public final class ListPost6sQuery: GraphQLQuery { public static let operationString = "query ListPost6s($filter: ModelPost6FilterInput, $limit: Int, $nextToken: String) {\n listPost6s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelPost6FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelPost6FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listPost6s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListPost6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listPost6s: ListPost6? = nil) { - self.init(snapshot: ["__typename": "Query", "listPost6s": listPost6s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listPost6s": listPost6s.flatMap(\.snapshot)]) } - + public var listPost6s: ListPost6? { get { return (snapshot["listPost6s"] as? Snapshot).flatMap { ListPost6(snapshot: $0) } @@ -27777,26 +27785,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listPost6s") } } - + public struct ListPost6: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27805,16 +27813,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -27823,10 +27831,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -27837,17 +27845,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27856,7 +27864,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -27865,7 +27873,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -27874,7 +27882,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -27883,7 +27891,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -27892,7 +27900,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -27901,7 +27909,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -27910,7 +27918,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -27919,10 +27927,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -27930,17 +27938,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -27949,7 +27957,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -27958,7 +27966,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -27967,7 +27975,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -27976,7 +27984,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -27986,25 +27994,25 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -28013,7 +28021,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -28027,38 +28035,38 @@ public struct APISwift { } } } - + public final class GetComment6Query: GraphQLQuery { public static let operationString = "query GetComment6($id: ID!) {\n getComment6(id: $id) {\n __typename\n id\n postID\n post {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n content\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getComment6", arguments: ["id": GraphQLVariable("id")], type: .object(GetComment6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getComment6: GetComment6? = nil) { - self.init(snapshot: ["__typename": "Query", "getComment6": getComment6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getComment6": getComment6.flatMap(\.snapshot)]) } - + public var getComment6: GetComment6? { get { return (snapshot["getComment6"] as? Snapshot).flatMap { GetComment6(snapshot: $0) } @@ -28067,10 +28075,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getComment6") } } - + public struct GetComment6: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -28080,17 +28088,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, post: Post? = nil, content: String, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap { $0.snapshot }, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap(\.snapshot), "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -28099,7 +28107,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -28108,7 +28116,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -28117,7 +28125,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -28126,7 +28134,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -28135,7 +28143,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -28144,7 +28152,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -28153,10 +28161,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -28167,17 +28175,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -28186,7 +28194,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -28195,7 +28203,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -28204,7 +28212,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -28213,7 +28221,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -28222,7 +28230,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -28231,7 +28239,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -28240,7 +28248,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -28249,10 +28257,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -28260,17 +28268,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -28279,7 +28287,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -28288,7 +28296,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -28297,7 +28305,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -28306,7 +28314,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -28316,25 +28324,25 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -28343,7 +28351,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -28357,42 +28365,42 @@ public struct APISwift { } } } - + public final class ListComment6sQuery: GraphQLQuery { public static let operationString = "query ListComment6s($filter: ModelComment6FilterInput, $limit: Int, $nextToken: String) {\n listComment6s(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n postID\n post {\n __typename\n id\n title\n blogID\n createdAt\n updatedAt\n }\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelComment6FilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelComment6FilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listComment6s", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListComment6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listComment6s: ListComment6? = nil) { - self.init(snapshot: ["__typename": "Query", "listComment6s": listComment6s.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listComment6s": listComment6s.flatMap(\.snapshot)]) } - + public var listComment6s: ListComment6? { get { return (snapshot["listComment6s"] as? Snapshot).flatMap { ListComment6(snapshot: $0) } @@ -28401,26 +28409,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listComment6s") } } - + public struct ListComment6: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -28429,16 +28437,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -28447,10 +28455,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -28460,17 +28468,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, post: Post? = nil, content: String, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap { $0.snapshot }, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap(\.snapshot), "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -28479,7 +28487,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -28488,7 +28496,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -28497,7 +28505,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -28506,7 +28514,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -28515,7 +28523,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -28524,7 +28532,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -28533,10 +28541,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -28545,17 +28553,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -28564,7 +28572,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -28573,7 +28581,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -28582,7 +28590,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -28591,7 +28599,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -28600,7 +28608,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -28614,38 +28622,38 @@ public struct APISwift { } } } - + public final class GetScalarContainerQuery: GraphQLQuery { public static let operationString = "query GetScalarContainer($id: ID!) {\n getScalarContainer(id: $id) {\n __typename\n id\n myString\n myInt\n myDouble\n myBool\n myDate\n myTime\n myDateTime\n myTimeStamp\n myEmail\n myJSON\n myPhone\n myURL\n myIPAddress\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getScalarContainer", arguments: ["id": GraphQLVariable("id")], type: .object(GetScalarContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getScalarContainer: GetScalarContainer? = nil) { - self.init(snapshot: ["__typename": "Query", "getScalarContainer": getScalarContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getScalarContainer": getScalarContainer.flatMap(\.snapshot)]) } - + public var getScalarContainer: GetScalarContainer? { get { return (snapshot["getScalarContainer"] as? Snapshot).flatMap { GetScalarContainer(snapshot: $0) } @@ -28654,10 +28662,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getScalarContainer") } } - + public struct GetScalarContainer: GraphQLSelectionSet { public static let possibleTypes = ["ScalarContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -28677,17 +28685,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, myString: String? = nil, myInt: Int? = nil, myDouble: Double? = nil, myBool: Bool? = nil, myDate: String? = nil, myTime: String? = nil, myDateTime: String? = nil, myTimeStamp: Int? = nil, myEmail: String? = nil, myJson: String? = nil, myPhone: String? = nil, myUrl: String? = nil, myIpAddress: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ScalarContainer", "id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -28696,7 +28704,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -28705,7 +28713,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var myString: String? { get { return snapshot["myString"] as? String @@ -28714,7 +28722,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myString") } } - + public var myInt: Int? { get { return snapshot["myInt"] as? Int @@ -28723,7 +28731,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myInt") } } - + public var myDouble: Double? { get { return snapshot["myDouble"] as? Double @@ -28732,7 +28740,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDouble") } } - + public var myBool: Bool? { get { return snapshot["myBool"] as? Bool @@ -28741,7 +28749,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myBool") } } - + public var myDate: String? { get { return snapshot["myDate"] as? String @@ -28750,7 +28758,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDate") } } - + public var myTime: String? { get { return snapshot["myTime"] as? String @@ -28759,7 +28767,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTime") } } - + public var myDateTime: String? { get { return snapshot["myDateTime"] as? String @@ -28768,7 +28776,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDateTime") } } - + public var myTimeStamp: Int? { get { return snapshot["myTimeStamp"] as? Int @@ -28777,7 +28785,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTimeStamp") } } - + public var myEmail: String? { get { return snapshot["myEmail"] as? String @@ -28786,7 +28794,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myEmail") } } - + public var myJson: String? { get { return snapshot["myJSON"] as? String @@ -28795,7 +28803,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myJSON") } } - + public var myPhone: String? { get { return snapshot["myPhone"] as? String @@ -28804,7 +28812,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myPhone") } } - + public var myUrl: String? { get { return snapshot["myURL"] as? String @@ -28813,7 +28821,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myURL") } } - + public var myIpAddress: String? { get { return snapshot["myIPAddress"] as? String @@ -28822,7 +28830,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myIPAddress") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -28831,7 +28839,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -28843,42 +28851,42 @@ public struct APISwift { } } } - + public final class ListScalarContainersQuery: GraphQLQuery { public static let operationString = "query ListScalarContainers($filter: ModelScalarContainerFilterInput, $limit: Int, $nextToken: String) {\n listScalarContainers(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n myString\n myInt\n myDouble\n myBool\n myDate\n myTime\n myDateTime\n myTimeStamp\n myEmail\n myJSON\n myPhone\n myURL\n myIPAddress\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelScalarContainerFilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelScalarContainerFilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listScalarContainers", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListScalarContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listScalarContainers: ListScalarContainer? = nil) { - self.init(snapshot: ["__typename": "Query", "listScalarContainers": listScalarContainers.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listScalarContainers": listScalarContainers.flatMap(\.snapshot)]) } - + public var listScalarContainers: ListScalarContainer? { get { return (snapshot["listScalarContainers"] as? Snapshot).flatMap { ListScalarContainer(snapshot: $0) } @@ -28887,26 +28895,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listScalarContainers") } } - + public struct ListScalarContainer: GraphQLSelectionSet { public static let possibleTypes = ["ModelScalarContainerConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelScalarContainerConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelScalarContainerConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -28915,16 +28923,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -28933,10 +28941,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["ScalarContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -28956,17 +28964,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, myString: String? = nil, myInt: Int? = nil, myDouble: Double? = nil, myBool: Bool? = nil, myDate: String? = nil, myTime: String? = nil, myDateTime: String? = nil, myTimeStamp: Int? = nil, myEmail: String? = nil, myJson: String? = nil, myPhone: String? = nil, myUrl: String? = nil, myIpAddress: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ScalarContainer", "id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -28975,7 +28983,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -28984,7 +28992,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var myString: String? { get { return snapshot["myString"] as? String @@ -28993,7 +29001,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myString") } } - + public var myInt: Int? { get { return snapshot["myInt"] as? Int @@ -29002,7 +29010,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myInt") } } - + public var myDouble: Double? { get { return snapshot["myDouble"] as? Double @@ -29011,7 +29019,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDouble") } } - + public var myBool: Bool? { get { return snapshot["myBool"] as? Bool @@ -29020,7 +29028,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myBool") } } - + public var myDate: String? { get { return snapshot["myDate"] as? String @@ -29029,7 +29037,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDate") } } - + public var myTime: String? { get { return snapshot["myTime"] as? String @@ -29038,7 +29046,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTime") } } - + public var myDateTime: String? { get { return snapshot["myDateTime"] as? String @@ -29047,7 +29055,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDateTime") } } - + public var myTimeStamp: Int? { get { return snapshot["myTimeStamp"] as? Int @@ -29056,7 +29064,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTimeStamp") } } - + public var myEmail: String? { get { return snapshot["myEmail"] as? String @@ -29065,7 +29073,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myEmail") } } - + public var myJson: String? { get { return snapshot["myJSON"] as? String @@ -29074,7 +29082,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myJSON") } } - + public var myPhone: String? { get { return snapshot["myPhone"] as? String @@ -29083,7 +29091,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myPhone") } } - + public var myUrl: String? { get { return snapshot["myURL"] as? String @@ -29092,7 +29100,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myURL") } } - + public var myIpAddress: String? { get { return snapshot["myIPAddress"] as? String @@ -29101,7 +29109,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myIPAddress") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -29110,7 +29118,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -29123,38 +29131,38 @@ public struct APISwift { } } } - + public final class GetListIntContainerQuery: GraphQLQuery { public static let operationString = "query GetListIntContainer($id: ID!) {\n getListIntContainer(id: $id) {\n __typename\n id\n test\n nullableInt\n intList\n intNullableList\n nullableIntList\n nullableIntNullableList\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getListIntContainer", arguments: ["id": GraphQLVariable("id")], type: .object(GetListIntContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getListIntContainer: GetListIntContainer? = nil) { - self.init(snapshot: ["__typename": "Query", "getListIntContainer": getListIntContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getListIntContainer": getListIntContainer.flatMap(\.snapshot)]) } - + public var getListIntContainer: GetListIntContainer? { get { return (snapshot["getListIntContainer"] as? Snapshot).flatMap { GetListIntContainer(snapshot: $0) } @@ -29163,10 +29171,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getListIntContainer") } } - + public struct GetListIntContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListIntContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -29179,17 +29187,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: Int, nullableInt: Int? = nil, intList: [Int], intNullableList: [Int]? = nil, nullableIntList: [Int?], nullableIntNullableList: [Int?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListIntContainer", "id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -29198,7 +29206,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -29207,7 +29215,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: Int { get { return snapshot["test"]! as! Int @@ -29216,7 +29224,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableInt: Int? { get { return snapshot["nullableInt"] as? Int @@ -29225,7 +29233,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableInt") } } - + public var intList: [Int] { get { return snapshot["intList"]! as! [Int] @@ -29234,7 +29242,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intList") } } - + public var intNullableList: [Int]? { get { return snapshot["intNullableList"] as? [Int] @@ -29243,7 +29251,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intNullableList") } } - + public var nullableIntList: [Int?] { get { return snapshot["nullableIntList"]! as! [Int?] @@ -29252,7 +29260,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntList") } } - + public var nullableIntNullableList: [Int?]? { get { return snapshot["nullableIntNullableList"] as? [Int?] @@ -29261,7 +29269,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -29270,7 +29278,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -29282,42 +29290,42 @@ public struct APISwift { } } } - + public final class ListListIntContainersQuery: GraphQLQuery { public static let operationString = "query ListListIntContainers($filter: ModelListIntContainerFilterInput, $limit: Int, $nextToken: String) {\n listListIntContainers(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n test\n nullableInt\n intList\n intNullableList\n nullableIntList\n nullableIntNullableList\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelListIntContainerFilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelListIntContainerFilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listListIntContainers", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListListIntContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listListIntContainers: ListListIntContainer? = nil) { - self.init(snapshot: ["__typename": "Query", "listListIntContainers": listListIntContainers.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listListIntContainers": listListIntContainers.flatMap(\.snapshot)]) } - + public var listListIntContainers: ListListIntContainer? { get { return (snapshot["listListIntContainers"] as? Snapshot).flatMap { ListListIntContainer(snapshot: $0) } @@ -29326,26 +29334,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listListIntContainers") } } - + public struct ListListIntContainer: GraphQLSelectionSet { public static let possibleTypes = ["ModelListIntContainerConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelListIntContainerConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelListIntContainerConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -29354,16 +29362,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -29372,10 +29380,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["ListIntContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -29388,17 +29396,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: Int, nullableInt: Int? = nil, intList: [Int], intNullableList: [Int]? = nil, nullableIntList: [Int?], nullableIntNullableList: [Int?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListIntContainer", "id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -29407,7 +29415,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -29416,7 +29424,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: Int { get { return snapshot["test"]! as! Int @@ -29425,7 +29433,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableInt: Int? { get { return snapshot["nullableInt"] as? Int @@ -29434,7 +29442,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableInt") } } - + public var intList: [Int] { get { return snapshot["intList"]! as! [Int] @@ -29443,7 +29451,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intList") } } - + public var intNullableList: [Int]? { get { return snapshot["intNullableList"] as? [Int] @@ -29452,7 +29460,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intNullableList") } } - + public var nullableIntList: [Int?] { get { return snapshot["nullableIntList"]! as! [Int?] @@ -29461,7 +29469,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntList") } } - + public var nullableIntNullableList: [Int?]? { get { return snapshot["nullableIntNullableList"] as? [Int?] @@ -29470,7 +29478,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -29479,7 +29487,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -29492,38 +29500,38 @@ public struct APISwift { } } } - + public final class GetListStringContainerQuery: GraphQLQuery { public static let operationString = "query GetListStringContainer($id: ID!) {\n getListStringContainer(id: $id) {\n __typename\n id\n test\n nullableString\n stringList\n stringNullableList\n nullableStringList\n nullableStringNullableList\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getListStringContainer", arguments: ["id": GraphQLVariable("id")], type: .object(GetListStringContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getListStringContainer: GetListStringContainer? = nil) { - self.init(snapshot: ["__typename": "Query", "getListStringContainer": getListStringContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getListStringContainer": getListStringContainer.flatMap(\.snapshot)]) } - + public var getListStringContainer: GetListStringContainer? { get { return (snapshot["getListStringContainer"] as? Snapshot).flatMap { GetListStringContainer(snapshot: $0) } @@ -29532,10 +29540,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getListStringContainer") } } - + public struct GetListStringContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListStringContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -29548,17 +29556,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: String, nullableString: String? = nil, stringList: [String], stringNullableList: [String]? = nil, nullableStringList: [String?], nullableStringNullableList: [String?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListStringContainer", "id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -29567,7 +29575,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -29576,7 +29584,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: String { get { return snapshot["test"]! as! String @@ -29585,7 +29593,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableString: String? { get { return snapshot["nullableString"] as? String @@ -29594,7 +29602,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableString") } } - + public var stringList: [String] { get { return snapshot["stringList"]! as! [String] @@ -29603,7 +29611,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringList") } } - + public var stringNullableList: [String]? { get { return snapshot["stringNullableList"] as? [String] @@ -29612,7 +29620,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringNullableList") } } - + public var nullableStringList: [String?] { get { return snapshot["nullableStringList"]! as! [String?] @@ -29621,7 +29629,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringList") } } - + public var nullableStringNullableList: [String?]? { get { return snapshot["nullableStringNullableList"] as? [String?] @@ -29630,7 +29638,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -29639,7 +29647,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -29651,42 +29659,42 @@ public struct APISwift { } } } - + public final class ListListStringContainersQuery: GraphQLQuery { public static let operationString = "query ListListStringContainers($filter: ModelListStringContainerFilterInput, $limit: Int, $nextToken: String) {\n listListStringContainers(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n test\n nullableString\n stringList\n stringNullableList\n nullableStringList\n nullableStringNullableList\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelListStringContainerFilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelListStringContainerFilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listListStringContainers", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListListStringContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listListStringContainers: ListListStringContainer? = nil) { - self.init(snapshot: ["__typename": "Query", "listListStringContainers": listListStringContainers.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listListStringContainers": listListStringContainers.flatMap(\.snapshot)]) } - + public var listListStringContainers: ListListStringContainer? { get { return (snapshot["listListStringContainers"] as? Snapshot).flatMap { ListListStringContainer(snapshot: $0) } @@ -29695,26 +29703,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listListStringContainers") } } - + public struct ListListStringContainer: GraphQLSelectionSet { public static let possibleTypes = ["ModelListStringContainerConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelListStringContainerConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelListStringContainerConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -29723,16 +29731,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -29741,10 +29749,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["ListStringContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -29757,17 +29765,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: String, nullableString: String? = nil, stringList: [String], stringNullableList: [String]? = nil, nullableStringList: [String?], nullableStringNullableList: [String?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListStringContainer", "id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -29776,7 +29784,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -29785,7 +29793,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: String { get { return snapshot["test"]! as! String @@ -29794,7 +29802,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableString: String? { get { return snapshot["nullableString"] as? String @@ -29803,7 +29811,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableString") } } - + public var stringList: [String] { get { return snapshot["stringList"]! as! [String] @@ -29812,7 +29820,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringList") } } - + public var stringNullableList: [String]? { get { return snapshot["stringNullableList"] as? [String] @@ -29821,7 +29829,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringNullableList") } } - + public var nullableStringList: [String?] { get { return snapshot["nullableStringList"]! as! [String?] @@ -29830,7 +29838,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringList") } } - + public var nullableStringNullableList: [String?]? { get { return snapshot["nullableStringNullableList"] as? [String?] @@ -29839,7 +29847,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -29848,7 +29856,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -29861,38 +29869,38 @@ public struct APISwift { } } } - + public final class GetEnumTestModelQuery: GraphQLQuery { public static let operationString = "query GetEnumTestModel($id: ID!) {\n getEnumTestModel(id: $id) {\n __typename\n id\n enumVal\n nullableEnumVal\n enumList\n enumNullableList\n nullableEnumList\n nullableEnumNullableList\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getEnumTestModel", arguments: ["id": GraphQLVariable("id")], type: .object(GetEnumTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getEnumTestModel: GetEnumTestModel? = nil) { - self.init(snapshot: ["__typename": "Query", "getEnumTestModel": getEnumTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getEnumTestModel": getEnumTestModel.flatMap(\.snapshot)]) } - + public var getEnumTestModel: GetEnumTestModel? { get { return (snapshot["getEnumTestModel"] as? Snapshot).flatMap { GetEnumTestModel(snapshot: $0) } @@ -29901,10 +29909,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getEnumTestModel") } } - + public struct GetEnumTestModel: GraphQLSelectionSet { public static let possibleTypes = ["EnumTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -29917,17 +29925,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, enumVal: TestEnum, nullableEnumVal: TestEnum? = nil, enumList: [TestEnum], enumNullableList: [TestEnum]? = nil, nullableEnumList: [TestEnum?], nullableEnumNullableList: [TestEnum?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "EnumTestModel", "id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -29936,7 +29944,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -29945,7 +29953,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var enumVal: TestEnum { get { return snapshot["enumVal"]! as! TestEnum @@ -29954,7 +29962,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumVal") } } - + public var nullableEnumVal: TestEnum? { get { return snapshot["nullableEnumVal"] as? TestEnum @@ -29963,7 +29971,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumVal") } } - + public var enumList: [TestEnum] { get { return snapshot["enumList"]! as! [TestEnum] @@ -29972,7 +29980,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumList") } } - + public var enumNullableList: [TestEnum]? { get { return snapshot["enumNullableList"] as? [TestEnum] @@ -29981,7 +29989,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumNullableList") } } - + public var nullableEnumList: [TestEnum?] { get { return snapshot["nullableEnumList"]! as! [TestEnum?] @@ -29990,7 +29998,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumList") } } - + public var nullableEnumNullableList: [TestEnum?]? { get { return snapshot["nullableEnumNullableList"] as? [TestEnum?] @@ -29999,7 +30007,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -30008,7 +30016,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -30020,42 +30028,42 @@ public struct APISwift { } } } - + public final class ListEnumTestModelsQuery: GraphQLQuery { public static let operationString = "query ListEnumTestModels($filter: ModelEnumTestModelFilterInput, $limit: Int, $nextToken: String) {\n listEnumTestModels(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n enumVal\n nullableEnumVal\n enumList\n enumNullableList\n nullableEnumList\n nullableEnumNullableList\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelEnumTestModelFilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelEnumTestModelFilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listEnumTestModels", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListEnumTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listEnumTestModels: ListEnumTestModel? = nil) { - self.init(snapshot: ["__typename": "Query", "listEnumTestModels": listEnumTestModels.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listEnumTestModels": listEnumTestModels.flatMap(\.snapshot)]) } - + public var listEnumTestModels: ListEnumTestModel? { get { return (snapshot["listEnumTestModels"] as? Snapshot).flatMap { ListEnumTestModel(snapshot: $0) } @@ -30064,26 +30072,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listEnumTestModels") } } - + public struct ListEnumTestModel: GraphQLSelectionSet { public static let possibleTypes = ["ModelEnumTestModelConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelEnumTestModelConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelEnumTestModelConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30092,16 +30100,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -30110,10 +30118,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["EnumTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -30126,17 +30134,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, enumVal: TestEnum, nullableEnumVal: TestEnum? = nil, enumList: [TestEnum], enumNullableList: [TestEnum]? = nil, nullableEnumList: [TestEnum?], nullableEnumNullableList: [TestEnum?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "EnumTestModel", "id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30145,7 +30153,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -30154,7 +30162,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var enumVal: TestEnum { get { return snapshot["enumVal"]! as! TestEnum @@ -30163,7 +30171,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumVal") } } - + public var nullableEnumVal: TestEnum? { get { return snapshot["nullableEnumVal"] as? TestEnum @@ -30172,7 +30180,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumVal") } } - + public var enumList: [TestEnum] { get { return snapshot["enumList"]! as! [TestEnum] @@ -30181,7 +30189,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumList") } } - + public var enumNullableList: [TestEnum]? { get { return snapshot["enumNullableList"] as? [TestEnum] @@ -30190,7 +30198,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumNullableList") } } - + public var nullableEnumList: [TestEnum?] { get { return snapshot["nullableEnumList"]! as! [TestEnum?] @@ -30199,7 +30207,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumList") } } - + public var nullableEnumNullableList: [TestEnum?]? { get { return snapshot["nullableEnumNullableList"] as? [TestEnum?] @@ -30208,7 +30216,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -30217,7 +30225,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -30230,38 +30238,38 @@ public struct APISwift { } } } - + public final class GetNestedTypeTestModelQuery: GraphQLQuery { public static let operationString = "query GetNestedTypeTestModel($id: ID!) {\n getNestedTypeTestModel(id: $id) {\n __typename\n id\n nestedVal {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedVal {\n __typename\n valueOne\n valueTwo\n }\n nestedList {\n __typename\n valueOne\n valueTwo\n }\n nestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getNestedTypeTestModel", arguments: ["id": GraphQLVariable("id")], type: .object(GetNestedTypeTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getNestedTypeTestModel: GetNestedTypeTestModel? = nil) { - self.init(snapshot: ["__typename": "Query", "getNestedTypeTestModel": getNestedTypeTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getNestedTypeTestModel": getNestedTypeTestModel.flatMap(\.snapshot)]) } - + public var getNestedTypeTestModel: GetNestedTypeTestModel? { get { return (snapshot["getNestedTypeTestModel"] as? Snapshot).flatMap { GetNestedTypeTestModel(snapshot: $0) } @@ -30270,10 +30278,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getNestedTypeTestModel") } } - + public struct GetNestedTypeTestModel: GraphQLSelectionSet { public static let possibleTypes = ["NestedTypeTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -30286,17 +30294,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, nestedVal: NestedVal, nullableNestedVal: NullableNestedVal? = nil, nestedList: [NestedList], nestedNullableList: [NestedNullableList]? = nil, nullableNestedList: [NullableNestedList?], nullableNestedNullableList: [NullableNestedNullableList?]? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap { $0.snapshot }, "nestedList": nestedList.map { $0.snapshot }, "nestedNullableList": nestedNullableList.flatMap { $0.map { $0.snapshot } }, "nullableNestedList": nullableNestedList.map { $0.flatMap { $0.snapshot } }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap(\.snapshot), "nestedList": nestedList.map(\.snapshot), "nestedNullableList": nestedNullableList.flatMap { $0.map(\.snapshot) }, "nullableNestedList": nullableNestedList.map { $0.flatMap(\.snapshot) }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap(\.snapshot) } }, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30305,7 +30313,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -30314,7 +30322,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var nestedVal: NestedVal { get { return NestedVal(snapshot: snapshot["nestedVal"]! as! Snapshot) @@ -30323,7 +30331,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "nestedVal") } } - + public var nullableNestedVal: NullableNestedVal? { get { return (snapshot["nullableNestedVal"] as? Snapshot).flatMap { NullableNestedVal(snapshot: $0) } @@ -30332,43 +30340,43 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "nullableNestedVal") } } - + public var nestedList: [NestedList] { get { return (snapshot["nestedList"] as! [Snapshot]).map { NestedList(snapshot: $0) } } set { - snapshot.updateValue(newValue.map { $0.snapshot }, forKey: "nestedList") + snapshot.updateValue(newValue.map(\.snapshot), forKey: "nestedList") } } - + public var nestedNullableList: [NestedNullableList]? { get { return (snapshot["nestedNullableList"] as? [Snapshot]).flatMap { $0.map { NestedNullableList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.snapshot } }, forKey: "nestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map(\.snapshot) }, forKey: "nestedNullableList") } } - + public var nullableNestedList: [NullableNestedList?] { get { return (snapshot["nullableNestedList"] as! [Snapshot?]).map { $0.flatMap { NullableNestedList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "nullableNestedList") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "nullableNestedList") } } - + public var nullableNestedNullableList: [NullableNestedNullableList?]? { get { return (snapshot["nullableNestedNullableList"] as? [Snapshot?]).flatMap { $0.map { $0.flatMap { NullableNestedNullableList(snapshot: $0) } } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, forKey: "nullableNestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap(\.snapshot) } }, forKey: "nullableNestedNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -30377,7 +30385,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -30386,26 +30394,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct NestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30414,7 +30422,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -30423,7 +30431,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -30433,26 +30441,26 @@ public struct APISwift { } } } - + public struct NullableNestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30461,7 +30469,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -30470,7 +30478,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -30480,26 +30488,26 @@ public struct APISwift { } } } - + public struct NestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30508,7 +30516,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -30517,7 +30525,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -30527,26 +30535,26 @@ public struct APISwift { } } } - + public struct NestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30555,7 +30563,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -30564,7 +30572,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -30574,26 +30582,26 @@ public struct APISwift { } } } - + public struct NullableNestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30602,7 +30610,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -30611,7 +30619,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -30621,26 +30629,26 @@ public struct APISwift { } } } - + public struct NullableNestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30649,7 +30657,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -30658,7 +30666,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -30671,42 +30679,42 @@ public struct APISwift { } } } - + public final class ListNestedTypeTestModelsQuery: GraphQLQuery { public static let operationString = "query ListNestedTypeTestModels($filter: ModelNestedTypeTestModelFilterInput, $limit: Int, $nextToken: String) {\n listNestedTypeTestModels(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n nestedVal {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedVal {\n __typename\n valueOne\n valueTwo\n }\n nestedList {\n __typename\n valueOne\n valueTwo\n }\n nestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelNestedTypeTestModelFilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelNestedTypeTestModelFilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listNestedTypeTestModels", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListNestedTypeTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listNestedTypeTestModels: ListNestedTypeTestModel? = nil) { - self.init(snapshot: ["__typename": "Query", "listNestedTypeTestModels": listNestedTypeTestModels.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listNestedTypeTestModels": listNestedTypeTestModels.flatMap(\.snapshot)]) } - + public var listNestedTypeTestModels: ListNestedTypeTestModel? { get { return (snapshot["listNestedTypeTestModels"] as? Snapshot).flatMap { ListNestedTypeTestModel(snapshot: $0) } @@ -30715,26 +30723,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listNestedTypeTestModels") } } - + public struct ListNestedTypeTestModel: GraphQLSelectionSet { public static let possibleTypes = ["ModelNestedTypeTestModelConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelNestedTypeTestModelConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelNestedTypeTestModelConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30743,16 +30751,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -30761,10 +30769,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["NestedTypeTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -30777,17 +30785,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, nestedVal: NestedVal, nullableNestedVal: NullableNestedVal? = nil, nestedList: [NestedList], nestedNullableList: [NestedNullableList]? = nil, nullableNestedList: [NullableNestedList?], nullableNestedNullableList: [NullableNestedNullableList?]? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap { $0.snapshot }, "nestedList": nestedList.map { $0.snapshot }, "nestedNullableList": nestedNullableList.flatMap { $0.map { $0.snapshot } }, "nullableNestedList": nullableNestedList.map { $0.flatMap { $0.snapshot } }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap(\.snapshot), "nestedList": nestedList.map(\.snapshot), "nestedNullableList": nestedNullableList.flatMap { $0.map(\.snapshot) }, "nullableNestedList": nullableNestedList.map { $0.flatMap(\.snapshot) }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap(\.snapshot) } }, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30796,7 +30804,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -30805,7 +30813,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var nestedVal: NestedVal { get { return NestedVal(snapshot: snapshot["nestedVal"]! as! Snapshot) @@ -30814,7 +30822,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "nestedVal") } } - + public var nullableNestedVal: NullableNestedVal? { get { return (snapshot["nullableNestedVal"] as? Snapshot).flatMap { NullableNestedVal(snapshot: $0) } @@ -30823,43 +30831,43 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "nullableNestedVal") } } - + public var nestedList: [NestedList] { get { return (snapshot["nestedList"] as! [Snapshot]).map { NestedList(snapshot: $0) } } set { - snapshot.updateValue(newValue.map { $0.snapshot }, forKey: "nestedList") + snapshot.updateValue(newValue.map(\.snapshot), forKey: "nestedList") } } - + public var nestedNullableList: [NestedNullableList]? { get { return (snapshot["nestedNullableList"] as? [Snapshot]).flatMap { $0.map { NestedNullableList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.snapshot } }, forKey: "nestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map(\.snapshot) }, forKey: "nestedNullableList") } } - + public var nullableNestedList: [NullableNestedList?] { get { return (snapshot["nullableNestedList"] as! [Snapshot?]).map { $0.flatMap { NullableNestedList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "nullableNestedList") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "nullableNestedList") } } - + public var nullableNestedNullableList: [NullableNestedNullableList?]? { get { return (snapshot["nullableNestedNullableList"] as? [Snapshot?]).flatMap { $0.map { $0.flatMap { NullableNestedNullableList(snapshot: $0) } } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, forKey: "nullableNestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap(\.snapshot) } }, forKey: "nullableNestedNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -30868,7 +30876,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -30877,26 +30885,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct NestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30905,7 +30913,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -30914,7 +30922,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -30924,26 +30932,26 @@ public struct APISwift { } } } - + public struct NullableNestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30952,7 +30960,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -30961,7 +30969,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -30971,26 +30979,26 @@ public struct APISwift { } } } - + public struct NestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -30999,7 +31007,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -31008,7 +31016,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -31018,26 +31026,26 @@ public struct APISwift { } } } - + public struct NestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -31046,7 +31054,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -31055,7 +31063,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -31065,26 +31073,26 @@ public struct APISwift { } } } - + public struct NullableNestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -31093,7 +31101,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -31102,7 +31110,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -31112,26 +31120,26 @@ public struct APISwift { } } } - + public struct NullableNestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -31140,7 +31148,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -31149,7 +31157,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -31163,31 +31171,31 @@ public struct APISwift { } } } - + public final class OnCreatePostSubscription: GraphQLSubscription { public static let operationString = "subscription OnCreatePost {\n onCreatePost {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n items {\n __typename\n id\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreatePost", type: .object(OnCreatePost.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreatePost: OnCreatePost? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreatePost": onCreatePost.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreatePost": onCreatePost.flatMap(\.snapshot)]) } - + public var onCreatePost: OnCreatePost? { get { return (snapshot["onCreatePost"] as? Snapshot).flatMap { OnCreatePost(snapshot: $0) } @@ -31196,10 +31204,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreatePost") } } - + public struct OnCreatePost: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -31212,17 +31220,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -31231,7 +31239,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -31240,7 +31248,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -31249,7 +31257,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -31258,7 +31266,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -31267,7 +31275,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -31276,7 +31284,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -31285,7 +31293,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -31294,7 +31302,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -31303,7 +31311,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -31312,26 +31320,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -31340,16 +31348,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -31358,10 +31366,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -31369,17 +31377,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -31388,7 +31396,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -31397,7 +31405,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -31406,7 +31414,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -31415,7 +31423,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -31429,31 +31437,31 @@ public struct APISwift { } } } - + public final class OnUpdatePostSubscription: GraphQLSubscription { public static let operationString = "subscription OnUpdatePost {\n onUpdatePost {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n items {\n __typename\n id\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdatePost", type: .object(OnUpdatePost.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdatePost: OnUpdatePost? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdatePost": onUpdatePost.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdatePost": onUpdatePost.flatMap(\.snapshot)]) } - + public var onUpdatePost: OnUpdatePost? { get { return (snapshot["onUpdatePost"] as? Snapshot).flatMap { OnUpdatePost(snapshot: $0) } @@ -31462,10 +31470,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdatePost") } } - + public struct OnUpdatePost: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -31478,17 +31486,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -31497,7 +31505,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -31506,7 +31514,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -31515,7 +31523,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -31524,7 +31532,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -31533,7 +31541,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -31542,7 +31550,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -31551,7 +31559,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -31560,7 +31568,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -31569,7 +31577,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -31578,26 +31586,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -31606,16 +31614,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -31624,10 +31632,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -31635,17 +31643,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -31654,7 +31662,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -31663,7 +31671,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -31672,7 +31680,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -31681,7 +31689,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -31695,31 +31703,31 @@ public struct APISwift { } } } - + public final class OnDeletePostSubscription: GraphQLSubscription { public static let operationString = "subscription OnDeletePost {\n onDeletePost {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n items {\n __typename\n id\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeletePost", type: .object(OnDeletePost.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeletePost: OnDeletePost? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeletePost": onDeletePost.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeletePost": onDeletePost.flatMap(\.snapshot)]) } - + public var onDeletePost: OnDeletePost? { get { return (snapshot["onDeletePost"] as? Snapshot).flatMap { OnDeletePost(snapshot: $0) } @@ -31728,10 +31736,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeletePost") } } - + public struct OnDeletePost: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -31744,17 +31752,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -31763,7 +31771,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -31772,7 +31780,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -31781,7 +31789,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -31790,7 +31798,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -31799,7 +31807,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -31808,7 +31816,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -31817,7 +31825,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -31826,7 +31834,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -31835,7 +31843,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -31844,26 +31852,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelCommentConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -31872,16 +31880,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -31890,10 +31898,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -31901,17 +31909,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -31920,7 +31928,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -31929,7 +31937,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -31938,7 +31946,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -31947,7 +31955,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -31961,31 +31969,31 @@ public struct APISwift { } } } - + public final class OnCreateCommentSubscription: GraphQLSubscription { public static let operationString = "subscription OnCreateComment {\n onCreateComment {\n __typename\n id\n content\n createdAt\n post {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n nextToken\n }\n }\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateComment", type: .object(OnCreateComment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateComment: OnCreateComment? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateComment": onCreateComment.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateComment": onCreateComment.flatMap(\.snapshot)]) } - + public var onCreateComment: OnCreateComment? { get { return (snapshot["onCreateComment"] as? Snapshot).flatMap { OnCreateComment(snapshot: $0) } @@ -31994,10 +32002,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateComment") } } - + public struct OnCreateComment: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -32006,17 +32014,17 @@ public struct APISwift { GraphQLField("post", type: .object(Post.selections)), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, post: Post? = nil, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap { $0.snapshot }, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap(\.snapshot), "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -32025,7 +32033,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -32034,7 +32042,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -32043,7 +32051,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -32052,7 +32060,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -32061,7 +32069,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -32070,10 +32078,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -32086,17 +32094,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -32105,7 +32113,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -32114,7 +32122,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -32123,7 +32131,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -32132,7 +32140,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -32141,7 +32149,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -32150,7 +32158,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -32159,7 +32167,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -32168,7 +32176,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -32177,7 +32185,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -32186,25 +32194,25 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelCommentConnection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -32213,7 +32221,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -32227,31 +32235,31 @@ public struct APISwift { } } } - + public final class OnUpdateCommentSubscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateComment {\n onUpdateComment {\n __typename\n id\n content\n createdAt\n post {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n nextToken\n }\n }\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateComment", type: .object(OnUpdateComment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateComment: OnUpdateComment? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateComment": onUpdateComment.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateComment": onUpdateComment.flatMap(\.snapshot)]) } - + public var onUpdateComment: OnUpdateComment? { get { return (snapshot["onUpdateComment"] as? Snapshot).flatMap { OnUpdateComment(snapshot: $0) } @@ -32260,10 +32268,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateComment") } } - + public struct OnUpdateComment: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -32272,17 +32280,17 @@ public struct APISwift { GraphQLField("post", type: .object(Post.selections)), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, post: Post? = nil, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap { $0.snapshot }, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap(\.snapshot), "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -32291,7 +32299,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -32300,7 +32308,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -32309,7 +32317,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -32318,7 +32326,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -32327,7 +32335,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -32336,10 +32344,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -32352,17 +32360,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -32371,7 +32379,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -32380,7 +32388,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -32389,7 +32397,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -32398,7 +32406,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -32407,7 +32415,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -32416,7 +32424,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -32425,7 +32433,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -32434,7 +32442,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -32443,7 +32451,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -32452,25 +32460,25 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelCommentConnection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -32479,7 +32487,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -32493,31 +32501,31 @@ public struct APISwift { } } } - + public final class OnDeleteCommentSubscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteComment {\n onDeleteComment {\n __typename\n id\n content\n createdAt\n post {\n __typename\n id\n title\n content\n createdAt\n updatedAt\n draft\n rating\n status\n comments {\n __typename\n nextToken\n }\n }\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteComment", type: .object(OnDeleteComment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteComment: OnDeleteComment? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteComment": onDeleteComment.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteComment": onDeleteComment.flatMap(\.snapshot)]) } - + public var onDeleteComment: OnDeleteComment? { get { return (snapshot["onDeleteComment"] as? Snapshot).flatMap { OnDeleteComment(snapshot: $0) } @@ -32526,10 +32534,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteComment") } } - + public struct OnDeleteComment: GraphQLSelectionSet { public static let possibleTypes = ["Comment"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -32538,17 +32546,17 @@ public struct APISwift { GraphQLField("post", type: .object(Post.selections)), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, content: String, createdAt: String, post: Post? = nil, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap { $0.snapshot }, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment", "id": id, "content": content, "createdAt": createdAt, "post": post.flatMap(\.snapshot), "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -32557,7 +32565,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -32566,7 +32574,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -32575,7 +32583,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -32584,7 +32592,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -32593,7 +32601,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -32602,10 +32610,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -32618,17 +32626,17 @@ public struct APISwift { GraphQLField("status", type: .scalar(PostStatus.self)), GraphQLField("comments", type: .object(Comment.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, content: String, createdAt: String, updatedAt: String? = nil, draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, comments: Comment? = nil) { - self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Post", "id": id, "title": title, "content": content, "createdAt": createdAt, "updatedAt": updatedAt, "draft": draft, "rating": rating, "status": status, "comments": comments.flatMap(\.snapshot)]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -32637,7 +32645,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -32646,7 +32654,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -32655,7 +32663,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -32664,7 +32672,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -32673,7 +32681,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String? { get { return snapshot["updatedAt"] as? String @@ -32682,7 +32690,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public var draft: Bool? { get { return snapshot["draft"] as? Bool @@ -32691,7 +32699,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "draft") } } - + public var rating: Double? { get { return snapshot["rating"] as? Double @@ -32700,7 +32708,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "rating") } } - + public var status: PostStatus? { get { return snapshot["status"] as? PostStatus @@ -32709,7 +32717,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "status") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -32718,25 +32726,25 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelCommentConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelCommentConnection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -32745,7 +32753,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -32759,31 +32767,31 @@ public struct APISwift { } } } - + public final class OnCreateProject1Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreateProject1 {\n onCreateProject1 {\n __typename\n id\n name\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateProject1", type: .object(OnCreateProject1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateProject1: OnCreateProject1? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateProject1": onCreateProject1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateProject1": onCreateProject1.flatMap(\.snapshot)]) } - + public var onCreateProject1: OnCreateProject1? { get { return (snapshot["onCreateProject1"] as? Snapshot).flatMap { OnCreateProject1(snapshot: $0) } @@ -32792,10 +32800,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateProject1") } } - + public struct OnCreateProject1: GraphQLSelectionSet { public static let possibleTypes = ["Project1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -32804,17 +32812,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -32823,7 +32831,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -32832,7 +32840,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -32841,7 +32849,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -32850,7 +32858,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -32859,7 +32867,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -32868,10 +32876,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -32879,17 +32887,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -32898,7 +32906,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -32907,7 +32915,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -32916,7 +32924,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -32925,7 +32933,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -32938,31 +32946,31 @@ public struct APISwift { } } } - + public final class OnUpdateProject1Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateProject1 {\n onUpdateProject1 {\n __typename\n id\n name\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateProject1", type: .object(OnUpdateProject1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateProject1: OnUpdateProject1? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateProject1": onUpdateProject1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateProject1": onUpdateProject1.flatMap(\.snapshot)]) } - + public var onUpdateProject1: OnUpdateProject1? { get { return (snapshot["onUpdateProject1"] as? Snapshot).flatMap { OnUpdateProject1(snapshot: $0) } @@ -32971,10 +32979,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateProject1") } } - + public struct OnUpdateProject1: GraphQLSelectionSet { public static let possibleTypes = ["Project1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -32983,17 +32991,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -33002,7 +33010,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -33011,7 +33019,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -33020,7 +33028,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -33029,7 +33037,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -33038,7 +33046,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -33047,10 +33055,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -33058,17 +33066,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -33077,7 +33085,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -33086,7 +33094,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -33095,7 +33103,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -33104,7 +33112,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -33117,31 +33125,31 @@ public struct APISwift { } } } - + public final class OnDeleteProject1Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteProject1 {\n onDeleteProject1 {\n __typename\n id\n name\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteProject1", type: .object(OnDeleteProject1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteProject1: OnDeleteProject1? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteProject1": onDeleteProject1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteProject1": onDeleteProject1.flatMap(\.snapshot)]) } - + public var onDeleteProject1: OnDeleteProject1? { get { return (snapshot["onDeleteProject1"] as? Snapshot).flatMap { OnDeleteProject1(snapshot: $0) } @@ -33150,10 +33158,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteProject1") } } - + public struct OnDeleteProject1: GraphQLSelectionSet { public static let possibleTypes = ["Project1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -33162,17 +33170,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project1", "id": id, "name": name, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -33181,7 +33189,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -33190,7 +33198,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -33199,7 +33207,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -33208,7 +33216,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -33217,7 +33225,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -33226,10 +33234,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -33237,17 +33245,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -33256,7 +33264,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -33265,7 +33273,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -33274,7 +33282,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -33283,7 +33291,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -33296,31 +33304,31 @@ public struct APISwift { } } } - + public final class OnCreateTeam1Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreateTeam1 {\n onCreateTeam1 {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateTeam1", type: .object(OnCreateTeam1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateTeam1: OnCreateTeam1? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateTeam1": onCreateTeam1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateTeam1": onCreateTeam1.flatMap(\.snapshot)]) } - + public var onCreateTeam1: OnCreateTeam1? { get { return (snapshot["onCreateTeam1"] as? Snapshot).flatMap { OnCreateTeam1(snapshot: $0) } @@ -33329,10 +33337,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateTeam1") } } - + public struct OnCreateTeam1: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -33340,17 +33348,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -33359,7 +33367,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -33368,7 +33376,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -33377,7 +33385,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -33386,7 +33394,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -33398,31 +33406,31 @@ public struct APISwift { } } } - + public final class OnUpdateTeam1Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateTeam1 {\n onUpdateTeam1 {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateTeam1", type: .object(OnUpdateTeam1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateTeam1: OnUpdateTeam1? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateTeam1": onUpdateTeam1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateTeam1": onUpdateTeam1.flatMap(\.snapshot)]) } - + public var onUpdateTeam1: OnUpdateTeam1? { get { return (snapshot["onUpdateTeam1"] as? Snapshot).flatMap { OnUpdateTeam1(snapshot: $0) } @@ -33431,10 +33439,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateTeam1") } } - + public struct OnUpdateTeam1: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -33442,17 +33450,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -33461,7 +33469,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -33470,7 +33478,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -33479,7 +33487,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -33488,7 +33496,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -33500,31 +33508,31 @@ public struct APISwift { } } } - + public final class OnDeleteTeam1Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteTeam1 {\n onDeleteTeam1 {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteTeam1", type: .object(OnDeleteTeam1.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteTeam1: OnDeleteTeam1? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteTeam1": onDeleteTeam1.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteTeam1": onDeleteTeam1.flatMap(\.snapshot)]) } - + public var onDeleteTeam1: OnDeleteTeam1? { get { return (snapshot["onDeleteTeam1"] as? Snapshot).flatMap { OnDeleteTeam1(snapshot: $0) } @@ -33533,10 +33541,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteTeam1") } } - + public struct OnDeleteTeam1: GraphQLSelectionSet { public static let possibleTypes = ["Team1"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -33544,17 +33552,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team1", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -33563,7 +33571,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -33572,7 +33580,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -33581,7 +33589,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -33590,7 +33598,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -33602,31 +33610,31 @@ public struct APISwift { } } } - + public final class OnCreateProject2Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreateProject2 {\n onCreateProject2 {\n __typename\n id\n name\n teamID\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateProject2", type: .object(OnCreateProject2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateProject2: OnCreateProject2? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateProject2": onCreateProject2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateProject2": onCreateProject2.flatMap(\.snapshot)]) } - + public var onCreateProject2: OnCreateProject2? { get { return (snapshot["onCreateProject2"] as? Snapshot).flatMap { OnCreateProject2(snapshot: $0) } @@ -33635,10 +33643,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateProject2") } } - + public struct OnCreateProject2: GraphQLSelectionSet { public static let possibleTypes = ["Project2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -33648,17 +33656,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, teamId: GraphQLID, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -33667,7 +33675,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -33676,7 +33684,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -33685,7 +33693,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var teamId: GraphQLID { get { return snapshot["teamID"]! as! GraphQLID @@ -33694,7 +33702,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "teamID") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -33703,7 +33711,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -33712,7 +33720,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -33721,10 +33729,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -33732,17 +33740,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -33751,7 +33759,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -33760,7 +33768,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -33769,7 +33777,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -33778,7 +33786,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -33791,31 +33799,31 @@ public struct APISwift { } } } - + public final class OnUpdateProject2Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateProject2 {\n onUpdateProject2 {\n __typename\n id\n name\n teamID\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateProject2", type: .object(OnUpdateProject2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateProject2: OnUpdateProject2? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateProject2": onUpdateProject2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateProject2": onUpdateProject2.flatMap(\.snapshot)]) } - + public var onUpdateProject2: OnUpdateProject2? { get { return (snapshot["onUpdateProject2"] as? Snapshot).flatMap { OnUpdateProject2(snapshot: $0) } @@ -33824,10 +33832,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateProject2") } } - + public struct OnUpdateProject2: GraphQLSelectionSet { public static let possibleTypes = ["Project2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -33837,17 +33845,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, teamId: GraphQLID, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -33856,7 +33864,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -33865,7 +33873,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -33874,7 +33882,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var teamId: GraphQLID { get { return snapshot["teamID"]! as! GraphQLID @@ -33883,7 +33891,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "teamID") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -33892,7 +33900,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -33901,7 +33909,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -33910,10 +33918,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -33921,17 +33929,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -33940,7 +33948,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -33949,7 +33957,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -33958,7 +33966,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -33967,7 +33975,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -33980,31 +33988,31 @@ public struct APISwift { } } } - + public final class OnDeleteProject2Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteProject2 {\n onDeleteProject2 {\n __typename\n id\n name\n teamID\n team {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteProject2", type: .object(OnDeleteProject2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteProject2: OnDeleteProject2? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteProject2": onDeleteProject2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteProject2": onDeleteProject2.flatMap(\.snapshot)]) } - + public var onDeleteProject2: OnDeleteProject2? { get { return (snapshot["onDeleteProject2"] as? Snapshot).flatMap { OnDeleteProject2(snapshot: $0) } @@ -34013,10 +34021,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteProject2") } } - + public struct OnDeleteProject2: GraphQLSelectionSet { public static let possibleTypes = ["Project2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -34026,17 +34034,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String? = nil, teamId: GraphQLID, team: Team? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Project2", "id": id, "name": name, "teamID": teamId, "team": team.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -34045,7 +34053,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -34054,7 +34062,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return snapshot["name"] as? String @@ -34063,7 +34071,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var teamId: GraphQLID { get { return snapshot["teamID"]! as! GraphQLID @@ -34072,7 +34080,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "teamID") } } - + public var team: Team? { get { return (snapshot["team"] as? Snapshot).flatMap { Team(snapshot: $0) } @@ -34081,7 +34089,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "team") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -34090,7 +34098,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -34099,10 +34107,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Team: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -34110,17 +34118,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -34129,7 +34137,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -34138,7 +34146,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -34147,7 +34155,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -34156,7 +34164,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -34169,31 +34177,31 @@ public struct APISwift { } } } - + public final class OnCreateTeam2Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreateTeam2 {\n onCreateTeam2 {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateTeam2", type: .object(OnCreateTeam2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateTeam2: OnCreateTeam2? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateTeam2": onCreateTeam2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateTeam2": onCreateTeam2.flatMap(\.snapshot)]) } - + public var onCreateTeam2: OnCreateTeam2? { get { return (snapshot["onCreateTeam2"] as? Snapshot).flatMap { OnCreateTeam2(snapshot: $0) } @@ -34202,10 +34210,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateTeam2") } } - + public struct OnCreateTeam2: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -34213,17 +34221,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -34232,7 +34240,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -34241,7 +34249,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -34250,7 +34258,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -34259,7 +34267,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -34271,31 +34279,31 @@ public struct APISwift { } } } - + public final class OnUpdateTeam2Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateTeam2 {\n onUpdateTeam2 {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateTeam2", type: .object(OnUpdateTeam2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateTeam2: OnUpdateTeam2? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateTeam2": onUpdateTeam2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateTeam2": onUpdateTeam2.flatMap(\.snapshot)]) } - + public var onUpdateTeam2: OnUpdateTeam2? { get { return (snapshot["onUpdateTeam2"] as? Snapshot).flatMap { OnUpdateTeam2(snapshot: $0) } @@ -34304,10 +34312,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateTeam2") } } - + public struct OnUpdateTeam2: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -34315,17 +34323,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -34334,7 +34342,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -34343,7 +34351,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -34352,7 +34360,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -34361,7 +34369,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -34373,31 +34381,31 @@ public struct APISwift { } } } - + public final class OnDeleteTeam2Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteTeam2 {\n onDeleteTeam2 {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteTeam2", type: .object(OnDeleteTeam2.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteTeam2: OnDeleteTeam2? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteTeam2": onDeleteTeam2.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteTeam2": onDeleteTeam2.flatMap(\.snapshot)]) } - + public var onDeleteTeam2: OnDeleteTeam2? { get { return (snapshot["onDeleteTeam2"] as? Snapshot).flatMap { OnDeleteTeam2(snapshot: $0) } @@ -34406,10 +34414,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteTeam2") } } - + public struct OnDeleteTeam2: GraphQLSelectionSet { public static let possibleTypes = ["Team2"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -34417,17 +34425,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Team2", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -34436,7 +34444,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -34445,7 +34453,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -34454,7 +34462,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -34463,7 +34471,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -34475,31 +34483,31 @@ public struct APISwift { } } } - + public final class OnCreatePost3Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreatePost3 {\n onCreatePost3 {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreatePost3", type: .object(OnCreatePost3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreatePost3: OnCreatePost3? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreatePost3": onCreatePost3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreatePost3": onCreatePost3.flatMap(\.snapshot)]) } - + public var onCreatePost3: OnCreatePost3? { get { return (snapshot["onCreatePost3"] as? Snapshot).flatMap { OnCreatePost3(snapshot: $0) } @@ -34508,10 +34516,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreatePost3") } } - + public struct OnCreatePost3: GraphQLSelectionSet { public static let possibleTypes = ["Post3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -34520,17 +34528,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -34539,7 +34547,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -34548,7 +34556,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -34557,7 +34565,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -34566,7 +34574,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -34575,7 +34583,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -34584,26 +34592,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment3Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -34612,16 +34620,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -34630,10 +34638,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -34642,17 +34650,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -34661,7 +34669,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -34670,7 +34678,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -34679,7 +34687,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -34688,7 +34696,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -34697,7 +34705,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -34711,31 +34719,31 @@ public struct APISwift { } } } - + public final class OnUpdatePost3Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdatePost3 {\n onUpdatePost3 {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdatePost3", type: .object(OnUpdatePost3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdatePost3: OnUpdatePost3? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdatePost3": onUpdatePost3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdatePost3": onUpdatePost3.flatMap(\.snapshot)]) } - + public var onUpdatePost3: OnUpdatePost3? { get { return (snapshot["onUpdatePost3"] as? Snapshot).flatMap { OnUpdatePost3(snapshot: $0) } @@ -34744,10 +34752,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdatePost3") } } - + public struct OnUpdatePost3: GraphQLSelectionSet { public static let possibleTypes = ["Post3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -34756,17 +34764,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -34775,7 +34783,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -34784,7 +34792,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -34793,7 +34801,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -34802,7 +34810,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -34811,7 +34819,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -34820,26 +34828,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment3Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -34848,16 +34856,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -34866,10 +34874,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -34878,17 +34886,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -34897,7 +34905,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -34906,7 +34914,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -34915,7 +34923,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -34924,7 +34932,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -34933,7 +34941,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -34947,31 +34955,31 @@ public struct APISwift { } } } - + public final class OnDeletePost3Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeletePost3 {\n onDeletePost3 {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeletePost3", type: .object(OnDeletePost3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeletePost3: OnDeletePost3? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeletePost3": onDeletePost3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeletePost3": onDeletePost3.flatMap(\.snapshot)]) } - + public var onDeletePost3: OnDeletePost3? { get { return (snapshot["onDeletePost3"] as? Snapshot).flatMap { OnDeletePost3(snapshot: $0) } @@ -34980,10 +34988,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeletePost3") } } - + public struct OnDeletePost3: GraphQLSelectionSet { public static let possibleTypes = ["Post3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -34992,17 +35000,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post3", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -35011,7 +35019,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -35020,7 +35028,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -35029,7 +35037,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -35038,7 +35046,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -35047,7 +35055,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -35056,26 +35064,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment3Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment3Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -35084,16 +35092,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -35102,10 +35110,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -35114,17 +35122,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -35133,7 +35141,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -35142,7 +35150,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -35151,7 +35159,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -35160,7 +35168,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -35169,7 +35177,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -35183,31 +35191,31 @@ public struct APISwift { } } } - + public final class OnCreateComment3Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreateComment3 {\n onCreateComment3 {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateComment3", type: .object(OnCreateComment3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateComment3: OnCreateComment3? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateComment3": onCreateComment3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateComment3": onCreateComment3.flatMap(\.snapshot)]) } - + public var onCreateComment3: OnCreateComment3? { get { return (snapshot["onCreateComment3"] as? Snapshot).flatMap { OnCreateComment3(snapshot: $0) } @@ -35216,10 +35224,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateComment3") } } - + public struct OnCreateComment3: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -35228,17 +35236,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -35247,7 +35255,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -35256,7 +35264,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -35265,7 +35273,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -35274,7 +35282,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -35283,7 +35291,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -35295,31 +35303,31 @@ public struct APISwift { } } } - + public final class OnUpdateComment3Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateComment3 {\n onUpdateComment3 {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateComment3", type: .object(OnUpdateComment3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateComment3: OnUpdateComment3? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateComment3": onUpdateComment3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateComment3": onUpdateComment3.flatMap(\.snapshot)]) } - + public var onUpdateComment3: OnUpdateComment3? { get { return (snapshot["onUpdateComment3"] as? Snapshot).flatMap { OnUpdateComment3(snapshot: $0) } @@ -35328,10 +35336,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateComment3") } } - + public struct OnUpdateComment3: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -35340,17 +35348,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -35359,7 +35367,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -35368,7 +35376,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -35377,7 +35385,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -35386,7 +35394,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -35395,7 +35403,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -35407,31 +35415,31 @@ public struct APISwift { } } } - + public final class OnDeleteComment3Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteComment3 {\n onDeleteComment3 {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteComment3", type: .object(OnDeleteComment3.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteComment3: OnDeleteComment3? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteComment3": onDeleteComment3.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteComment3": onDeleteComment3.flatMap(\.snapshot)]) } - + public var onDeleteComment3: OnDeleteComment3? { get { return (snapshot["onDeleteComment3"] as? Snapshot).flatMap { OnDeleteComment3(snapshot: $0) } @@ -35440,10 +35448,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteComment3") } } - + public struct OnDeleteComment3: GraphQLSelectionSet { public static let possibleTypes = ["Comment3"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -35452,17 +35460,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment3", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -35471,7 +35479,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -35480,7 +35488,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -35489,7 +35497,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -35498,7 +35506,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -35507,7 +35515,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -35519,31 +35527,31 @@ public struct APISwift { } } } - + public final class OnCreatePost4Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreatePost4 {\n onCreatePost4 {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreatePost4", type: .object(OnCreatePost4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreatePost4: OnCreatePost4? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreatePost4": onCreatePost4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreatePost4": onCreatePost4.flatMap(\.snapshot)]) } - + public var onCreatePost4: OnCreatePost4? { get { return (snapshot["onCreatePost4"] as? Snapshot).flatMap { OnCreatePost4(snapshot: $0) } @@ -35552,10 +35560,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreatePost4") } } - + public struct OnCreatePost4: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -35564,17 +35572,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -35583,7 +35591,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -35592,7 +35600,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -35601,7 +35609,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -35610,7 +35618,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -35619,7 +35627,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -35628,26 +35636,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -35656,16 +35664,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -35674,10 +35682,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -35686,17 +35694,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -35705,7 +35713,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -35714,7 +35722,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -35723,7 +35731,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -35732,7 +35740,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -35741,7 +35749,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -35755,31 +35763,31 @@ public struct APISwift { } } } - + public final class OnUpdatePost4Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdatePost4 {\n onUpdatePost4 {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdatePost4", type: .object(OnUpdatePost4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdatePost4: OnUpdatePost4? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdatePost4": onUpdatePost4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdatePost4": onUpdatePost4.flatMap(\.snapshot)]) } - + public var onUpdatePost4: OnUpdatePost4? { get { return (snapshot["onUpdatePost4"] as? Snapshot).flatMap { OnUpdatePost4(snapshot: $0) } @@ -35788,10 +35796,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdatePost4") } } - + public struct OnUpdatePost4: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -35800,17 +35808,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -35819,7 +35827,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -35828,7 +35836,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -35837,7 +35845,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -35846,7 +35854,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -35855,7 +35863,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -35864,26 +35872,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -35892,16 +35900,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -35910,10 +35918,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -35922,17 +35930,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -35941,7 +35949,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -35950,7 +35958,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -35959,7 +35967,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -35968,7 +35976,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -35977,7 +35985,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -35991,31 +35999,31 @@ public struct APISwift { } } } - + public final class OnDeletePost4Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeletePost4 {\n onDeletePost4 {\n __typename\n id\n title\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeletePost4", type: .object(OnDeletePost4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeletePost4: OnDeletePost4? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeletePost4": onDeletePost4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeletePost4": onDeletePost4.flatMap(\.snapshot)]) } - + public var onDeletePost4: OnDeletePost4? { get { return (snapshot["onDeletePost4"] as? Snapshot).flatMap { OnDeletePost4(snapshot: $0) } @@ -36024,10 +36032,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeletePost4") } } - + public struct OnDeletePost4: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -36036,17 +36044,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36055,7 +36063,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -36064,7 +36072,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -36073,7 +36081,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -36082,7 +36090,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -36091,7 +36099,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -36100,26 +36108,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment4Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36128,16 +36136,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -36146,10 +36154,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -36158,17 +36166,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36177,7 +36185,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -36186,7 +36194,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -36195,7 +36203,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -36204,7 +36212,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -36213,7 +36221,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -36227,31 +36235,31 @@ public struct APISwift { } } } - + public final class OnCreateComment4Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreateComment4 {\n onCreateComment4 {\n __typename\n id\n postID\n content\n post {\n __typename\n id\n title\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateComment4", type: .object(OnCreateComment4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateComment4: OnCreateComment4? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateComment4": onCreateComment4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateComment4": onCreateComment4.flatMap(\.snapshot)]) } - + public var onCreateComment4: OnCreateComment4? { get { return (snapshot["onCreateComment4"] as? Snapshot).flatMap { OnCreateComment4(snapshot: $0) } @@ -36260,10 +36268,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateComment4") } } - + public struct OnCreateComment4: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -36273,17 +36281,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, post: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36292,7 +36300,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -36301,7 +36309,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -36310,7 +36318,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -36319,7 +36327,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -36328,7 +36336,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -36337,7 +36345,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -36346,10 +36354,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -36358,17 +36366,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36377,7 +36385,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -36386,7 +36394,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -36395,7 +36403,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -36404,7 +36412,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -36413,7 +36421,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -36422,25 +36430,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment4Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36449,7 +36457,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -36463,31 +36471,31 @@ public struct APISwift { } } } - + public final class OnUpdateComment4Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateComment4 {\n onUpdateComment4 {\n __typename\n id\n postID\n content\n post {\n __typename\n id\n title\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateComment4", type: .object(OnUpdateComment4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateComment4: OnUpdateComment4? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateComment4": onUpdateComment4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateComment4": onUpdateComment4.flatMap(\.snapshot)]) } - + public var onUpdateComment4: OnUpdateComment4? { get { return (snapshot["onUpdateComment4"] as? Snapshot).flatMap { OnUpdateComment4(snapshot: $0) } @@ -36496,10 +36504,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateComment4") } } - + public struct OnUpdateComment4: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -36509,17 +36517,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, post: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36528,7 +36536,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -36537,7 +36545,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -36546,7 +36554,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -36555,7 +36563,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -36564,7 +36572,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -36573,7 +36581,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -36582,10 +36590,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -36594,17 +36602,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36613,7 +36621,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -36622,7 +36630,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -36631,7 +36639,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -36640,7 +36648,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -36649,7 +36657,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -36658,25 +36666,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment4Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36685,7 +36693,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -36699,31 +36707,31 @@ public struct APISwift { } } } - + public final class OnDeleteComment4Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteComment4 {\n onDeleteComment4 {\n __typename\n id\n postID\n content\n post {\n __typename\n id\n title\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteComment4", type: .object(OnDeleteComment4.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteComment4: OnDeleteComment4? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteComment4": onDeleteComment4.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteComment4": onDeleteComment4.flatMap(\.snapshot)]) } - + public var onDeleteComment4: OnDeleteComment4? { get { return (snapshot["onDeleteComment4"] as? Snapshot).flatMap { OnDeleteComment4(snapshot: $0) } @@ -36732,10 +36740,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteComment4") } } - + public struct OnDeleteComment4: GraphQLSelectionSet { public static let possibleTypes = ["Comment4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -36745,17 +36753,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, post: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment4", "id": id, "postID": postId, "content": content, "post": post.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36764,7 +36772,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -36773,7 +36781,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -36782,7 +36790,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -36791,7 +36799,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -36800,7 +36808,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -36809,7 +36817,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -36818,10 +36826,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post4"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -36830,17 +36838,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post4", "id": id, "title": title, "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36849,7 +36857,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -36858,7 +36866,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -36867,7 +36875,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -36876,7 +36884,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -36885,7 +36893,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -36894,25 +36902,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment4Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment4Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36921,7 +36929,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -36935,31 +36943,31 @@ public struct APISwift { } } } - + public final class OnCreatePost5Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreatePost5 {\n onCreatePost5 {\n __typename\n id\n title\n editors {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreatePost5", type: .object(OnCreatePost5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreatePost5: OnCreatePost5? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreatePost5": onCreatePost5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreatePost5": onCreatePost5.flatMap(\.snapshot)]) } - + public var onCreatePost5: OnCreatePost5? { get { return (snapshot["onCreatePost5"] as? Snapshot).flatMap { OnCreatePost5(snapshot: $0) } @@ -36968,10 +36976,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreatePost5") } } - + public struct OnCreatePost5: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -36980,17 +36988,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -36999,7 +37007,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -37008,7 +37016,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -37017,7 +37025,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -37026,7 +37034,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -37035,7 +37043,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -37044,26 +37052,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37072,16 +37080,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -37090,10 +37098,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -37102,17 +37110,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37121,7 +37129,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -37130,7 +37138,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -37139,7 +37147,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -37148,7 +37156,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -37157,7 +37165,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -37171,31 +37179,31 @@ public struct APISwift { } } } - + public final class OnUpdatePost5Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdatePost5 {\n onUpdatePost5 {\n __typename\n id\n title\n editors {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdatePost5", type: .object(OnUpdatePost5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdatePost5: OnUpdatePost5? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdatePost5": onUpdatePost5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdatePost5": onUpdatePost5.flatMap(\.snapshot)]) } - + public var onUpdatePost5: OnUpdatePost5? { get { return (snapshot["onUpdatePost5"] as? Snapshot).flatMap { OnUpdatePost5(snapshot: $0) } @@ -37204,10 +37212,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdatePost5") } } - + public struct OnUpdatePost5: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -37216,17 +37224,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37235,7 +37243,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -37244,7 +37252,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -37253,7 +37261,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -37262,7 +37270,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -37271,7 +37279,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -37280,26 +37288,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37308,16 +37316,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -37326,10 +37334,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -37338,17 +37346,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37357,7 +37365,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -37366,7 +37374,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -37375,7 +37383,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -37384,7 +37392,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -37393,7 +37401,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -37407,31 +37415,31 @@ public struct APISwift { } } } - + public final class OnDeletePost5Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeletePost5 {\n onDeletePost5 {\n __typename\n id\n title\n editors {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeletePost5", type: .object(OnDeletePost5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeletePost5: OnDeletePost5? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeletePost5": onDeletePost5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeletePost5": onDeletePost5.flatMap(\.snapshot)]) } - + public var onDeletePost5: OnDeletePost5? { get { return (snapshot["onDeletePost5"] as? Snapshot).flatMap { OnDeletePost5(snapshot: $0) } @@ -37440,10 +37448,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeletePost5") } } - + public struct OnDeletePost5: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -37452,17 +37460,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37471,7 +37479,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -37480,7 +37488,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -37489,7 +37497,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -37498,7 +37506,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -37507,7 +37515,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -37516,26 +37524,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37544,16 +37552,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -37562,10 +37570,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -37574,17 +37582,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37593,7 +37601,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -37602,7 +37610,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -37611,7 +37619,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -37620,7 +37628,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -37629,7 +37637,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -37643,31 +37651,31 @@ public struct APISwift { } } } - + public final class OnCreatePostEditor5Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreatePostEditor5 {\n onCreatePostEditor5 {\n __typename\n id\n postID\n editorID\n post {\n __typename\n id\n title\n editors {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n editor {\n __typename\n id\n username\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreatePostEditor5", type: .object(OnCreatePostEditor5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreatePostEditor5: OnCreatePostEditor5? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreatePostEditor5": onCreatePostEditor5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreatePostEditor5": onCreatePostEditor5.flatMap(\.snapshot)]) } - + public var onCreatePostEditor5: OnCreatePostEditor5? { get { return (snapshot["onCreatePostEditor5"] as? Snapshot).flatMap { OnCreatePostEditor5(snapshot: $0) } @@ -37676,10 +37684,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreatePostEditor5") } } - + public struct OnCreatePostEditor5: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -37690,17 +37698,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, post: Post, editor: Editor, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "post": post.snapshot, "editor": editor.snapshot, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37709,7 +37717,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -37718,7 +37726,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -37727,7 +37735,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -37736,7 +37744,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var post: Post { get { return Post(snapshot: snapshot["post"]! as! Snapshot) @@ -37745,7 +37753,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "post") } } - + public var editor: Editor { get { return Editor(snapshot: snapshot["editor"]! as! Snapshot) @@ -37754,7 +37762,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "editor") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -37763,7 +37771,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -37772,10 +37780,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -37784,17 +37792,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37803,7 +37811,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -37812,7 +37820,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -37821,7 +37829,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -37830,7 +37838,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -37839,7 +37847,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -37848,25 +37856,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37875,7 +37883,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -37886,10 +37894,10 @@ public struct APISwift { } } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -37898,17 +37906,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37917,7 +37925,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -37926,7 +37934,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -37935,7 +37943,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -37944,7 +37952,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -37953,7 +37961,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -37962,25 +37970,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -37989,7 +37997,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -38003,31 +38011,31 @@ public struct APISwift { } } } - + public final class OnUpdatePostEditor5Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdatePostEditor5 {\n onUpdatePostEditor5 {\n __typename\n id\n postID\n editorID\n post {\n __typename\n id\n title\n editors {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n editor {\n __typename\n id\n username\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdatePostEditor5", type: .object(OnUpdatePostEditor5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdatePostEditor5: OnUpdatePostEditor5? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdatePostEditor5": onUpdatePostEditor5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdatePostEditor5": onUpdatePostEditor5.flatMap(\.snapshot)]) } - + public var onUpdatePostEditor5: OnUpdatePostEditor5? { get { return (snapshot["onUpdatePostEditor5"] as? Snapshot).flatMap { OnUpdatePostEditor5(snapshot: $0) } @@ -38036,10 +38044,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdatePostEditor5") } } - + public struct OnUpdatePostEditor5: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -38050,17 +38058,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, post: Post, editor: Editor, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "post": post.snapshot, "editor": editor.snapshot, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38069,7 +38077,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -38078,7 +38086,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -38087,7 +38095,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -38096,7 +38104,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var post: Post { get { return Post(snapshot: snapshot["post"]! as! Snapshot) @@ -38105,7 +38113,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "post") } } - + public var editor: Editor { get { return Editor(snapshot: snapshot["editor"]! as! Snapshot) @@ -38114,7 +38122,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "editor") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -38123,7 +38131,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -38132,10 +38140,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -38144,17 +38152,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38163,7 +38171,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -38172,7 +38180,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -38181,7 +38189,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -38190,7 +38198,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -38199,7 +38207,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -38208,25 +38216,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38235,7 +38243,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -38246,10 +38254,10 @@ public struct APISwift { } } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -38258,17 +38266,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38277,7 +38285,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -38286,7 +38294,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -38295,7 +38303,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -38304,7 +38312,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -38313,7 +38321,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -38322,25 +38330,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38349,7 +38357,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -38363,31 +38371,31 @@ public struct APISwift { } } } - + public final class OnDeletePostEditor5Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeletePostEditor5 {\n onDeletePostEditor5 {\n __typename\n id\n postID\n editorID\n post {\n __typename\n id\n title\n editors {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n editor {\n __typename\n id\n username\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeletePostEditor5", type: .object(OnDeletePostEditor5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeletePostEditor5: OnDeletePostEditor5? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeletePostEditor5": onDeletePostEditor5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeletePostEditor5": onDeletePostEditor5.flatMap(\.snapshot)]) } - + public var onDeletePostEditor5: OnDeletePostEditor5? { get { return (snapshot["onDeletePostEditor5"] as? Snapshot).flatMap { OnDeletePostEditor5(snapshot: $0) } @@ -38396,10 +38404,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeletePostEditor5") } } - + public struct OnDeletePostEditor5: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -38410,17 +38418,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, post: Post, editor: Editor, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "post": post.snapshot, "editor": editor.snapshot, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38429,7 +38437,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -38438,7 +38446,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -38447,7 +38455,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -38456,7 +38464,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var post: Post { get { return Post(snapshot: snapshot["post"]! as! Snapshot) @@ -38465,7 +38473,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "post") } } - + public var editor: Editor { get { return Editor(snapshot: snapshot["editor"]! as! Snapshot) @@ -38474,7 +38482,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "editor") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -38483,7 +38491,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -38492,10 +38500,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -38504,17 +38512,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, editors: Editor? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post5", "id": id, "title": title, "editors": editors.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38523,7 +38531,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -38532,7 +38540,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -38541,7 +38549,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var editors: Editor? { get { return (snapshot["editors"] as? Snapshot).flatMap { Editor(snapshot: $0) } @@ -38550,7 +38558,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "editors") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -38559,7 +38567,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -38568,25 +38576,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38595,7 +38603,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -38606,10 +38614,10 @@ public struct APISwift { } } } - + public struct Editor: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -38618,17 +38626,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38637,7 +38645,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -38646,7 +38654,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -38655,7 +38663,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -38664,7 +38672,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -38673,7 +38681,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -38682,25 +38690,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38709,7 +38717,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -38723,31 +38731,31 @@ public struct APISwift { } } } - + public final class OnCreateUser5Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreateUser5 {\n onCreateUser5 {\n __typename\n id\n username\n posts {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateUser5", type: .object(OnCreateUser5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateUser5: OnCreateUser5? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateUser5": onCreateUser5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateUser5": onCreateUser5.flatMap(\.snapshot)]) } - + public var onCreateUser5: OnCreateUser5? { get { return (snapshot["onCreateUser5"] as? Snapshot).flatMap { OnCreateUser5(snapshot: $0) } @@ -38756,10 +38764,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateUser5") } } - + public struct OnCreateUser5: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -38768,17 +38776,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38787,7 +38795,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -38796,7 +38804,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -38805,7 +38813,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -38814,7 +38822,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -38823,7 +38831,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -38832,26 +38840,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38860,16 +38868,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -38878,10 +38886,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -38890,17 +38898,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -38909,7 +38917,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -38918,7 +38926,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -38927,7 +38935,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -38936,7 +38944,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -38945,7 +38953,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -38959,31 +38967,31 @@ public struct APISwift { } } } - + public final class OnUpdateUser5Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateUser5 {\n onUpdateUser5 {\n __typename\n id\n username\n posts {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateUser5", type: .object(OnUpdateUser5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateUser5: OnUpdateUser5? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateUser5": onUpdateUser5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateUser5": onUpdateUser5.flatMap(\.snapshot)]) } - + public var onUpdateUser5: OnUpdateUser5? { get { return (snapshot["onUpdateUser5"] as? Snapshot).flatMap { OnUpdateUser5(snapshot: $0) } @@ -38992,10 +39000,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateUser5") } } - + public struct OnUpdateUser5: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -39004,17 +39012,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39023,7 +39031,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -39032,7 +39040,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -39041,7 +39049,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -39050,7 +39058,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -39059,7 +39067,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -39068,26 +39076,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39096,16 +39104,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -39114,10 +39122,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -39126,17 +39134,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39145,7 +39153,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -39154,7 +39162,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -39163,7 +39171,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -39172,7 +39180,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -39181,7 +39189,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -39195,31 +39203,31 @@ public struct APISwift { } } } - + public final class OnDeleteUser5Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteUser5 {\n onDeleteUser5 {\n __typename\n id\n username\n posts {\n __typename\n items {\n __typename\n id\n postID\n editorID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteUser5", type: .object(OnDeleteUser5.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteUser5: OnDeleteUser5? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteUser5": onDeleteUser5.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteUser5": onDeleteUser5.flatMap(\.snapshot)]) } - + public var onDeleteUser5: OnDeleteUser5? { get { return (snapshot["onDeleteUser5"] as? Snapshot).flatMap { OnDeleteUser5(snapshot: $0) } @@ -39228,10 +39236,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteUser5") } } - + public struct OnDeleteUser5: GraphQLSelectionSet { public static let possibleTypes = ["User5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -39240,17 +39248,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, username: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "User5", "id": id, "username": username, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39259,7 +39267,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -39268,7 +39276,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var username: String { get { return snapshot["username"]! as! String @@ -39277,7 +39285,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "username") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -39286,7 +39294,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -39295,7 +39303,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -39304,26 +39312,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPostEditor5Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPostEditor5Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39332,16 +39340,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -39350,10 +39358,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["PostEditor5"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -39362,17 +39370,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, editorId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "PostEditor5", "id": id, "postID": postId, "editorID": editorId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39381,7 +39389,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -39390,7 +39398,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -39399,7 +39407,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var editorId: GraphQLID { get { return snapshot["editorID"]! as! GraphQLID @@ -39408,7 +39416,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "editorID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -39417,7 +39425,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -39431,31 +39439,31 @@ public struct APISwift { } } } - + public final class OnCreateBlog6Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreateBlog6 {\n onCreateBlog6 {\n __typename\n id\n name\n posts {\n __typename\n items {\n __typename\n id\n title\n blogID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateBlog6", type: .object(OnCreateBlog6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateBlog6: OnCreateBlog6? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateBlog6": onCreateBlog6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateBlog6": onCreateBlog6.flatMap(\.snapshot)]) } - + public var onCreateBlog6: OnCreateBlog6? { get { return (snapshot["onCreateBlog6"] as? Snapshot).flatMap { OnCreateBlog6(snapshot: $0) } @@ -39464,10 +39472,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateBlog6") } } - + public struct OnCreateBlog6: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -39476,17 +39484,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39495,7 +39503,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -39504,7 +39512,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -39513,7 +39521,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -39522,7 +39530,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -39531,7 +39539,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -39540,26 +39548,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39568,16 +39576,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -39586,10 +39594,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -39598,17 +39606,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39617,7 +39625,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -39626,7 +39634,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -39635,7 +39643,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -39644,7 +39652,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -39653,7 +39661,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -39667,31 +39675,31 @@ public struct APISwift { } } } - + public final class OnUpdateBlog6Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateBlog6 {\n onUpdateBlog6 {\n __typename\n id\n name\n posts {\n __typename\n items {\n __typename\n id\n title\n blogID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateBlog6", type: .object(OnUpdateBlog6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateBlog6: OnUpdateBlog6? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateBlog6": onUpdateBlog6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateBlog6": onUpdateBlog6.flatMap(\.snapshot)]) } - + public var onUpdateBlog6: OnUpdateBlog6? { get { return (snapshot["onUpdateBlog6"] as? Snapshot).flatMap { OnUpdateBlog6(snapshot: $0) } @@ -39700,10 +39708,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateBlog6") } } - + public struct OnUpdateBlog6: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -39712,17 +39720,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39731,7 +39739,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -39740,7 +39748,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -39749,7 +39757,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -39758,7 +39766,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -39767,7 +39775,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -39776,26 +39784,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39804,16 +39812,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -39822,10 +39830,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -39834,17 +39842,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39853,7 +39861,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -39862,7 +39870,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -39871,7 +39879,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -39880,7 +39888,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -39889,7 +39897,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -39903,31 +39911,31 @@ public struct APISwift { } } } - + public final class OnDeleteBlog6Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteBlog6 {\n onDeleteBlog6 {\n __typename\n id\n name\n posts {\n __typename\n items {\n __typename\n id\n title\n blogID\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteBlog6", type: .object(OnDeleteBlog6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteBlog6: OnDeleteBlog6? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteBlog6": onDeleteBlog6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteBlog6": onDeleteBlog6.flatMap(\.snapshot)]) } - + public var onDeleteBlog6: OnDeleteBlog6? { get { return (snapshot["onDeleteBlog6"] as? Snapshot).flatMap { OnDeleteBlog6(snapshot: $0) } @@ -39936,10 +39944,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteBlog6") } } - + public struct OnDeleteBlog6: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -39948,17 +39956,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -39967,7 +39975,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -39976,7 +39984,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -39985,7 +39993,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -39994,7 +40002,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -40003,7 +40011,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -40012,26 +40020,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelPost6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40040,16 +40048,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -40058,10 +40066,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -40070,17 +40078,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40089,7 +40097,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -40098,7 +40106,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -40107,7 +40115,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -40116,7 +40124,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -40125,7 +40133,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -40139,31 +40147,31 @@ public struct APISwift { } } } - + public final class OnCreatePost6Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreatePost6 {\n onCreatePost6 {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreatePost6", type: .object(OnCreatePost6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreatePost6: OnCreatePost6? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreatePost6": onCreatePost6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreatePost6": onCreatePost6.flatMap(\.snapshot)]) } - + public var onCreatePost6: OnCreatePost6? { get { return (snapshot["onCreatePost6"] as? Snapshot).flatMap { OnCreatePost6(snapshot: $0) } @@ -40172,10 +40180,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreatePost6") } } - + public struct OnCreatePost6: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -40186,17 +40194,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40205,7 +40213,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -40214,7 +40222,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -40223,7 +40231,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -40232,7 +40240,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -40241,7 +40249,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -40250,7 +40258,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -40259,7 +40267,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -40268,10 +40276,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -40280,17 +40288,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40299,7 +40307,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -40308,7 +40316,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -40317,7 +40325,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -40326,7 +40334,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -40335,7 +40343,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -40344,25 +40352,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPost6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40371,7 +40379,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -40382,26 +40390,26 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40410,16 +40418,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -40428,10 +40436,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -40440,17 +40448,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40459,7 +40467,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -40468,7 +40476,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -40477,7 +40485,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -40486,7 +40494,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -40495,7 +40503,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -40509,31 +40517,31 @@ public struct APISwift { } } } - + public final class OnUpdatePost6Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdatePost6 {\n onUpdatePost6 {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdatePost6", type: .object(OnUpdatePost6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdatePost6: OnUpdatePost6? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdatePost6": onUpdatePost6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdatePost6": onUpdatePost6.flatMap(\.snapshot)]) } - + public var onUpdatePost6: OnUpdatePost6? { get { return (snapshot["onUpdatePost6"] as? Snapshot).flatMap { OnUpdatePost6(snapshot: $0) } @@ -40542,10 +40550,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdatePost6") } } - + public struct OnUpdatePost6: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -40556,17 +40564,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40575,7 +40583,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -40584,7 +40592,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -40593,7 +40601,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -40602,7 +40610,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -40611,7 +40619,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -40620,7 +40628,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -40629,7 +40637,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -40638,10 +40646,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -40650,17 +40658,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40669,7 +40677,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -40678,7 +40686,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -40687,7 +40695,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -40696,7 +40704,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -40705,7 +40713,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -40714,25 +40722,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPost6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40741,7 +40749,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -40752,26 +40760,26 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40780,16 +40788,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -40798,10 +40806,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -40810,17 +40818,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40829,7 +40837,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -40838,7 +40846,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -40847,7 +40855,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -40856,7 +40864,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -40865,7 +40873,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -40879,31 +40887,31 @@ public struct APISwift { } } } - + public final class OnDeletePost6Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeletePost6 {\n onDeletePost6 {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n posts {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n comments {\n __typename\n items {\n __typename\n id\n postID\n content\n createdAt\n updatedAt\n }\n nextToken\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeletePost6", type: .object(OnDeletePost6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeletePost6: OnDeletePost6? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeletePost6": onDeletePost6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeletePost6": onDeletePost6.flatMap(\.snapshot)]) } - + public var onDeletePost6: OnDeletePost6? { get { return (snapshot["onDeletePost6"] as? Snapshot).flatMap { OnDeletePost6(snapshot: $0) } @@ -40912,10 +40920,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeletePost6") } } - + public struct OnDeletePost6: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -40926,17 +40934,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -40945,7 +40953,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -40954,7 +40962,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -40963,7 +40971,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -40972,7 +40980,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -40981,7 +40989,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -40990,7 +40998,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -40999,7 +41007,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -41008,10 +41016,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -41020,17 +41028,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, posts: Post? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "posts": posts.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41039,7 +41047,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -41048,7 +41056,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -41057,7 +41065,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var posts: Post? { get { return (snapshot["posts"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -41066,7 +41074,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "posts") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -41075,7 +41083,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -41084,25 +41092,25 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["ModelPost6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelPost6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41111,7 +41119,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -41122,26 +41130,26 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelComment6Connection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41150,16 +41158,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -41168,10 +41176,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -41180,17 +41188,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, content: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41199,7 +41207,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -41208,7 +41216,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -41217,7 +41225,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -41226,7 +41234,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -41235,7 +41243,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -41249,31 +41257,31 @@ public struct APISwift { } } } - + public final class OnCreateComment6Subscription: GraphQLSubscription { public static let operationString = "subscription OnCreateComment6 {\n onCreateComment6 {\n __typename\n id\n postID\n post {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n content\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateComment6", type: .object(OnCreateComment6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateComment6: OnCreateComment6? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateComment6": onCreateComment6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateComment6": onCreateComment6.flatMap(\.snapshot)]) } - + public var onCreateComment6: OnCreateComment6? { get { return (snapshot["onCreateComment6"] as? Snapshot).flatMap { OnCreateComment6(snapshot: $0) } @@ -41282,10 +41290,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateComment6") } } - + public struct OnCreateComment6: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -41295,17 +41303,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, post: Post? = nil, content: String, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap { $0.snapshot }, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap(\.snapshot), "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41314,7 +41322,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -41323,7 +41331,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -41332,7 +41340,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -41341,7 +41349,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -41350,7 +41358,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -41359,7 +41367,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -41368,10 +41376,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -41382,17 +41390,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41401,7 +41409,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -41410,7 +41418,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -41419,7 +41427,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -41428,7 +41436,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -41437,7 +41445,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -41446,7 +41454,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -41455,7 +41463,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -41464,10 +41472,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -41475,17 +41483,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41494,7 +41502,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -41503,7 +41511,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -41512,7 +41520,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -41521,7 +41529,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -41531,25 +41539,25 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41558,7 +41566,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -41572,31 +41580,31 @@ public struct APISwift { } } } - + public final class OnUpdateComment6Subscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateComment6 {\n onUpdateComment6 {\n __typename\n id\n postID\n post {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n content\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateComment6", type: .object(OnUpdateComment6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateComment6: OnUpdateComment6? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateComment6": onUpdateComment6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateComment6": onUpdateComment6.flatMap(\.snapshot)]) } - + public var onUpdateComment6: OnUpdateComment6? { get { return (snapshot["onUpdateComment6"] as? Snapshot).flatMap { OnUpdateComment6(snapshot: $0) } @@ -41605,10 +41613,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateComment6") } } - + public struct OnUpdateComment6: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -41618,17 +41626,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, post: Post? = nil, content: String, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap { $0.snapshot }, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap(\.snapshot), "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41637,7 +41645,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -41646,7 +41654,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -41655,7 +41663,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -41664,7 +41672,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -41673,7 +41681,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -41682,7 +41690,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -41691,10 +41699,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -41705,17 +41713,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41724,7 +41732,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -41733,7 +41741,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -41742,7 +41750,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -41751,7 +41759,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -41760,7 +41768,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -41769,7 +41777,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -41778,7 +41786,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -41787,10 +41795,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -41798,17 +41806,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41817,7 +41825,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -41826,7 +41834,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -41835,7 +41843,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -41844,7 +41852,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -41854,25 +41862,25 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41881,7 +41889,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -41895,31 +41903,31 @@ public struct APISwift { } } } - + public final class OnDeleteComment6Subscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteComment6 {\n onDeleteComment6 {\n __typename\n id\n postID\n post {\n __typename\n id\n title\n blogID\n blog {\n __typename\n id\n name\n createdAt\n updatedAt\n }\n comments {\n __typename\n nextToken\n }\n createdAt\n updatedAt\n }\n content\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteComment6", type: .object(OnDeleteComment6.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteComment6: OnDeleteComment6? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteComment6": onDeleteComment6.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteComment6": onDeleteComment6.flatMap(\.snapshot)]) } - + public var onDeleteComment6: OnDeleteComment6? { get { return (snapshot["onDeleteComment6"] as? Snapshot).flatMap { OnDeleteComment6(snapshot: $0) } @@ -41928,10 +41936,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteComment6") } } - + public struct OnDeleteComment6: GraphQLSelectionSet { public static let possibleTypes = ["Comment6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -41941,17 +41949,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, postId: GraphQLID, post: Post? = nil, content: String, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap { $0.snapshot }, "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Comment6", "id": id, "postID": postId, "post": post.flatMap(\.snapshot), "content": content, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -41960,7 +41968,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -41969,7 +41977,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var postId: GraphQLID { get { return snapshot["postID"]! as! GraphQLID @@ -41978,7 +41986,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "postID") } } - + public var post: Post? { get { return (snapshot["post"] as? Snapshot).flatMap { Post(snapshot: $0) } @@ -41987,7 +41995,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "post") } } - + public var content: String { get { return snapshot["content"]! as! String @@ -41996,7 +42004,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "content") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -42005,7 +42013,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -42014,10 +42022,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Post: GraphQLSelectionSet { public static let possibleTypes = ["Post6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -42028,17 +42036,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, title: String, blogId: GraphQLID, blog: Blog? = nil, comments: Comment? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap { $0.snapshot }, "comments": comments.flatMap { $0.snapshot }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "Post6", "id": id, "title": title, "blogID": blogId, "blog": blog.flatMap(\.snapshot), "comments": comments.flatMap(\.snapshot), "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -42047,7 +42055,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -42056,7 +42064,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var title: String { get { return snapshot["title"]! as! String @@ -42065,7 +42073,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "title") } } - + public var blogId: GraphQLID { get { return snapshot["blogID"]! as! GraphQLID @@ -42074,7 +42082,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "blogID") } } - + public var blog: Blog? { get { return (snapshot["blog"] as? Snapshot).flatMap { Blog(snapshot: $0) } @@ -42083,7 +42091,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "blog") } } - + public var comments: Comment? { get { return (snapshot["comments"] as? Snapshot).flatMap { Comment(snapshot: $0) } @@ -42092,7 +42100,7 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "comments") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -42101,7 +42109,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -42110,10 +42118,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct Blog: GraphQLSelectionSet { public static let possibleTypes = ["Blog6"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -42121,17 +42129,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Blog6", "id": id, "name": name, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -42140,7 +42148,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -42149,7 +42157,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -42158,7 +42166,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -42167,7 +42175,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -42177,25 +42185,25 @@ public struct APISwift { } } } - + public struct Comment: GraphQLSelectionSet { public static let possibleTypes = ["ModelComment6Connection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(nextToken: String? = nil) { self.init(snapshot: ["__typename": "ModelComment6Connection", "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -42204,7 +42212,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -42218,31 +42226,31 @@ public struct APISwift { } } } - + public final class OnCreateScalarContainerSubscription: GraphQLSubscription { public static let operationString = "subscription OnCreateScalarContainer {\n onCreateScalarContainer {\n __typename\n id\n myString\n myInt\n myDouble\n myBool\n myDate\n myTime\n myDateTime\n myTimeStamp\n myEmail\n myJSON\n myPhone\n myURL\n myIPAddress\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateScalarContainer", type: .object(OnCreateScalarContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateScalarContainer: OnCreateScalarContainer? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateScalarContainer": onCreateScalarContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateScalarContainer": onCreateScalarContainer.flatMap(\.snapshot)]) } - + public var onCreateScalarContainer: OnCreateScalarContainer? { get { return (snapshot["onCreateScalarContainer"] as? Snapshot).flatMap { OnCreateScalarContainer(snapshot: $0) } @@ -42251,10 +42259,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateScalarContainer") } } - + public struct OnCreateScalarContainer: GraphQLSelectionSet { public static let possibleTypes = ["ScalarContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -42274,17 +42282,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, myString: String? = nil, myInt: Int? = nil, myDouble: Double? = nil, myBool: Bool? = nil, myDate: String? = nil, myTime: String? = nil, myDateTime: String? = nil, myTimeStamp: Int? = nil, myEmail: String? = nil, myJson: String? = nil, myPhone: String? = nil, myUrl: String? = nil, myIpAddress: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ScalarContainer", "id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -42293,7 +42301,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -42302,7 +42310,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var myString: String? { get { return snapshot["myString"] as? String @@ -42311,7 +42319,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myString") } } - + public var myInt: Int? { get { return snapshot["myInt"] as? Int @@ -42320,7 +42328,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myInt") } } - + public var myDouble: Double? { get { return snapshot["myDouble"] as? Double @@ -42329,7 +42337,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDouble") } } - + public var myBool: Bool? { get { return snapshot["myBool"] as? Bool @@ -42338,7 +42346,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myBool") } } - + public var myDate: String? { get { return snapshot["myDate"] as? String @@ -42347,7 +42355,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDate") } } - + public var myTime: String? { get { return snapshot["myTime"] as? String @@ -42356,7 +42364,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTime") } } - + public var myDateTime: String? { get { return snapshot["myDateTime"] as? String @@ -42365,7 +42373,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDateTime") } } - + public var myTimeStamp: Int? { get { return snapshot["myTimeStamp"] as? Int @@ -42374,7 +42382,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTimeStamp") } } - + public var myEmail: String? { get { return snapshot["myEmail"] as? String @@ -42383,7 +42391,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myEmail") } } - + public var myJson: String? { get { return snapshot["myJSON"] as? String @@ -42392,7 +42400,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myJSON") } } - + public var myPhone: String? { get { return snapshot["myPhone"] as? String @@ -42401,7 +42409,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myPhone") } } - + public var myUrl: String? { get { return snapshot["myURL"] as? String @@ -42410,7 +42418,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myURL") } } - + public var myIpAddress: String? { get { return snapshot["myIPAddress"] as? String @@ -42419,7 +42427,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myIPAddress") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -42428,7 +42436,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -42440,31 +42448,31 @@ public struct APISwift { } } } - + public final class OnUpdateScalarContainerSubscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateScalarContainer {\n onUpdateScalarContainer {\n __typename\n id\n myString\n myInt\n myDouble\n myBool\n myDate\n myTime\n myDateTime\n myTimeStamp\n myEmail\n myJSON\n myPhone\n myURL\n myIPAddress\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateScalarContainer", type: .object(OnUpdateScalarContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateScalarContainer: OnUpdateScalarContainer? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateScalarContainer": onUpdateScalarContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateScalarContainer": onUpdateScalarContainer.flatMap(\.snapshot)]) } - + public var onUpdateScalarContainer: OnUpdateScalarContainer? { get { return (snapshot["onUpdateScalarContainer"] as? Snapshot).flatMap { OnUpdateScalarContainer(snapshot: $0) } @@ -42473,10 +42481,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateScalarContainer") } } - + public struct OnUpdateScalarContainer: GraphQLSelectionSet { public static let possibleTypes = ["ScalarContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -42496,17 +42504,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, myString: String? = nil, myInt: Int? = nil, myDouble: Double? = nil, myBool: Bool? = nil, myDate: String? = nil, myTime: String? = nil, myDateTime: String? = nil, myTimeStamp: Int? = nil, myEmail: String? = nil, myJson: String? = nil, myPhone: String? = nil, myUrl: String? = nil, myIpAddress: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ScalarContainer", "id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -42515,7 +42523,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -42524,7 +42532,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var myString: String? { get { return snapshot["myString"] as? String @@ -42533,7 +42541,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myString") } } - + public var myInt: Int? { get { return snapshot["myInt"] as? Int @@ -42542,7 +42550,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myInt") } } - + public var myDouble: Double? { get { return snapshot["myDouble"] as? Double @@ -42551,7 +42559,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDouble") } } - + public var myBool: Bool? { get { return snapshot["myBool"] as? Bool @@ -42560,7 +42568,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myBool") } } - + public var myDate: String? { get { return snapshot["myDate"] as? String @@ -42569,7 +42577,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDate") } } - + public var myTime: String? { get { return snapshot["myTime"] as? String @@ -42578,7 +42586,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTime") } } - + public var myDateTime: String? { get { return snapshot["myDateTime"] as? String @@ -42587,7 +42595,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDateTime") } } - + public var myTimeStamp: Int? { get { return snapshot["myTimeStamp"] as? Int @@ -42596,7 +42604,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTimeStamp") } } - + public var myEmail: String? { get { return snapshot["myEmail"] as? String @@ -42605,7 +42613,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myEmail") } } - + public var myJson: String? { get { return snapshot["myJSON"] as? String @@ -42614,7 +42622,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myJSON") } } - + public var myPhone: String? { get { return snapshot["myPhone"] as? String @@ -42623,7 +42631,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myPhone") } } - + public var myUrl: String? { get { return snapshot["myURL"] as? String @@ -42632,7 +42640,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myURL") } } - + public var myIpAddress: String? { get { return snapshot["myIPAddress"] as? String @@ -42641,7 +42649,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myIPAddress") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -42650,7 +42658,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -42662,31 +42670,31 @@ public struct APISwift { } } } - + public final class OnDeleteScalarContainerSubscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteScalarContainer {\n onDeleteScalarContainer {\n __typename\n id\n myString\n myInt\n myDouble\n myBool\n myDate\n myTime\n myDateTime\n myTimeStamp\n myEmail\n myJSON\n myPhone\n myURL\n myIPAddress\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteScalarContainer", type: .object(OnDeleteScalarContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteScalarContainer: OnDeleteScalarContainer? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteScalarContainer": onDeleteScalarContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteScalarContainer": onDeleteScalarContainer.flatMap(\.snapshot)]) } - + public var onDeleteScalarContainer: OnDeleteScalarContainer? { get { return (snapshot["onDeleteScalarContainer"] as? Snapshot).flatMap { OnDeleteScalarContainer(snapshot: $0) } @@ -42695,10 +42703,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteScalarContainer") } } - + public struct OnDeleteScalarContainer: GraphQLSelectionSet { public static let possibleTypes = ["ScalarContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -42718,17 +42726,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, myString: String? = nil, myInt: Int? = nil, myDouble: Double? = nil, myBool: Bool? = nil, myDate: String? = nil, myTime: String? = nil, myDateTime: String? = nil, myTimeStamp: Int? = nil, myEmail: String? = nil, myJson: String? = nil, myPhone: String? = nil, myUrl: String? = nil, myIpAddress: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ScalarContainer", "id": id, "myString": myString, "myInt": myInt, "myDouble": myDouble, "myBool": myBool, "myDate": myDate, "myTime": myTime, "myDateTime": myDateTime, "myTimeStamp": myTimeStamp, "myEmail": myEmail, "myJSON": myJson, "myPhone": myPhone, "myURL": myUrl, "myIPAddress": myIpAddress, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -42737,7 +42745,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -42746,7 +42754,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var myString: String? { get { return snapshot["myString"] as? String @@ -42755,7 +42763,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myString") } } - + public var myInt: Int? { get { return snapshot["myInt"] as? Int @@ -42764,7 +42772,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myInt") } } - + public var myDouble: Double? { get { return snapshot["myDouble"] as? Double @@ -42773,7 +42781,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDouble") } } - + public var myBool: Bool? { get { return snapshot["myBool"] as? Bool @@ -42782,7 +42790,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myBool") } } - + public var myDate: String? { get { return snapshot["myDate"] as? String @@ -42791,7 +42799,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDate") } } - + public var myTime: String? { get { return snapshot["myTime"] as? String @@ -42800,7 +42808,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTime") } } - + public var myDateTime: String? { get { return snapshot["myDateTime"] as? String @@ -42809,7 +42817,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myDateTime") } } - + public var myTimeStamp: Int? { get { return snapshot["myTimeStamp"] as? Int @@ -42818,7 +42826,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myTimeStamp") } } - + public var myEmail: String? { get { return snapshot["myEmail"] as? String @@ -42827,7 +42835,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myEmail") } } - + public var myJson: String? { get { return snapshot["myJSON"] as? String @@ -42836,7 +42844,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myJSON") } } - + public var myPhone: String? { get { return snapshot["myPhone"] as? String @@ -42845,7 +42853,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myPhone") } } - + public var myUrl: String? { get { return snapshot["myURL"] as? String @@ -42854,7 +42862,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myURL") } } - + public var myIpAddress: String? { get { return snapshot["myIPAddress"] as? String @@ -42863,7 +42871,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "myIPAddress") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -42872,7 +42880,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -42884,31 +42892,31 @@ public struct APISwift { } } } - + public final class OnCreateListIntContainerSubscription: GraphQLSubscription { public static let operationString = "subscription OnCreateListIntContainer {\n onCreateListIntContainer {\n __typename\n id\n test\n nullableInt\n intList\n intNullableList\n nullableIntList\n nullableIntNullableList\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateListIntContainer", type: .object(OnCreateListIntContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateListIntContainer: OnCreateListIntContainer? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateListIntContainer": onCreateListIntContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateListIntContainer": onCreateListIntContainer.flatMap(\.snapshot)]) } - + public var onCreateListIntContainer: OnCreateListIntContainer? { get { return (snapshot["onCreateListIntContainer"] as? Snapshot).flatMap { OnCreateListIntContainer(snapshot: $0) } @@ -42917,10 +42925,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateListIntContainer") } } - + public struct OnCreateListIntContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListIntContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -42933,17 +42941,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: Int, nullableInt: Int? = nil, intList: [Int], intNullableList: [Int]? = nil, nullableIntList: [Int?], nullableIntNullableList: [Int?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListIntContainer", "id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -42952,7 +42960,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -42961,7 +42969,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: Int { get { return snapshot["test"]! as! Int @@ -42970,7 +42978,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableInt: Int? { get { return snapshot["nullableInt"] as? Int @@ -42979,7 +42987,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableInt") } } - + public var intList: [Int] { get { return snapshot["intList"]! as! [Int] @@ -42988,7 +42996,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intList") } } - + public var intNullableList: [Int]? { get { return snapshot["intNullableList"] as? [Int] @@ -42997,7 +43005,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intNullableList") } } - + public var nullableIntList: [Int?] { get { return snapshot["nullableIntList"]! as! [Int?] @@ -43006,7 +43014,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntList") } } - + public var nullableIntNullableList: [Int?]? { get { return snapshot["nullableIntNullableList"] as? [Int?] @@ -43015,7 +43023,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -43024,7 +43032,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -43036,31 +43044,31 @@ public struct APISwift { } } } - + public final class OnUpdateListIntContainerSubscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateListIntContainer {\n onUpdateListIntContainer {\n __typename\n id\n test\n nullableInt\n intList\n intNullableList\n nullableIntList\n nullableIntNullableList\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateListIntContainer", type: .object(OnUpdateListIntContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateListIntContainer: OnUpdateListIntContainer? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateListIntContainer": onUpdateListIntContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateListIntContainer": onUpdateListIntContainer.flatMap(\.snapshot)]) } - + public var onUpdateListIntContainer: OnUpdateListIntContainer? { get { return (snapshot["onUpdateListIntContainer"] as? Snapshot).flatMap { OnUpdateListIntContainer(snapshot: $0) } @@ -43069,10 +43077,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateListIntContainer") } } - + public struct OnUpdateListIntContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListIntContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -43085,17 +43093,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: Int, nullableInt: Int? = nil, intList: [Int], intNullableList: [Int]? = nil, nullableIntList: [Int?], nullableIntNullableList: [Int?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListIntContainer", "id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -43104,7 +43112,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -43113,7 +43121,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: Int { get { return snapshot["test"]! as! Int @@ -43122,7 +43130,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableInt: Int? { get { return snapshot["nullableInt"] as? Int @@ -43131,7 +43139,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableInt") } } - + public var intList: [Int] { get { return snapshot["intList"]! as! [Int] @@ -43140,7 +43148,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intList") } } - + public var intNullableList: [Int]? { get { return snapshot["intNullableList"] as? [Int] @@ -43149,7 +43157,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intNullableList") } } - + public var nullableIntList: [Int?] { get { return snapshot["nullableIntList"]! as! [Int?] @@ -43158,7 +43166,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntList") } } - + public var nullableIntNullableList: [Int?]? { get { return snapshot["nullableIntNullableList"] as? [Int?] @@ -43167,7 +43175,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -43176,7 +43184,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -43188,31 +43196,31 @@ public struct APISwift { } } } - + public final class OnDeleteListIntContainerSubscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteListIntContainer {\n onDeleteListIntContainer {\n __typename\n id\n test\n nullableInt\n intList\n intNullableList\n nullableIntList\n nullableIntNullableList\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteListIntContainer", type: .object(OnDeleteListIntContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteListIntContainer: OnDeleteListIntContainer? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteListIntContainer": onDeleteListIntContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteListIntContainer": onDeleteListIntContainer.flatMap(\.snapshot)]) } - + public var onDeleteListIntContainer: OnDeleteListIntContainer? { get { return (snapshot["onDeleteListIntContainer"] as? Snapshot).flatMap { OnDeleteListIntContainer(snapshot: $0) } @@ -43221,10 +43229,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteListIntContainer") } } - + public struct OnDeleteListIntContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListIntContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -43237,17 +43245,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: Int, nullableInt: Int? = nil, intList: [Int], intNullableList: [Int]? = nil, nullableIntList: [Int?], nullableIntNullableList: [Int?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListIntContainer", "id": id, "test": test, "nullableInt": nullableInt, "intList": intList, "intNullableList": intNullableList, "nullableIntList": nullableIntList, "nullableIntNullableList": nullableIntNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -43256,7 +43264,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -43265,7 +43273,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: Int { get { return snapshot["test"]! as! Int @@ -43274,7 +43282,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableInt: Int? { get { return snapshot["nullableInt"] as? Int @@ -43283,7 +43291,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableInt") } } - + public var intList: [Int] { get { return snapshot["intList"]! as! [Int] @@ -43292,7 +43300,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intList") } } - + public var intNullableList: [Int]? { get { return snapshot["intNullableList"] as? [Int] @@ -43301,7 +43309,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "intNullableList") } } - + public var nullableIntList: [Int?] { get { return snapshot["nullableIntList"]! as! [Int?] @@ -43310,7 +43318,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntList") } } - + public var nullableIntNullableList: [Int?]? { get { return snapshot["nullableIntNullableList"] as? [Int?] @@ -43319,7 +43327,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableIntNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -43328,7 +43336,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -43340,31 +43348,31 @@ public struct APISwift { } } } - + public final class OnCreateListStringContainerSubscription: GraphQLSubscription { public static let operationString = "subscription OnCreateListStringContainer {\n onCreateListStringContainer {\n __typename\n id\n test\n nullableString\n stringList\n stringNullableList\n nullableStringList\n nullableStringNullableList\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateListStringContainer", type: .object(OnCreateListStringContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateListStringContainer: OnCreateListStringContainer? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateListStringContainer": onCreateListStringContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateListStringContainer": onCreateListStringContainer.flatMap(\.snapshot)]) } - + public var onCreateListStringContainer: OnCreateListStringContainer? { get { return (snapshot["onCreateListStringContainer"] as? Snapshot).flatMap { OnCreateListStringContainer(snapshot: $0) } @@ -43373,10 +43381,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateListStringContainer") } } - + public struct OnCreateListStringContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListStringContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -43389,17 +43397,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: String, nullableString: String? = nil, stringList: [String], stringNullableList: [String]? = nil, nullableStringList: [String?], nullableStringNullableList: [String?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListStringContainer", "id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -43408,7 +43416,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -43417,7 +43425,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: String { get { return snapshot["test"]! as! String @@ -43426,7 +43434,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableString: String? { get { return snapshot["nullableString"] as? String @@ -43435,7 +43443,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableString") } } - + public var stringList: [String] { get { return snapshot["stringList"]! as! [String] @@ -43444,7 +43452,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringList") } } - + public var stringNullableList: [String]? { get { return snapshot["stringNullableList"] as? [String] @@ -43453,7 +43461,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringNullableList") } } - + public var nullableStringList: [String?] { get { return snapshot["nullableStringList"]! as! [String?] @@ -43462,7 +43470,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringList") } } - + public var nullableStringNullableList: [String?]? { get { return snapshot["nullableStringNullableList"] as? [String?] @@ -43471,7 +43479,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -43480,7 +43488,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -43492,31 +43500,31 @@ public struct APISwift { } } } - + public final class OnUpdateListStringContainerSubscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateListStringContainer {\n onUpdateListStringContainer {\n __typename\n id\n test\n nullableString\n stringList\n stringNullableList\n nullableStringList\n nullableStringNullableList\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateListStringContainer", type: .object(OnUpdateListStringContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateListStringContainer: OnUpdateListStringContainer? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateListStringContainer": onUpdateListStringContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateListStringContainer": onUpdateListStringContainer.flatMap(\.snapshot)]) } - + public var onUpdateListStringContainer: OnUpdateListStringContainer? { get { return (snapshot["onUpdateListStringContainer"] as? Snapshot).flatMap { OnUpdateListStringContainer(snapshot: $0) } @@ -43525,10 +43533,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateListStringContainer") } } - + public struct OnUpdateListStringContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListStringContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -43541,17 +43549,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: String, nullableString: String? = nil, stringList: [String], stringNullableList: [String]? = nil, nullableStringList: [String?], nullableStringNullableList: [String?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListStringContainer", "id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -43560,7 +43568,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -43569,7 +43577,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: String { get { return snapshot["test"]! as! String @@ -43578,7 +43586,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableString: String? { get { return snapshot["nullableString"] as? String @@ -43587,7 +43595,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableString") } } - + public var stringList: [String] { get { return snapshot["stringList"]! as! [String] @@ -43596,7 +43604,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringList") } } - + public var stringNullableList: [String]? { get { return snapshot["stringNullableList"] as? [String] @@ -43605,7 +43613,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringNullableList") } } - + public var nullableStringList: [String?] { get { return snapshot["nullableStringList"]! as! [String?] @@ -43614,7 +43622,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringList") } } - + public var nullableStringNullableList: [String?]? { get { return snapshot["nullableStringNullableList"] as? [String?] @@ -43623,7 +43631,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -43632,7 +43640,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -43644,31 +43652,31 @@ public struct APISwift { } } } - + public final class OnDeleteListStringContainerSubscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteListStringContainer {\n onDeleteListStringContainer {\n __typename\n id\n test\n nullableString\n stringList\n stringNullableList\n nullableStringList\n nullableStringNullableList\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteListStringContainer", type: .object(OnDeleteListStringContainer.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteListStringContainer: OnDeleteListStringContainer? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteListStringContainer": onDeleteListStringContainer.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteListStringContainer": onDeleteListStringContainer.flatMap(\.snapshot)]) } - + public var onDeleteListStringContainer: OnDeleteListStringContainer? { get { return (snapshot["onDeleteListStringContainer"] as? Snapshot).flatMap { OnDeleteListStringContainer(snapshot: $0) } @@ -43677,10 +43685,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteListStringContainer") } } - + public struct OnDeleteListStringContainer: GraphQLSelectionSet { public static let possibleTypes = ["ListStringContainer"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -43693,17 +43701,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, test: String, nullableString: String? = nil, stringList: [String], stringNullableList: [String]? = nil, nullableStringList: [String?], nullableStringNullableList: [String?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "ListStringContainer", "id": id, "test": test, "nullableString": nullableString, "stringList": stringList, "stringNullableList": stringNullableList, "nullableStringList": nullableStringList, "nullableStringNullableList": nullableStringNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -43712,7 +43720,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -43721,7 +43729,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var test: String { get { return snapshot["test"]! as! String @@ -43730,7 +43738,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "test") } } - + public var nullableString: String? { get { return snapshot["nullableString"] as? String @@ -43739,7 +43747,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableString") } } - + public var stringList: [String] { get { return snapshot["stringList"]! as! [String] @@ -43748,7 +43756,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringList") } } - + public var stringNullableList: [String]? { get { return snapshot["stringNullableList"] as? [String] @@ -43757,7 +43765,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "stringNullableList") } } - + public var nullableStringList: [String?] { get { return snapshot["nullableStringList"]! as! [String?] @@ -43766,7 +43774,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringList") } } - + public var nullableStringNullableList: [String?]? { get { return snapshot["nullableStringNullableList"] as? [String?] @@ -43775,7 +43783,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableStringNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -43784,7 +43792,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -43796,31 +43804,31 @@ public struct APISwift { } } } - + public final class OnCreateEnumTestModelSubscription: GraphQLSubscription { public static let operationString = "subscription OnCreateEnumTestModel {\n onCreateEnumTestModel {\n __typename\n id\n enumVal\n nullableEnumVal\n enumList\n enumNullableList\n nullableEnumList\n nullableEnumNullableList\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateEnumTestModel", type: .object(OnCreateEnumTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateEnumTestModel: OnCreateEnumTestModel? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateEnumTestModel": onCreateEnumTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateEnumTestModel": onCreateEnumTestModel.flatMap(\.snapshot)]) } - + public var onCreateEnumTestModel: OnCreateEnumTestModel? { get { return (snapshot["onCreateEnumTestModel"] as? Snapshot).flatMap { OnCreateEnumTestModel(snapshot: $0) } @@ -43829,10 +43837,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateEnumTestModel") } } - + public struct OnCreateEnumTestModel: GraphQLSelectionSet { public static let possibleTypes = ["EnumTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -43845,17 +43853,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, enumVal: TestEnum, nullableEnumVal: TestEnum? = nil, enumList: [TestEnum], enumNullableList: [TestEnum]? = nil, nullableEnumList: [TestEnum?], nullableEnumNullableList: [TestEnum?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "EnumTestModel", "id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -43864,7 +43872,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -43873,7 +43881,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var enumVal: TestEnum { get { return snapshot["enumVal"]! as! TestEnum @@ -43882,7 +43890,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumVal") } } - + public var nullableEnumVal: TestEnum? { get { return snapshot["nullableEnumVal"] as? TestEnum @@ -43891,7 +43899,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumVal") } } - + public var enumList: [TestEnum] { get { return snapshot["enumList"]! as! [TestEnum] @@ -43900,7 +43908,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumList") } } - + public var enumNullableList: [TestEnum]? { get { return snapshot["enumNullableList"] as? [TestEnum] @@ -43909,7 +43917,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumNullableList") } } - + public var nullableEnumList: [TestEnum?] { get { return snapshot["nullableEnumList"]! as! [TestEnum?] @@ -43918,7 +43926,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumList") } } - + public var nullableEnumNullableList: [TestEnum?]? { get { return snapshot["nullableEnumNullableList"] as? [TestEnum?] @@ -43927,7 +43935,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -43936,7 +43944,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -43948,31 +43956,31 @@ public struct APISwift { } } } - + public final class OnUpdateEnumTestModelSubscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateEnumTestModel {\n onUpdateEnumTestModel {\n __typename\n id\n enumVal\n nullableEnumVal\n enumList\n enumNullableList\n nullableEnumList\n nullableEnumNullableList\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateEnumTestModel", type: .object(OnUpdateEnumTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateEnumTestModel: OnUpdateEnumTestModel? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateEnumTestModel": onUpdateEnumTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateEnumTestModel": onUpdateEnumTestModel.flatMap(\.snapshot)]) } - + public var onUpdateEnumTestModel: OnUpdateEnumTestModel? { get { return (snapshot["onUpdateEnumTestModel"] as? Snapshot).flatMap { OnUpdateEnumTestModel(snapshot: $0) } @@ -43981,10 +43989,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateEnumTestModel") } } - + public struct OnUpdateEnumTestModel: GraphQLSelectionSet { public static let possibleTypes = ["EnumTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -43997,17 +44005,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, enumVal: TestEnum, nullableEnumVal: TestEnum? = nil, enumList: [TestEnum], enumNullableList: [TestEnum]? = nil, nullableEnumList: [TestEnum?], nullableEnumNullableList: [TestEnum?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "EnumTestModel", "id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44016,7 +44024,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -44025,7 +44033,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var enumVal: TestEnum { get { return snapshot["enumVal"]! as! TestEnum @@ -44034,7 +44042,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumVal") } } - + public var nullableEnumVal: TestEnum? { get { return snapshot["nullableEnumVal"] as? TestEnum @@ -44043,7 +44051,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumVal") } } - + public var enumList: [TestEnum] { get { return snapshot["enumList"]! as! [TestEnum] @@ -44052,7 +44060,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumList") } } - + public var enumNullableList: [TestEnum]? { get { return snapshot["enumNullableList"] as? [TestEnum] @@ -44061,7 +44069,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumNullableList") } } - + public var nullableEnumList: [TestEnum?] { get { return snapshot["nullableEnumList"]! as! [TestEnum?] @@ -44070,7 +44078,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumList") } } - + public var nullableEnumNullableList: [TestEnum?]? { get { return snapshot["nullableEnumNullableList"] as? [TestEnum?] @@ -44079,7 +44087,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -44088,7 +44096,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -44100,31 +44108,31 @@ public struct APISwift { } } } - + public final class OnDeleteEnumTestModelSubscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteEnumTestModel {\n onDeleteEnumTestModel {\n __typename\n id\n enumVal\n nullableEnumVal\n enumList\n enumNullableList\n nullableEnumList\n nullableEnumNullableList\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteEnumTestModel", type: .object(OnDeleteEnumTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteEnumTestModel: OnDeleteEnumTestModel? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteEnumTestModel": onDeleteEnumTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteEnumTestModel": onDeleteEnumTestModel.flatMap(\.snapshot)]) } - + public var onDeleteEnumTestModel: OnDeleteEnumTestModel? { get { return (snapshot["onDeleteEnumTestModel"] as? Snapshot).flatMap { OnDeleteEnumTestModel(snapshot: $0) } @@ -44133,10 +44141,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteEnumTestModel") } } - + public struct OnDeleteEnumTestModel: GraphQLSelectionSet { public static let possibleTypes = ["EnumTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -44149,17 +44157,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, enumVal: TestEnum, nullableEnumVal: TestEnum? = nil, enumList: [TestEnum], enumNullableList: [TestEnum]? = nil, nullableEnumList: [TestEnum?], nullableEnumNullableList: [TestEnum?]? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "EnumTestModel", "id": id, "enumVal": enumVal, "nullableEnumVal": nullableEnumVal, "enumList": enumList, "enumNullableList": enumNullableList, "nullableEnumList": nullableEnumList, "nullableEnumNullableList": nullableEnumNullableList, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44168,7 +44176,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -44177,7 +44185,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var enumVal: TestEnum { get { return snapshot["enumVal"]! as! TestEnum @@ -44186,7 +44194,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumVal") } } - + public var nullableEnumVal: TestEnum? { get { return snapshot["nullableEnumVal"] as? TestEnum @@ -44195,7 +44203,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumVal") } } - + public var enumList: [TestEnum] { get { return snapshot["enumList"]! as! [TestEnum] @@ -44204,7 +44212,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumList") } } - + public var enumNullableList: [TestEnum]? { get { return snapshot["enumNullableList"] as? [TestEnum] @@ -44213,7 +44221,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "enumNullableList") } } - + public var nullableEnumList: [TestEnum?] { get { return snapshot["nullableEnumList"]! as! [TestEnum?] @@ -44222,7 +44230,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumList") } } - + public var nullableEnumNullableList: [TestEnum?]? { get { return snapshot["nullableEnumNullableList"] as? [TestEnum?] @@ -44231,7 +44239,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nullableEnumNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -44240,7 +44248,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -44252,31 +44260,31 @@ public struct APISwift { } } } - + public final class OnCreateNestedTypeTestModelSubscription: GraphQLSubscription { public static let operationString = "subscription OnCreateNestedTypeTestModel {\n onCreateNestedTypeTestModel {\n __typename\n id\n nestedVal {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedVal {\n __typename\n valueOne\n valueTwo\n }\n nestedList {\n __typename\n valueOne\n valueTwo\n }\n nestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateNestedTypeTestModel", type: .object(OnCreateNestedTypeTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateNestedTypeTestModel: OnCreateNestedTypeTestModel? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateNestedTypeTestModel": onCreateNestedTypeTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateNestedTypeTestModel": onCreateNestedTypeTestModel.flatMap(\.snapshot)]) } - + public var onCreateNestedTypeTestModel: OnCreateNestedTypeTestModel? { get { return (snapshot["onCreateNestedTypeTestModel"] as? Snapshot).flatMap { OnCreateNestedTypeTestModel(snapshot: $0) } @@ -44285,10 +44293,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateNestedTypeTestModel") } } - + public struct OnCreateNestedTypeTestModel: GraphQLSelectionSet { public static let possibleTypes = ["NestedTypeTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -44301,17 +44309,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, nestedVal: NestedVal, nullableNestedVal: NullableNestedVal? = nil, nestedList: [NestedList], nestedNullableList: [NestedNullableList]? = nil, nullableNestedList: [NullableNestedList?], nullableNestedNullableList: [NullableNestedNullableList?]? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap { $0.snapshot }, "nestedList": nestedList.map { $0.snapshot }, "nestedNullableList": nestedNullableList.flatMap { $0.map { $0.snapshot } }, "nullableNestedList": nullableNestedList.map { $0.flatMap { $0.snapshot } }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap(\.snapshot), "nestedList": nestedList.map(\.snapshot), "nestedNullableList": nestedNullableList.flatMap { $0.map(\.snapshot) }, "nullableNestedList": nullableNestedList.map { $0.flatMap(\.snapshot) }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap(\.snapshot) } }, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44320,7 +44328,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -44329,7 +44337,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var nestedVal: NestedVal { get { return NestedVal(snapshot: snapshot["nestedVal"]! as! Snapshot) @@ -44338,7 +44346,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "nestedVal") } } - + public var nullableNestedVal: NullableNestedVal? { get { return (snapshot["nullableNestedVal"] as? Snapshot).flatMap { NullableNestedVal(snapshot: $0) } @@ -44347,43 +44355,43 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "nullableNestedVal") } } - + public var nestedList: [NestedList] { get { return (snapshot["nestedList"] as! [Snapshot]).map { NestedList(snapshot: $0) } } set { - snapshot.updateValue(newValue.map { $0.snapshot }, forKey: "nestedList") + snapshot.updateValue(newValue.map(\.snapshot), forKey: "nestedList") } } - + public var nestedNullableList: [NestedNullableList]? { get { return (snapshot["nestedNullableList"] as? [Snapshot]).flatMap { $0.map { NestedNullableList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.snapshot } }, forKey: "nestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map(\.snapshot) }, forKey: "nestedNullableList") } } - + public var nullableNestedList: [NullableNestedList?] { get { return (snapshot["nullableNestedList"] as! [Snapshot?]).map { $0.flatMap { NullableNestedList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "nullableNestedList") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "nullableNestedList") } } - + public var nullableNestedNullableList: [NullableNestedNullableList?]? { get { return (snapshot["nullableNestedNullableList"] as? [Snapshot?]).flatMap { $0.map { $0.flatMap { NullableNestedNullableList(snapshot: $0) } } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, forKey: "nullableNestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap(\.snapshot) } }, forKey: "nullableNestedNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -44392,7 +44400,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -44401,26 +44409,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct NestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44429,7 +44437,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -44438,7 +44446,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -44448,26 +44456,26 @@ public struct APISwift { } } } - + public struct NullableNestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44476,7 +44484,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -44485,7 +44493,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -44495,26 +44503,26 @@ public struct APISwift { } } } - + public struct NestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44523,7 +44531,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -44532,7 +44540,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -44542,26 +44550,26 @@ public struct APISwift { } } } - + public struct NestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44570,7 +44578,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -44579,7 +44587,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -44589,26 +44597,26 @@ public struct APISwift { } } } - + public struct NullableNestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44617,7 +44625,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -44626,7 +44634,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -44636,26 +44644,26 @@ public struct APISwift { } } } - + public struct NullableNestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44664,7 +44672,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -44673,7 +44681,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -44686,31 +44694,31 @@ public struct APISwift { } } } - + public final class OnUpdateNestedTypeTestModelSubscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateNestedTypeTestModel {\n onUpdateNestedTypeTestModel {\n __typename\n id\n nestedVal {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedVal {\n __typename\n valueOne\n valueTwo\n }\n nestedList {\n __typename\n valueOne\n valueTwo\n }\n nestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateNestedTypeTestModel", type: .object(OnUpdateNestedTypeTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateNestedTypeTestModel: OnUpdateNestedTypeTestModel? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateNestedTypeTestModel": onUpdateNestedTypeTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateNestedTypeTestModel": onUpdateNestedTypeTestModel.flatMap(\.snapshot)]) } - + public var onUpdateNestedTypeTestModel: OnUpdateNestedTypeTestModel? { get { return (snapshot["onUpdateNestedTypeTestModel"] as? Snapshot).flatMap { OnUpdateNestedTypeTestModel(snapshot: $0) } @@ -44719,10 +44727,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateNestedTypeTestModel") } } - + public struct OnUpdateNestedTypeTestModel: GraphQLSelectionSet { public static let possibleTypes = ["NestedTypeTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -44735,17 +44743,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, nestedVal: NestedVal, nullableNestedVal: NullableNestedVal? = nil, nestedList: [NestedList], nestedNullableList: [NestedNullableList]? = nil, nullableNestedList: [NullableNestedList?], nullableNestedNullableList: [NullableNestedNullableList?]? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap { $0.snapshot }, "nestedList": nestedList.map { $0.snapshot }, "nestedNullableList": nestedNullableList.flatMap { $0.map { $0.snapshot } }, "nullableNestedList": nullableNestedList.map { $0.flatMap { $0.snapshot } }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap(\.snapshot), "nestedList": nestedList.map(\.snapshot), "nestedNullableList": nestedNullableList.flatMap { $0.map(\.snapshot) }, "nullableNestedList": nullableNestedList.map { $0.flatMap(\.snapshot) }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap(\.snapshot) } }, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44754,7 +44762,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -44763,7 +44771,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var nestedVal: NestedVal { get { return NestedVal(snapshot: snapshot["nestedVal"]! as! Snapshot) @@ -44772,7 +44780,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "nestedVal") } } - + public var nullableNestedVal: NullableNestedVal? { get { return (snapshot["nullableNestedVal"] as? Snapshot).flatMap { NullableNestedVal(snapshot: $0) } @@ -44781,43 +44789,43 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "nullableNestedVal") } } - + public var nestedList: [NestedList] { get { return (snapshot["nestedList"] as! [Snapshot]).map { NestedList(snapshot: $0) } } set { - snapshot.updateValue(newValue.map { $0.snapshot }, forKey: "nestedList") + snapshot.updateValue(newValue.map(\.snapshot), forKey: "nestedList") } } - + public var nestedNullableList: [NestedNullableList]? { get { return (snapshot["nestedNullableList"] as? [Snapshot]).flatMap { $0.map { NestedNullableList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.snapshot } }, forKey: "nestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map(\.snapshot) }, forKey: "nestedNullableList") } } - + public var nullableNestedList: [NullableNestedList?] { get { return (snapshot["nullableNestedList"] as! [Snapshot?]).map { $0.flatMap { NullableNestedList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "nullableNestedList") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "nullableNestedList") } } - + public var nullableNestedNullableList: [NullableNestedNullableList?]? { get { return (snapshot["nullableNestedNullableList"] as? [Snapshot?]).flatMap { $0.map { $0.flatMap { NullableNestedNullableList(snapshot: $0) } } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, forKey: "nullableNestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap(\.snapshot) } }, forKey: "nullableNestedNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -44826,7 +44834,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -44835,26 +44843,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct NestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44863,7 +44871,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -44872,7 +44880,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -44882,26 +44890,26 @@ public struct APISwift { } } } - + public struct NullableNestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44910,7 +44918,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -44919,7 +44927,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -44929,26 +44937,26 @@ public struct APISwift { } } } - + public struct NestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -44957,7 +44965,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -44966,7 +44974,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -44976,26 +44984,26 @@ public struct APISwift { } } } - + public struct NestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -45004,7 +45012,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -45013,7 +45021,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -45023,26 +45031,26 @@ public struct APISwift { } } } - + public struct NullableNestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -45051,7 +45059,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -45060,7 +45068,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -45070,26 +45078,26 @@ public struct APISwift { } } } - + public struct NullableNestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -45098,7 +45106,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -45107,7 +45115,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -45120,31 +45128,31 @@ public struct APISwift { } } } - + public final class OnDeleteNestedTypeTestModelSubscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteNestedTypeTestModel {\n onDeleteNestedTypeTestModel {\n __typename\n id\n nestedVal {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedVal {\n __typename\n valueOne\n valueTwo\n }\n nestedList {\n __typename\n valueOne\n valueTwo\n }\n nestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedList {\n __typename\n valueOne\n valueTwo\n }\n nullableNestedNullableList {\n __typename\n valueOne\n valueTwo\n }\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteNestedTypeTestModel", type: .object(OnDeleteNestedTypeTestModel.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteNestedTypeTestModel: OnDeleteNestedTypeTestModel? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteNestedTypeTestModel": onDeleteNestedTypeTestModel.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteNestedTypeTestModel": onDeleteNestedTypeTestModel.flatMap(\.snapshot)]) } - + public var onDeleteNestedTypeTestModel: OnDeleteNestedTypeTestModel? { get { return (snapshot["onDeleteNestedTypeTestModel"] as? Snapshot).flatMap { OnDeleteNestedTypeTestModel(snapshot: $0) } @@ -45153,10 +45161,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteNestedTypeTestModel") } } - + public struct OnDeleteNestedTypeTestModel: GraphQLSelectionSet { public static let possibleTypes = ["NestedTypeTestModel"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -45169,17 +45177,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, nestedVal: NestedVal, nullableNestedVal: NullableNestedVal? = nil, nestedList: [NestedList], nestedNullableList: [NestedNullableList]? = nil, nullableNestedList: [NullableNestedList?], nullableNestedNullableList: [NullableNestedNullableList?]? = nil, createdAt: String, updatedAt: String) { - self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap { $0.snapshot }, "nestedList": nestedList.map { $0.snapshot }, "nestedNullableList": nestedNullableList.flatMap { $0.map { $0.snapshot } }, "nullableNestedList": nullableNestedList.map { $0.flatMap { $0.snapshot } }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, "createdAt": createdAt, "updatedAt": updatedAt]) + self.init(snapshot: ["__typename": "NestedTypeTestModel", "id": id, "nestedVal": nestedVal.snapshot, "nullableNestedVal": nullableNestedVal.flatMap(\.snapshot), "nestedList": nestedList.map(\.snapshot), "nestedNullableList": nestedNullableList.flatMap { $0.map(\.snapshot) }, "nullableNestedList": nullableNestedList.map { $0.flatMap(\.snapshot) }, "nullableNestedNullableList": nullableNestedNullableList.flatMap { $0.map { $0.flatMap(\.snapshot) } }, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -45188,7 +45196,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -45197,7 +45205,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var nestedVal: NestedVal { get { return NestedVal(snapshot: snapshot["nestedVal"]! as! Snapshot) @@ -45206,7 +45214,7 @@ public struct APISwift { snapshot.updateValue(newValue.snapshot, forKey: "nestedVal") } } - + public var nullableNestedVal: NullableNestedVal? { get { return (snapshot["nullableNestedVal"] as? Snapshot).flatMap { NullableNestedVal(snapshot: $0) } @@ -45215,43 +45223,43 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "nullableNestedVal") } } - + public var nestedList: [NestedList] { get { return (snapshot["nestedList"] as! [Snapshot]).map { NestedList(snapshot: $0) } } set { - snapshot.updateValue(newValue.map { $0.snapshot }, forKey: "nestedList") + snapshot.updateValue(newValue.map(\.snapshot), forKey: "nestedList") } } - + public var nestedNullableList: [NestedNullableList]? { get { return (snapshot["nestedNullableList"] as? [Snapshot]).flatMap { $0.map { NestedNullableList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.snapshot } }, forKey: "nestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map(\.snapshot) }, forKey: "nestedNullableList") } } - + public var nullableNestedList: [NullableNestedList?] { get { return (snapshot["nullableNestedList"] as! [Snapshot?]).map { $0.flatMap { NullableNestedList(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "nullableNestedList") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "nullableNestedList") } } - + public var nullableNestedNullableList: [NullableNestedNullableList?]? { get { return (snapshot["nullableNestedNullableList"] as? [Snapshot?]).flatMap { $0.map { $0.flatMap { NullableNestedNullableList(snapshot: $0) } } } } set { - snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap { $0.snapshot } } }, forKey: "nullableNestedNullableList") + snapshot.updateValue(newValue.flatMap { $0.map { $0.flatMap(\.snapshot) } }, forKey: "nullableNestedNullableList") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -45260,7 +45268,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -45269,26 +45277,26 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "updatedAt") } } - + public struct NestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -45297,7 +45305,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -45306,7 +45314,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -45316,26 +45324,26 @@ public struct APISwift { } } } - + public struct NullableNestedVal: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -45344,7 +45352,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -45353,7 +45361,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -45363,26 +45371,26 @@ public struct APISwift { } } } - + public struct NestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -45391,7 +45399,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -45400,7 +45408,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -45410,26 +45418,26 @@ public struct APISwift { } } } - + public struct NestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -45438,7 +45446,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -45447,7 +45455,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -45457,26 +45465,26 @@ public struct APISwift { } } } - + public struct NullableNestedList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -45485,7 +45493,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -45494,7 +45502,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String @@ -45504,26 +45512,26 @@ public struct APISwift { } } } - + public struct NullableNestedNullableList: GraphQLSelectionSet { public static let possibleTypes = ["Nested"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("valueOne", type: .scalar(Int.self)), GraphQLField("valueTwo", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(valueOne: Int? = nil, valueTwo: String? = nil) { self.init(snapshot: ["__typename": "Nested", "valueOne": valueOne, "valueTwo": valueTwo]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -45532,7 +45540,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var valueOne: Int? { get { return snapshot["valueOne"] as? Int @@ -45541,7 +45549,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "valueOne") } } - + public var valueTwo: String? { get { return snapshot["valueTwo"] as? String diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/AnyModelIntegrationTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/AnyModelIntegrationTests.swift index 8a6397c488..7d4072e55d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/AnyModelIntegrationTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/AnyModelIntegrationTests.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Foundation import AWSAPIPlugin -@testable import APIHostApp +import Foundation +import XCTest @testable import Amplify +@testable import APIHostApp class AnyModelIntegrationTests: XCTestCase { let networkTimeout: TimeInterval = 180.0 @@ -42,9 +42,11 @@ class AnyModelIntegrationTests: XCTestCase { func testCreateAsAnyModel() throws { let createdAt: Temporal.DateTime = .now() let content = "Original post content as of \(createdAt)" - let originalPost = Post(title: "Post title", - content: content, - createdAt: createdAt) + let originalPost = Post( + title: "Post title", + content: content, + createdAt: createdAt + ) let anyPost = try originalPost.eraseToAnyModel() let callbackInvoked = expectation(description: "Callback invoked") @@ -96,9 +98,11 @@ class AnyModelIntegrationTests: XCTestCase { func testUpdateAsAnyModel() throws { let createdAt: Temporal.DateTime = .now() let content = "Original post content as of \(createdAt)" - let originalPost = Post(title: "Post title", - content: content, - createdAt: createdAt) + let originalPost = Post( + title: "Post title", + content: content, + createdAt: createdAt + ) let originalAnyPost = try originalPost.eraseToAnyModel() let createCallbackInvoked = expectation(description: "Create callback invoked") @@ -161,9 +165,11 @@ class AnyModelIntegrationTests: XCTestCase { func testDeleteAsAnyModel() throws { let createdAt: Temporal.DateTime = .now() let content = "Original post content as of \(createdAt)" - let originalPost = Post(title: "Post title", - content: content, - createdAt: createdAt) + let originalPost = Post( + title: "Post title", + content: content, + createdAt: createdAt + ) let originalAnyPost = try originalPost.eraseToAnyModel() let createCallbackInvoked = expectation(description: "Create callback invoked") diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/AppSyncRealTimeClientTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/AppSyncRealTimeClientTests.swift index c151f9c50c..20bfe181f1 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/AppSyncRealTimeClientTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/AppSyncRealTimeClientTests.swift @@ -5,9 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // - -import XCTest import Combine +import XCTest @testable import Amplify @testable import AWSAPIPlugin @testable @_spi(WebSocket) import AWSPluginsCore @@ -38,7 +37,7 @@ class AppSyncRealTimeClientTests: XCTestCase { let data = try TestConfigHelper.retrieve( forResource: GraphQLModelBasedTests.amplifyConfiguration ) - + let amplifyConfig = try JSONDecoder().decode(JSONValue.self, from: data) let (endpoint, apiKey) = (amplifyConfig.api?.plugins?.awsAPIPlugin?.asObject?.values .map { ($0.endpoint?.stringValue, $0.apiKey?.stringValue)} @@ -82,7 +81,7 @@ class AppSyncRealTimeClientTests: XCTestCase { }?.store(in: &cancellables) await fulfillment(of: [subscribedExpectation], timeout: 5) - withExtendedLifetime(cancellables, { }) + withExtendedLifetime(cancellables) { } } func testMultThreads_withConnectedClient_subscribeAndUnsubscribe() async throws { @@ -97,11 +96,11 @@ class AppSyncRealTimeClientTests: XCTestCase { of: AnyCancellable?.self, returning: [AnyCancellable?].self ) { taskGroup in - (0.. AnyCancellable? in guard let self else { return nil } - let subscription = try await self.makeOneSubscription(id: id) { + let subscription = try await makeOneSubscription(id: id) { if case .subscribed = $0 { expectedSubscription.fulfill() Task { @@ -121,7 +120,7 @@ class AppSyncRealTimeClientTests: XCTestCase { } await fulfillment(of: [expectedSubscription, expectedUnsubscription], timeout: 3) - withExtendedLifetime(cancellables, { }) + withExtendedLifetime(cancellables) { } } func testMaxSubscriptionReached_throwMaxSubscriptionsReachedError() async throws { @@ -133,11 +132,11 @@ class AppSyncRealTimeClientTests: XCTestCase { of: AnyCancellable?.self, returning: [AnyCancellable?].self ) { taskGroup in - (0.. AnyCancellable? in guard let self else { return nil } - let subscription = try await self.makeOneSubscription(id: id) { + let subscription = try await makeOneSubscription(id: id) { if case .subscribed = $0 { maxSubsctiptionsSuccess.fulfill() } @@ -154,7 +153,7 @@ class AppSyncRealTimeClientTests: XCTestCase { let maxSubscriptionReachedError = expectation(description: "Should return max subscription reached error") maxSubscriptionReachedError.assertForOverFulfill = false let retryTriggerredAndSucceed = expectation(description: "Retry on max subscription reached error and succeed") - cancellables.append(try await makeOneSubscription { event in + try await cancellables.append(makeOneSubscription { event in if case .error(let errors) = event { XCTAssertTrue(errors.count == 1) XCTAssertTrue(errors[0] is AppSyncRealTimeRequest.Error) @@ -167,7 +166,7 @@ class AppSyncRealTimeClientTests: XCTestCase { } }) await fulfillment(of: [maxSubscriptionReachedError, retryTriggerredAndSucceed], timeout: 5, enforceOrder: true) - withExtendedLifetime(cancellables, { }) + withExtendedLifetime(cancellables) { } } private func makeOneSubscription( @@ -176,7 +175,7 @@ class AppSyncRealTimeClientTests: XCTestCase { ) async throws -> AnyCancellable? { let subscription = try await appSyncRealTimeClient?.subscribe( id: id, - query: Self.appSyncQuery(with: self.subscriptionRequest) + query: Self.appSyncQuery(with: subscriptionRequest) ).sink(receiveValue: { onSubscriptionEvents?($0) }) @@ -195,7 +194,7 @@ class AppSyncRealTimeClientTests: XCTestCase { ) throws -> String { let payload: JSONValue = .object([ "query": .string(query), - "variables": (variables.isEmpty ? .null : .object(variables)) + "variables": variables.isEmpty ? .null : .object(variables) ]) let data = try JSONEncoder().encode(payload) return String(data: data, encoding: .utf8)! diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario1APISwiftTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario1APISwiftTests.swift index 5dacaf7714..b180310ecb 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario1APISwiftTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario1APISwiftTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest #if os(watchOS) @testable import APIWatchApp #else @@ -14,14 +14,15 @@ import Amplify #endif extension GraphQLConnectionScenario1Tests { - + func createTeamAPISwift() async throws -> APISwift.CreateTeam1Mutation.Data.CreateTeam1? { let input = APISwift.CreateTeam1Input(name: "name".withUUID) let mutation = APISwift.CreateTeam1Mutation(input: input) let request = GraphQLRequest( document: APISwift.CreateTeam1Mutation.operationString, variables: mutation.variables?.jsonObject, - responseType: APISwift.CreateTeam1Mutation.Data.self) + responseType: APISwift.CreateTeam1Mutation.Data.self + ) let response = try await Amplify.API.mutate(request: request) switch response { case .success(let data): @@ -30,15 +31,16 @@ extension GraphQLConnectionScenario1Tests { throw graphQLResponseError } } - + func createProjectAPISwift(with team: APISwift.CreateTeam1Mutation.Data.CreateTeam1? = nil) async throws -> APISwift.CreateProject1Mutation.Data.CreateProject1? { - + let input = APISwift.CreateProject1Input(project1TeamId: team?.id) let mutation = APISwift.CreateProject1Mutation(input: input) let request = GraphQLRequest( document: APISwift.CreateProject1Mutation.operationString, variables: mutation.variables?.jsonObject, - responseType: APISwift.CreateProject1Mutation.Data.self) + responseType: APISwift.CreateProject1Mutation.Data.self + ) let response = try await Amplify.API.mutate(request: request) switch response { case .success(let data): @@ -47,14 +49,15 @@ extension GraphQLConnectionScenario1Tests { throw graphQLResponseError } } - + func updateProjectAPISwift(projectId: String, teamId: String) async throws -> APISwift.UpdateProject1Mutation.Data.UpdateProject1? { let input = APISwift.UpdateProject1Input(id: projectId, project1TeamId: teamId) let mutation = APISwift.UpdateProject1Mutation(input: input) let request = GraphQLRequest( document: APISwift.UpdateProject1Mutation.operationString, variables: mutation.variables?.jsonObject, - responseType: APISwift.UpdateProject1Mutation.Data.self) + responseType: APISwift.UpdateProject1Mutation.Data.self + ) let response = try await Amplify.API.mutate(request: request) switch response { case .success(let data): @@ -63,14 +66,15 @@ extension GraphQLConnectionScenario1Tests { throw graphQLResponseError } } - + func deleteProjectAPISwift(projectId: String) async throws -> APISwift.DeleteProject1Mutation.Data.DeleteProject1? { let input = APISwift.DeleteProject1Input(id: projectId) let mutation = APISwift.DeleteProject1Mutation(input: input) let request = GraphQLRequest( document: APISwift.DeleteProject1Mutation.operationString, variables: mutation.variables?.jsonObject, - responseType: APISwift.DeleteProject1Mutation.Data.self) + responseType: APISwift.DeleteProject1Mutation.Data.self + ) let response = try await Amplify.API.mutate(request: request) switch response { case .success(let data): @@ -79,13 +83,14 @@ extension GraphQLConnectionScenario1Tests { throw graphQLResponseError } } - + func getProjectAPISwift(projectId: String) async throws -> APISwift.GetProject1Query.Data.GetProject1? { let query = APISwift.GetProject1Query(id: projectId) let request = GraphQLRequest( document: APISwift.GetProject1Query.operationString, variables: query.variables?.jsonObject, - responseType: APISwift.GetProject1Query.Data.self) + responseType: APISwift.GetProject1Query.Data.self + ) let response = try await Amplify.API.query(request: request) switch response { case .success(let data): @@ -94,13 +99,14 @@ extension GraphQLConnectionScenario1Tests { throw graphQLResponseError } } - + func listProjectsAPISwift() async throws -> APISwift.ListProject1sQuery.Data.ListProject1? { let query = APISwift.ListProject1sQuery(limit: 1) let request = GraphQLRequest( document: APISwift.ListProject1sQuery.operationString, variables: query.variables?.jsonObject, - responseType: APISwift.ListProject1sQuery.Data.self) + responseType: APISwift.ListProject1sQuery.Data.self + ) let response = try await Amplify.API.query(request: request) switch response { case .success(let data): @@ -109,33 +115,35 @@ extension GraphQLConnectionScenario1Tests { throw graphQLResponseError } } - + func testCreateTeamAPISwift() async throws { guard try await createTeamAPISwift() != nil else { XCTFail("Could not create team") return } } - + func testCreateProject() async throws { guard try await createProjectAPISwift() != nil else { XCTFail("Could not create team") return } } - + func testCreateAndGetProjectAPISwift() async throws { guard let team = try await createTeamAPISwift(), - let project = try await createProjectAPISwift(with: team) else { + let project = try await createProjectAPISwift(with: team) + else { XCTFail("Could not create team and a project") return } - + let query = APISwift.GetProject1Query(id: project.id) let request = GraphQLRequest( document: APISwift.GetProject1Query.operationString, variables: query.variables?.jsonObject, - responseType: APISwift.GetProject1Query.Data.self) + responseType: APISwift.GetProject1Query.Data.self + ) let result = try await Amplify.API.query(request: request) switch result { case .success(let data): @@ -153,10 +161,11 @@ extension GraphQLConnectionScenario1Tests { XCTFail("Failed with: \(response)") } } - + func testUpdateProjectWithAnotherTeamAPISwift() async throws { guard let team = try await createTeamAPISwift(), - let project = try await createProjectAPISwift(with: team) else { + let project = try await createProjectAPISwift(with: team) + else { XCTFail("Could not create a Team") return } @@ -164,33 +173,34 @@ extension GraphQLConnectionScenario1Tests { XCTFail("Failed to create another team") return } - + guard let updatedProject = try await updateProjectAPISwift(projectId: project.id, teamId: createdAnotherTeam.id) else { XCTFail("Failed to update project to another team") return } XCTAssertEqual(updatedProject.team?.id, createdAnotherTeam.id) } - + func testDeleteAndGetProjectAPISwift() async throws { guard let team = try await createTeamAPISwift(), - let project = try await createProjectAPISwift(with: team) else { + let project = try await createProjectAPISwift(with: team) + else { XCTFail("Could not create team and a project") return } - + guard let deletedProject = try await deleteProjectAPISwift(projectId: project.id) else { XCTFail("Could not delete project") return } XCTAssertEqual(deletedProject.id, project.id) - + guard try await getProjectAPISwift(projectId: project.id) == nil else { XCTFail("Project after deletion should be nil") return } } - + func testListProjectsAPISwift() async throws { guard let projects = try await listProjectsAPISwift() else { XCTFail("Could not list projects") diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario1Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario1Tests.swift index 89f05f502d..ccaa635436 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario1Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario1Tests.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else @@ -32,35 +32,36 @@ import XCTest */ class GraphQLConnectionScenario1Tests: XCTestCase { - + override func setUp() async throws { do { Amplify.Logging.logLevel = .verbose try Amplify.add(plugin: AWSAPIPlugin()) - + let amplifyConfig = try TestConfigHelper.retrieveAmplifyConfiguration( forResource: GraphQLModelBasedTests.amplifyConfiguration) try Amplify.configure(amplifyConfig) - + ModelRegistry.register(modelType: Project1.self) ModelRegistry.register(modelType: Team1.self) - + } catch { XCTFail("Error during setup: \(error)") } } - + override func tearDown() async throws { await Amplify.reset() } - + func testCreateAndGetProject() async throws { guard let team = try await createTeam(name: "name".withUUID), - let project = try await createProject(team: team) else { + let project = try await createProject(team: team) + else { XCTFail("Could not create team and a project") return } - + let result = try await Amplify.API.query(request: .get(Project1.self, byId: project.id)) switch result { case .success(let queriedProjectOptional): @@ -74,10 +75,11 @@ class GraphQLConnectionScenario1Tests: XCTestCase { XCTFail("Failed with: \(response)") } } - + func testUpdateProjectWithAnotherTeam() async throws { guard let team = try await createTeam(name: "name".withUUID), - var project = try await createProject(team: team) else { + var project = try await createProject(team: team) + else { XCTFail("Could not create a Team") return } @@ -94,10 +96,11 @@ class GraphQLConnectionScenario1Tests: XCTestCase { } XCTAssertEqual(updatedProject.team, anotherTeam) } - + func testDeleteAndGetProject() async throws { guard let team = try await createTeam(name: "name".withUUID), - let project = try await createProject(team: team) else { + let project = try await createProject(team: team) + else { XCTFail("Could not create team and a project") return } @@ -120,12 +123,13 @@ class GraphQLConnectionScenario1Tests: XCTestCase { XCTFail("Failed with: \(response)") } } - + // The filter we are passing into is the ProjectTeamID, but the API doesn't have the field ProjectTeamID // so we are disabling it func testListProjectsByTeamID() async throws { guard let team = try await createTeam(name: "name".withUUID), - let project = try await createProject(team: team) else { + let project = try await createProject(team: team) + else { XCTFail("Could not create team and a project") return } @@ -139,23 +143,24 @@ class GraphQLConnectionScenario1Tests: XCTestCase { XCTFail("Failed with: \(response)") } } - + func testPaginatedListProjects() async throws { let testCompleted = expectation(description: "test completed") Task { guard let team = try await createTeam(name: "name".withUUID), let projecta = try await createProject(team: team), - let projectb = try await createProject(team: team) else { + let projectb = try await createProject(team: team) + else { XCTFail("Could not create team and two projects") return } - + var results: List? let predicate = Project1.keys.id == projecta.id || Project1.keys.id == projectb.id let request: GraphQLRequest> = GraphQLRequest.list(Project1.self, where: predicate) - + let result = try await Amplify.API.query(request: request) - + guard case .success(let projects) = result else { XCTFail("Missing Successful response") return @@ -177,7 +182,7 @@ class GraphQLConnectionScenario1Tests: XCTestCase { } await fulfillment(of: [testCompleted], timeout: TestCommonConstants.networkTimeout) } - + func createTeam(id: String = UUID().uuidString, name: String) async throws -> Team1? { let team = Team1(id: id, name: name) let graphQLResponse = try await Amplify.API.mutate(request: .create(team)) @@ -188,10 +193,12 @@ class GraphQLConnectionScenario1Tests: XCTestCase { throw graphQLResponseError } } - - func createProject(id: String = UUID().uuidString, - name: String? = nil, - team: Team1? = nil) async throws -> Project1? { + + func createProject( + id: String = UUID().uuidString, + name: String? = nil, + team: Team1? = nil + ) async throws -> Project1? { let project = Project1(id: id, name: name, team: team) let graphQLResponse = try await Amplify.API.mutate(request: .create(project)) switch graphQLResponse { @@ -204,8 +211,10 @@ class GraphQLConnectionScenario1Tests: XCTestCase { } extension Team1: Equatable { - public static func == (lhs: Team1, - rhs: Team1) -> Bool { + public static func == ( + lhs: Team1, + rhs: Team1 + ) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario2Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario2Tests.swift index 2e43f532d9..11423809ee 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario2Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario2Tests.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else @@ -62,7 +62,8 @@ class GraphQLConnectionScenario2Tests: XCTestCase { func testCreateAndGetProject() async throws { guard let team = try await createTeam2(name: "name".withUUID), let project2a = try await createProject2(teamID: team.id, team: team), - let project2b = try await createProject2(teamID: team.id, team: team) else { + let project2b = try await createProject2(teamID: team.id, team: team) + else { XCTFail("Could not create team and a project") return } @@ -94,7 +95,8 @@ class GraphQLConnectionScenario2Tests: XCTestCase { func testUpdateProjectWithAnotherTeam() async throws { guard let team = try await createTeam2(name: "name".withUUID), - var project2 = try await createProject2(teamID: team.id, team: team) else { + var project2 = try await createProject2(teamID: team.id, team: team) + else { XCTFail("Could not create team and a project") return } @@ -113,10 +115,11 @@ class GraphQLConnectionScenario2Tests: XCTestCase { // The team object does not get retrieved from the service and is `nil`, but should be eager loaded to contain the `team` // XCTAssertEqual(updatedProject.team, anotherTeam) } - + func testDeleteAndGetProject() async throws { guard let team = try await createTeam2(name: "name".withUUID), - let project2 = try await createProject2(teamID: team.id, team: team) else { + let project2 = try await createProject2(teamID: team.id, team: team) + else { XCTFail("Could not create team and a project") return } @@ -142,7 +145,8 @@ class GraphQLConnectionScenario2Tests: XCTestCase { func testListProjectsByTeamID() async throws { guard let team = try await createTeam2(name: "name".withUUID), - try await createProject2(teamID: team.id, team: team) != nil else { + try await createProject2(teamID: team.id, team: team) != nil + else { XCTFail("Could not create team and two projects") return } @@ -161,7 +165,8 @@ class GraphQLConnectionScenario2Tests: XCTestCase { func testPaginatedListProjectsByTeamID() async throws { guard let team = try await createTeam2(name: "name".withUUID), try await createProject2(teamID: team.id, team: team) != nil, - try await createProject2(teamID: team.id, team: team) != nil else { + try await createProject2(teamID: team.id, team: team) != nil + else { XCTFail("Could not create team and two projects") return } @@ -186,7 +191,7 @@ class GraphQLConnectionScenario2Tests: XCTestCase { } XCTAssertEqual(resultsArray.count, 2) } - + func createTeam2(id: String = UUID().uuidString, name: String) async throws -> Team2? { let team = Team2(id: id, name: name) let graphQLResponse = try await Amplify.API.mutate(request: .create(team)) @@ -198,10 +203,12 @@ class GraphQLConnectionScenario2Tests: XCTestCase { } } - func createProject2(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2? = nil) async throws -> Project2? { + func createProject2( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2? = nil + ) async throws -> Project2? { let project = Project2(id: id, name: name, teamID: teamID, team: team) let graphQLResponse = try await Amplify.API.mutate(request: .create(project)) switch graphQLResponse { @@ -214,8 +221,10 @@ class GraphQLConnectionScenario2Tests: XCTestCase { } extension Team2: Equatable { - public static func == (lhs: Team2, - rhs: Team2) -> Bool { + public static func == ( + lhs: Team2, + rhs: Team2 + ) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name && lhs.createdAt == rhs.createdAt diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3APISwiftTests+Subscribe.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3APISwiftTests+Subscribe.swift index 9820132217..d98e9e7bad 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3APISwiftTests+Subscribe.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3APISwiftTests+Subscribe.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else @@ -15,21 +15,23 @@ import XCTest #endif extension GraphQLConnectionScenario3Tests { - + func onCreatePost3APISwiftRequest() -> GraphQLRequest { let request = GraphQLRequest( document: APISwift.OnCreatePost3Subscription.operationString, - responseType: APISwift.OnCreatePost3Subscription.Data.self) + responseType: APISwift.OnCreatePost3Subscription.Data.self + ) return request } - + func createPost3APISwift(_ id: String, _ title: String) async throws -> APISwift.CreatePost3Mutation.Data.CreatePost3? { let input = APISwift.CreatePost3Input(id: id, title: title) let mutation = APISwift.CreatePost3Mutation(input: input) let request = GraphQLRequest( document: APISwift.CreatePost3Mutation.operationString, variables: mutation.variables?.jsonObject, - responseType: APISwift.CreatePost3Mutation.Data.self) + responseType: APISwift.CreatePost3Mutation.Data.self + ) let response = try await Amplify.API.mutate(request: request) switch response { case .success(let data): @@ -38,7 +40,7 @@ extension GraphQLConnectionScenario3Tests { throw error } } - + func testOnCreateSubscriptionAPISwift() async throws { let connectedInvoked = expectation(description: "Connection established") let progressInvoked = expectation(description: "progress invoked") @@ -76,10 +78,11 @@ extension GraphQLConnectionScenario3Tests { XCTFail("Unexpected subscription failure") } } - + await fulfillment(of: [connectedInvoked], timeout: TestCommonConstants.networkTimeout) guard try await createPost3APISwift(uuid, title) != nil, - try await createPost3APISwift(uuid2, title) != nil else { + try await createPost3APISwift(uuid2, title) != nil + else { XCTFail("Failed to create post") return } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests+Helpers.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests+Helpers.swift index fb95b5abd0..04f23259c9 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests+Helpers.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests+Helpers.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else @@ -15,7 +15,7 @@ import XCTest #endif extension GraphQLConnectionScenario3Tests { - + func createPost(id: String = UUID().uuidString, title: String) async throws -> Post3? { let post = Post3(id: id, title: title) let event = try await Amplify.API.mutate(request: .create(post)) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests+List.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests+List.swift index 8edf725162..8ef75606be 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests+List.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests+List.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else @@ -38,7 +38,8 @@ extension GraphQLConnectionScenario3Tests { let commentContent = "content".withUUID guard let post = try await createPost(title: "title".withUUID), try await createComment(postID: post.id, content: commentContent) != nil, - try await createComment(postID: post.id, content: commentContent) != nil else { + try await createComment(postID: post.id, content: commentContent) != nil + else { XCTFail("Could not create post and two comments") return } @@ -78,7 +79,8 @@ extension GraphQLConnectionScenario3Tests { guard let post = try await createPost(title: "title".withUUID), try await createComment(postID: post.id, content: commentContent) != nil, - try await createComment(postID: post.id, content: commentContent) != nil else { + try await createComment(postID: post.id, content: commentContent) != nil + else { XCTFail("Could not create post and two comments") return } @@ -137,13 +139,13 @@ extension GraphQLConnectionScenario3Tests { let post = Post3.keys let predicate = post.id == uuid && post.title == uniqueTitle - let graphQLResponse = try await Amplify.API.query(request: .list(Post3.self, where: predicate, limit: 1000)) + let graphQLResponse = try await Amplify.API.query(request: .list(Post3.self, where: predicate, limit: 1_000)) guard case var .success(posts) = graphQLResponse else { XCTFail("Missing successful response") return } - - while posts.count == 0 && posts.hasNextPage() { + + while posts.isEmpty && posts.hasNextPage() { posts = try await posts.getNextPage() } XCTAssertEqual(posts.count, 1) @@ -174,7 +176,7 @@ extension GraphQLConnectionScenario3Tests { return } - while comments.count == 0 && comments.hasNextPage() { + while comments.isEmpty && comments.hasNextPage() { comments = try await comments.getNextPage() } XCTAssertEqual(comments.count, 1) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests+Subscribe.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests+Subscribe.swift index 926831267b..1393525328 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests+Subscribe.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests+Subscribe.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else @@ -53,7 +53,7 @@ extension GraphQLConnectionScenario3Tests { XCTFail("Unexpected subscription failure") } } - + await fulfillment(of: [connectedInvoked], timeout: TestCommonConstants.networkTimeout) let post = Post3(id: uuid, title: title) _ = try await Amplify.API.mutate(request: .create(post)) @@ -62,7 +62,7 @@ extension GraphQLConnectionScenario3Tests { await fulfillment(of: [progressInvoked], timeout: TestCommonConstants.networkTimeout) } - + func testOnUpdatePostSubscriptionWithModel() async throws { let connectingInvoked = expectation(description: "Connection connecting") let connectedInvoked = expectation(description: "Connection established") @@ -91,9 +91,9 @@ extension GraphQLConnectionScenario3Tests { XCTFail("Unexpected subscription failure") } } - + await fulfillment(of: [connectingInvoked, connectedInvoked], timeout: TestCommonConstants.networkTimeout) - + let uuid = UUID().uuidString let testMethodName = String("\(#function)".dropLast(2)) let title = testMethodName + "Title".withUUID @@ -103,12 +103,12 @@ extension GraphQLConnectionScenario3Tests { await fulfillment(of: [progressInvoked], timeout: TestCommonConstants.networkTimeout) } - + func testOnDeletePostSubscriptionWithModel() async throws { let connectingInvoked = expectation(description: "Connection connecting") let connectedInvoked = expectation(description: "Connection established") let progressInvoked = expectation(description: "progress invoked") - + let subscription = Amplify.API.subscribe(request: .subscription(of: Post3.self, type: .onDelete)) Task { do { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests.swift index e8fb12f625..a24ba6d98d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario3Tests.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario4Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario4Tests.swift index 26428342e8..440f58a1be 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario4Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario4Tests.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else @@ -116,7 +116,7 @@ class GraphQLConnectionScenario4Tests: XCTestCase { try await comments.fetch() results = comments fetchCommentsCompleted.fulfill() - + case .failure(let response): XCTFail("Failed with: \(response)") } @@ -211,13 +211,14 @@ class GraphQLConnectionScenario4Tests: XCTestCase { let commentContent = "content".withUUID guard let post = try await createPost(title: "title".withUUID), try await createComment(content: commentContent, post: post) != nil, - try await createComment(content: commentContent, post: post) != nil else { + try await createComment(content: commentContent, post: post) != nil + else { XCTFail("Could not create post and two comments") return } let predicate = field("postID").eq(post.id) var results: List? - let result = try await Amplify.API.query(request: .list(Comment4.self, where: predicate, limit: 3000)) + let result = try await Amplify.API.query(request: .list(Comment4.self, where: predicate, limit: 3_000)) switch result { case .success(let comments): results = comments @@ -248,7 +249,7 @@ class GraphQLConnectionScenario4Tests: XCTestCase { throw error } } - + func createComment(id: String = UUID().uuidString, content: String, post: Post4) async throws -> Comment4? { let comment = Comment4(id: id, content: content, post: post) let data = try await Amplify.API.mutate(request: .create(comment)) @@ -262,8 +263,10 @@ class GraphQLConnectionScenario4Tests: XCTestCase { } extension Post4: Equatable { - public static func == (lhs: Post4, - rhs: Post4) -> Bool { + public static func == ( + lhs: Post4, + rhs: Post4 + ) -> Bool { return lhs.id == rhs.id && lhs.title == rhs.title } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario5Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario5Tests.swift index 7fa611e950..ddae12ca6a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario5Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario5Tests.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else @@ -234,10 +234,10 @@ class GraphQLConnectionScenario5Tests: XCTestCase { resultsArray.append(contentsOf: subsequentResults) } XCTAssertEqual(resultsArray.count, 2) - XCTAssertTrue(resultsArray.contains(where: { (postEditor) -> Bool in + XCTAssertTrue(resultsArray.contains(where: { postEditor -> Bool in postEditor.post.id == post1.id })) - XCTAssertTrue(resultsArray.contains(where: { (postEditor) -> Bool in + XCTAssertTrue(resultsArray.contains(where: { postEditor -> Bool in postEditor.post.id == post2.id })) } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario6Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario6Tests.swift index d53eebfbdb..9e9b0d230a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario6Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLConnectionScenario6Tests.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else @@ -69,7 +69,8 @@ class GraphQLConnectionScenario6Tests: XCTestCase { let post1 = try await createPost(title: "title".withUUID, blog: blog), try await createPost(title: "title", blog: blog) != nil, let comment1post1 = try await createComment(post: post1, content: commentContent), - let comment2post1 = try await createComment(post: post1, content: commentContent) else { + let comment2post1 = try await createComment(post: post1, content: commentContent) + else { XCTFail("Could not create blog, posts, and comments") return } @@ -98,7 +99,7 @@ class GraphQLConnectionScenario6Tests: XCTestCase { let allPosts = try await getAll(list: resultPosts) XCTAssertEqual(allPosts.count, 2) - guard let fetchedPost = allPosts.first(where: { (post) -> Bool in + guard let fetchedPost = allPosts.first(where: { post -> Bool in post.id == post1.id }), let comments = fetchedPost.comments else { XCTFail("Could not set up - failed to get a post and its comments") @@ -113,16 +114,16 @@ class GraphQLConnectionScenario6Tests: XCTestCase { await fulfillment(of: [fetchCommentsCompleted], timeout: TestCommonConstants.networkTimeout) let allComments = try await getAll(list: resultComments) XCTAssertEqual(allComments.count, 2) - XCTAssertTrue(allComments.contains(where: { (comment) -> Bool in + XCTAssertTrue(allComments.contains(where: { comment -> Bool in comment.id == comment1post1.id })) - XCTAssertTrue(allComments.contains(where: { (comment) -> Bool in + XCTAssertTrue(allComments.contains(where: { comment -> Bool in comment.id == comment2post1.id })) } func getAll(list: List?) async throws -> [M] { - guard var list = list else { + guard var list else { return [] } var results = [M]() diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLModelBasedTests+List.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLModelBasedTests+List.swift index 032a9d9c67..c5b4564d84 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLModelBasedTests+List.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLModelBasedTests+List.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else @@ -39,8 +39,8 @@ extension GraphQLModelBasedTests { let post = Post.keys let predicate = post.id == uuid1 || post.id == uuid2 var results: List? - let response = try await Amplify.API.query(request: .list(Post.self, where: predicate, limit: 3000)) - + let response = try await Amplify.API.query(request: .list(Post.self, where: predicate, limit: 3_000)) + guard case .success(let graphQLresponse) = response else { XCTFail("Missing successful response") return @@ -96,7 +96,7 @@ extension GraphQLModelBasedTests { subsequentResults = listResult } XCTAssertFalse(subsequentResults.hasNextPage()) - + do { let listResult = try await subsequentResults.getNextPage() XCTFail("Unexpected \(listResult)") @@ -126,7 +126,7 @@ extension GraphQLModelBasedTests { _ = try await Amplify.API.mutate(request: .create(comment)) var results: Post? let response = try await Amplify.API.query(request: .get(Post.self, byId: post.id)) - + guard case .success(let graphQLResponse) = response else { XCTFail("Missing successful response") return @@ -137,7 +137,7 @@ extension GraphQLModelBasedTests { XCTFail("Could not get post") return } - + do { try await retrievedPost.comments?.fetch() XCTFail("Should have failed to fetch") @@ -177,7 +177,7 @@ extension GraphQLModelBasedTests { let listPosts = try await list( .list( Post.self, - where: Post.keys.draft.attributeExists(false) + where: Post.keys.draft.attributeExists(false) && Post.keys.createdAt >= post.createdAt ) ) @@ -188,13 +188,13 @@ extension GraphQLModelBasedTests { func list(_ request: GraphQLRequest>) async throws -> [M] { func getAllPages(_ list: List) async throws -> [M] { if list.hasNextPage() { - return list.elements + (try await getAllPages(list.getNextPage())) + return try list.elements + (await getAllPages(list.getNextPage())) } else { return list.elements } } - return try await getAllPages(try await Amplify.API.query(request: request).get()) + return try await getAllPages(await Amplify.API.query(request: request).get()) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLModelBasedTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLModelBasedTests.swift index 8d16762f17..74e20d620e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLModelBasedTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLModelBasedTests.swift @@ -16,24 +16,24 @@ import XCTest // swiftlint:disable type_body_length class GraphQLModelBasedTests: XCTestCase { - + static let amplifyConfiguration = "testconfiguration/GraphQLModelBasedTests-amplifyconfiguration" - final public class PostCommentModelRegistration: AmplifyModelRegistration { + public final class PostCommentModelRegistration: AmplifyModelRegistration { public func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post.self) ModelRegistry.register(modelType: Comment.self) } - + public let version: String = "1" } - - + + override func setUp() async throws { await Amplify.reset() Amplify.Logging.logLevel = .verbose let plugin = AWSAPIPlugin(modelRegistration: PostCommentModelRegistration()) - + do { try Amplify.add(plugin: plugin) let amplifyConfig = try TestConfigHelper.retrieveAmplifyConfiguration( @@ -42,16 +42,16 @@ class GraphQLModelBasedTests: XCTestCase { ModelRegistry.register(modelType: Comment.self) ModelRegistry.register(modelType: Post.self) - + } catch { XCTFail("Error during setup: \(error)") } } - + override func tearDown() async throws { await Amplify.reset() } - + func testQuerySinglePostWithModel() async throws { let uuid = UUID().uuidString let testMethodName = String("\(#function)".dropLast(2)) @@ -67,11 +67,11 @@ class GraphQLModelBasedTests: XCTestCase { XCTFail("Missing post from query") return } - + XCTAssertEqual(resultPost.id, post.id) XCTAssertEqual(resultPost.title, title) } - + /// Test custom GraphQLRequest with nested list deserializes to generated Post Model /// /// - Given: A post containing a single comment @@ -86,11 +86,13 @@ class GraphQLModelBasedTests: XCTestCase { let title = testMethodName + "Title" let post = Post(id: uuid, title: title, content: "content", createdAt: .now()) _ = try await Amplify.API.mutate(request: .create(post)) - let comment = Comment(content: "commentContent", - createdAt: .now(), - post: post) + let comment = Comment( + content: "commentContent", + createdAt: .now(), + post: post + ) _ = try await Amplify.API.mutate(request: .create(comment)) - + let document = """ query getPost($id: ID!) { getPost(id: $id){ @@ -124,10 +126,12 @@ class GraphQLModelBasedTests: XCTestCase { } } """ - let graphQLRequest = GraphQLRequest(document: document, - variables: ["id": uuid], - responseType: Post?.self, - decodePath: "getPost") + let graphQLRequest = GraphQLRequest( + document: document, + variables: ["id": uuid], + responseType: Post?.self, + decodePath: "getPost" + ) let graphQLResponse = try await Amplify.API.query(request: graphQLRequest) guard case .success(let data) = graphQLResponse else { XCTFail("Missing successful response") @@ -137,7 +141,7 @@ class GraphQLModelBasedTests: XCTestCase { XCTFail("Missing post from query") return } - + XCTAssertEqual(resultPost.id, post.id) XCTAssertEqual(resultPost.title, title) guard let comments = resultPost.comments else { @@ -146,14 +150,14 @@ class GraphQLModelBasedTests: XCTestCase { } XCTAssertEqual(comments.count, 1) } - + func testListQueryWithModel() async throws { let uuid = UUID().uuidString let testMethodName = String("\(#function)".dropLast(2)) let title = testMethodName + "Title" let post = Post(id: uuid, title: title, content: "content", createdAt: .now()) _ = try await Amplify.API.mutate(request: .create(post)) - + let graphQLResponse = try await Amplify.API.query(request: .list(Post.self)) guard case .success(let posts) = graphQLResponse else { XCTFail("Missing successful response") @@ -161,17 +165,19 @@ class GraphQLModelBasedTests: XCTestCase { } XCTAssertTrue(!posts.isEmpty) } - + func testListQueryWithPredicate() async throws { let uuid = UUID().uuidString let testMethodName = String("\(#function)".dropLast(2)) let uniqueTitle = testMethodName + uuid + "Title" - let createdPost = Post(id: uuid, - title: uniqueTitle, - content: "content", - createdAt: .now(), - draft: true, - rating: 12.3) + let createdPost = Post( + id: uuid, + title: uniqueTitle, + content: "content", + createdAt: .now(), + draft: true, + rating: 12.3 + ) _ = try await Amplify.API.mutate(request: .create(createdPost)) let post = Post.keys let predicate = post.id == uuid && @@ -180,14 +186,14 @@ class GraphQLModelBasedTests: XCTestCase { post.createdAt == createdPost.createdAt && post.rating == 12.3 && post.draft == true - - let graphQLResponse = try await Amplify.API.query(request: .list(Post.self, where: predicate, limit: 1000)) + + let graphQLResponse = try await Amplify.API.query(request: .list(Post.self, where: predicate, limit: 1_000)) guard case .success(var posts) = graphQLResponse else { XCTFail("Missing successful response") return } - - while posts.count == 0 && posts.hasNextPage() { + + while posts.isEmpty && posts.hasNextPage() { posts = try await posts.getNextPage() } XCTAssertEqual(posts.count, 1) @@ -202,7 +208,7 @@ class GraphQLModelBasedTests: XCTestCase { XCTAssertEqual(singlePost.rating, 12.3) XCTAssertEqual(singlePost.draft, true) } - + func testCreatPostWithModel() async throws { let post = Post(title: "title", content: "content", createdAt: .now()) let createdPostResult = try await Amplify.API.mutate(request: .create(post)) @@ -212,16 +218,18 @@ class GraphQLModelBasedTests: XCTestCase { } XCTAssertEqual(resultedPost.title, "title") } - + func testCreateCommentWithModel() async throws { let uuid = UUID().uuidString let testMethodName = String("\(#function)".dropLast(2)) let title = testMethodName + "Title" let post = Post(id: uuid, title: title, content: "content", createdAt: .now()) _ = try await Amplify.API.mutate(request: .create(post)) - let comment = Comment(content: "commentContent", - createdAt: .now(), - post: post) + let comment = Comment( + content: "commentContent", + createdAt: .now(), + post: post + ) let createdCommentResult = try await Amplify.API.mutate(request: .create(comment)) guard case .success(let resultComment) = createdCommentResult else { XCTFail("Error creating a Comment \(createdCommentResult)") @@ -230,7 +238,7 @@ class GraphQLModelBasedTests: XCTestCase { XCTAssertEqual(resultComment.content, "commentContent") XCTAssertNotNil(resultComment.post) } - + func testDeletePostWithModel() async throws { let uuid = UUID().uuidString let testMethodName = String("\(#function)".dropLast(2)) @@ -254,7 +262,7 @@ class GraphQLModelBasedTests: XCTestCase { XCTFail("Failed with: \(response)") } } - + func testUpdatePostWithModel() async throws { let uuid = UUID().uuidString let testMethodName = String("\(#function)".dropLast(2)) @@ -270,7 +278,7 @@ class GraphQLModelBasedTests: XCTestCase { } XCTAssertEqual(updatedPosts.title, updatedTitle) } - + func testOnCreatePostSubscriptionWithModel() async throws { let connectedInvoked = expectation(description: "Connection established") let progressInvoked = expectation(description: "progress invoked") @@ -308,16 +316,16 @@ class GraphQLModelBasedTests: XCTestCase { XCTFail("Unexpected subscription failure") } } - + await fulfillment(of: [connectedInvoked], timeout: TestCommonConstants.networkTimeout) - + let post = Post(id: uuid, title: title, content: "content", createdAt: .now()) _ = try await Amplify.API.mutate(request: .create(post)) let post2 = Post(id: uuid2, title: title, content: "content", createdAt: .now()) _ = try await Amplify.API.mutate(request: .create(post2)) await fulfillment(of: [progressInvoked], timeout: TestCommonConstants.networkTimeout) } - + func testOnUpdatePostSubscriptionWithModel() async throws { let connectingInvoked = expectation(description: "Connection connecting") let connectedInvoked = expectation(description: "Connection established") @@ -346,24 +354,24 @@ class GraphQLModelBasedTests: XCTestCase { XCTFail("Unexpected subscription failure") } } - + await fulfillment(of: [connectingInvoked, connectedInvoked], timeout: TestCommonConstants.networkTimeout) - + let uuid = UUID().uuidString let testMethodName = String("\(#function)".dropLast(2)) let title = testMethodName + "Title" let post = Post(id: uuid, title: title, content: "content", createdAt: .now()) _ = try await Amplify.API.mutate(request: .create(post)) _ = try await Amplify.API.mutate(request: .update(post)) - + await fulfillment(of: [progressInvoked], timeout: TestCommonConstants.networkTimeout) } - + func testOnDeletePostSubscriptionWithModel() async throws { let connectingInvoked = expectation(description: "Connection connecting") let connectedInvoked = expectation(description: "Connection established") let progressInvoked = expectation(description: "progress invoked") - + let subscription = Amplify.API.subscribe(request: .subscription(of: Post.self, type: .onDelete)) Task { do { @@ -386,19 +394,19 @@ class GraphQLModelBasedTests: XCTestCase { XCTFail("Unexpected subscription failure") } } - + await fulfillment(of: [connectingInvoked, connectedInvoked], timeout: TestCommonConstants.networkTimeout) - + let uuid = UUID().uuidString let testMethodName = String("\(#function)".dropLast(2)) let title = testMethodName + "Title" let post = Post(id: uuid, title: title, content: "content", createdAt: .now()) _ = try await Amplify.API.mutate(request: .create(post)) _ = try await Amplify.API.mutate(request: .delete(post)) - + await fulfillment(of: [progressInvoked], timeout: TestCommonConstants.networkTimeout) } - + func testOnCreateCommentSubscriptionWithModel() async throws { let connectedInvoked = expectation(description: "Connection established") let progressInvoked = expectation(description: "progress invoked") @@ -436,7 +444,7 @@ class GraphQLModelBasedTests: XCTestCase { XCTFail("Unexpected subscription failure") } } - + await fulfillment(of: [connectedInvoked], timeout: TestCommonConstants.networkTimeout) let post = Post(id: uuid, title: title, content: "content", createdAt: .now()) _ = try await Amplify.API.mutate(request: .create(post)) @@ -456,10 +464,10 @@ class GraphQLModelBasedTests: XCTestCase { let allSubscribedExpectation = expectation(description: "All subscriptions are subscribed") allSubscribedExpectation.expectedFulfillmentCount = numberOfSubscription - let subscriptions = (0..<5).map { _ in + let subscriptions = (0 ..< 5).map { _ in Amplify.API.subscribe(request: .subscription(of: Comment.self, type: .onCreate)) } - subscriptions.forEach { subscription in + for subscription in subscriptions { Task { do { for try await subscriptionEvent in subscription { @@ -491,8 +499,7 @@ class GraphQLModelBasedTests: XCTestCase { if let appSyncRealTimeClientFactory = getUnderlyingAPIPlugin()?.appSyncRealTimeClientFactory as? AppSyncRealTimeClientFactory, let appSyncRealTimeClient = - await appSyncRealTimeClientFactory.apiToClientCache.values.first as? AppSyncRealTimeClient - { + await appSyncRealTimeClientFactory.apiToClientCache.values.first as? AppSyncRealTimeClient { var appSyncSubscriptions = await appSyncRealTimeClient.numberOfSubscriptions XCTAssertEqual(appSyncSubscriptions, numberOfSubscription) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLScalarAPISwiftTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLScalarAPISwiftTests.swift index 6e3c70c7b2..730b1b4330 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLScalarAPISwiftTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLScalarAPISwiftTests.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else @@ -15,7 +15,7 @@ import XCTest #endif extension GraphQLScalarTests { - + func testScalarContainerAPISwift() async throws { let id = UUID().uuidString let date = Temporal.Date.now().iso8601String @@ -35,14 +35,16 @@ extension GraphQLScalarTests { myJson: "{}", myPhone: "2342355678", myUrl: "https://www.amazon.com/dp/B000NZW3KC/", - myIpAddress: "123.12.34.56") + myIpAddress: "123.12.34.56" + ) let mutation = APISwift.CreateScalarContainerMutation(input: input) - + let request = GraphQLRequest( document: APISwift.CreateScalarContainerMutation.operationString, variables: mutation.variables?.jsonObject, - responseType: APISwift.CreateScalarContainerMutation.Data.self) - + responseType: APISwift.CreateScalarContainerMutation.Data.self + ) + let data = try await mutateModel(request: request) guard let container = data.createScalarContainer else { XCTFail("Missing created container") @@ -62,21 +64,23 @@ extension GraphQLScalarTests { XCTAssertEqual(container.myPhone, "2342355678") XCTAssertEqual(container.myUrl, "https://www.amazon.com/dp/B000NZW3KC/") XCTAssertEqual(container.myIpAddress, "123.12.34.56") - + } - + func testListIntContainerAPISwift() async throws { let id = UUID().uuidString let input = APISwift.CreateListIntContainerInput( id: id, test: 2, intList: [1, 2, 3], - nullableIntList: [1, 2, 3]) + nullableIntList: [1, 2, 3] + ) let mutation = APISwift.CreateListIntContainerMutation(input: input) let request = GraphQLRequest( document: APISwift.CreateListIntContainerMutation.operationString, variables: mutation.variables?.jsonObject, - responseType: APISwift.CreateListIntContainerMutation.Data.self) + responseType: APISwift.CreateListIntContainerMutation.Data.self + ) let data = try await mutateModel(request: request) guard let container = data.createListIntContainer else { XCTFail("Missing created container") diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLScalarTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLScalarTests.swift index 45593c79d9..3d8c8609be 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLScalarTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLScalarTests.swift @@ -6,8 +6,8 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin #if os(watchOS) @testable import APIWatchApp #else @@ -41,19 +41,21 @@ class GraphQLScalarTests: GraphQLTestBase { } func testScalarContainer() async throws { - let container = ScalarContainer(myString: "myString".withUUID, - myInt: 1, - myDouble: 1.0, - myBool: true, - myDate: .now(), - myTime: .now(), - myDateTime: .now(), - myTimeStamp: 123, - myEmail: "local-part@domain-part", - myJSON: "{}", - myPhone: "2342355678", - myURL: "https://www.amazon.com/dp/B000NZW3KC/", - myIPAddress: "123.12.34.56") + let container = ScalarContainer( + myString: "myString".withUUID, + myInt: 1, + myDouble: 1.0, + myBool: true, + myDate: .now(), + myTime: .now(), + myDateTime: .now(), + myTimeStamp: 123, + myEmail: "local-part@domain-part", + myJSON: "{}", + myPhone: "2342355678", + myURL: "https://www.amazon.com/dp/B000NZW3KC/", + myIPAddress: "123.12.34.56" + ) let updatedContainer = ScalarContainer(id: container.id) let createdModel = try await mutateModel(request: .create(container)) @@ -83,15 +85,18 @@ class GraphQLScalarTests: GraphQLTestBase { intList: [], intNullableList: [], nullableIntList: [], - nullableIntNullableList: nil) - - let updatedContainer = ListIntContainer(id: container.id, - test: 2, - nullableInt: nil, - intList: [1, 2, 3], - intNullableList: [1, 2, 3], - nullableIntList: [1, 2, 3], - nullableIntNullableList: [1, 2, 3]) + nullableIntNullableList: nil + ) + + let updatedContainer = ListIntContainer( + id: container.id, + test: 2, + nullableInt: nil, + intList: [1, 2, 3], + intNullableList: [1, 2, 3], + nullableIntList: [1, 2, 3], + nullableIntNullableList: [1, 2, 3] + ) let createdModel = try await mutateModel(request: .create(container)) XCTAssertEqual(createdModel, container) @@ -119,23 +124,28 @@ class GraphQLScalarTests: GraphQLTestBase { stringList: ["value1".withUUID], stringNullableList: [], nullableStringList: [], - nullableStringNullableList: nil) - - let updatedContainer = ListStringContainer(id: container.id, - test: "test", - nullableString: "test", - stringList: ["value1"], - stringNullableList: ["value1"], - nullableStringList: ["value1"], - nullableStringNullableList: ["value1"]) + nullableStringNullableList: nil + ) + + let updatedContainer = ListStringContainer( + id: container.id, + test: "test", + nullableString: "test", + stringList: ["value1"], + stringNullableList: ["value1"], + nullableStringList: ["value1"], + nullableStringNullableList: ["value1"] + ) let createdModel = try await mutateModel(request: .create(container)) XCTAssertEqual(createdModel, container) let updatedModel = try await mutateModel(request: .update(updatedContainer)) XCTAssertEqual(updatedModel, updatedContainer) - guard let queriedModel = try await queryModel(request: .get(ListStringContainer.self, - byId: container.id)) else { + guard let queriedModel = try await queryModel(request: .get( + ListStringContainer.self, + byId: container.id + )) else { XCTFail("Failed to query model") return } @@ -155,23 +165,28 @@ class GraphQLScalarTests: GraphQLTestBase { stringList: ["value1".withUUID], stringNullableList: nil, nullableStringList: [nil], - nullableStringNullableList: nil) - - let updatedContainer = ListStringContainer(id: container.id, - test: "test", - nullableString: "test", - stringList: ["value1"], - stringNullableList: ["value1"], - nullableStringList: ["value1"], - nullableStringNullableList: ["value1"]) + nullableStringNullableList: nil + ) + + let updatedContainer = ListStringContainer( + id: container.id, + test: "test", + nullableString: "test", + stringList: ["value1"], + stringNullableList: ["value1"], + nullableStringList: ["value1"], + nullableStringNullableList: ["value1"] + ) let createdModel = try await mutateModel(request: .create(container)) XCTAssertEqual(createdModel, container) let updatedModel = try await mutateModel(request: .update(updatedContainer)) XCTAssertEqual(updatedModel, updatedContainer) - guard let queriedModel = try await queryModel(request: .get(ListStringContainer.self, - byId: container.id)) else { + guard let queriedModel = try await queryModel(request: .get( + ListStringContainer.self, + byId: container.id + )) else { XCTFail("Failed to query model") return } @@ -185,19 +200,23 @@ class GraphQLScalarTests: GraphQLTestBase { } func testEnumTestModel() async throws { - let container = EnumTestModel(enumVal: .valueOne, - nullableEnumVal: .valueTwo, - enumList: [.valueOne], - enumNullableList: [.valueTwo], - nullableEnumList: [.valueOne, .valueTwo], - nullableEnumNullableList: [.valueTwo, .valueOne]) - let updatedContainer = EnumTestModel(id: container.id, - enumVal: .valueTwo, - nullableEnumVal: nil, - enumList: [.valueTwo], - enumNullableList: [.valueTwo, .valueOne], - nullableEnumList: [.valueTwo, .valueOne], - nullableEnumNullableList: [.valueOne, .valueTwo]) + let container = EnumTestModel( + enumVal: .valueOne, + nullableEnumVal: .valueTwo, + enumList: [.valueOne], + enumNullableList: [.valueTwo], + nullableEnumList: [.valueOne, .valueTwo], + nullableEnumNullableList: [.valueTwo, .valueOne] + ) + let updatedContainer = EnumTestModel( + id: container.id, + enumVal: .valueTwo, + nullableEnumVal: nil, + enumList: [.valueTwo], + enumNullableList: [.valueTwo, .valueOne], + nullableEnumList: [.valueTwo, .valueOne], + nullableEnumNullableList: [.valueOne, .valueTwo] + ) let createdModel = try await mutateModel(request: .create(container)) XCTAssertEqual(createdModel, container) @@ -218,20 +237,24 @@ class GraphQLScalarTests: GraphQLTestBase { } func testNestedEnumTestModel() async throws { - let container = NestedTypeTestModel(nestedVal: .init(valueOne: 1), - nullableNestedVal: .init(), - nestedList: [.init(valueTwo: "value2")], - nestedNullableList: [.init()], - nullableNestedList: [.init(valueOne: 1, valueTwo: "value2")], - nullableNestedNullableList: [.init(valueOne: 1, valueTwo: "value2")]) - - let updatedContainer = NestedTypeTestModel(id: container.id, - nestedVal: .init(valueOne: 1), - nullableNestedVal: .init(), - nestedList: [.init(valueTwo: "updatedValue"), .init(valueOne: 1)], - nestedNullableList: [.init(valueOne: 1, valueTwo: "value2")], - nullableNestedList: [], - nullableNestedNullableList: nil) + let container = NestedTypeTestModel( + nestedVal: .init(valueOne: 1), + nullableNestedVal: .init(), + nestedList: [.init(valueTwo: "value2")], + nestedNullableList: [.init()], + nullableNestedList: [.init(valueOne: 1, valueTwo: "value2")], + nullableNestedNullableList: [.init(valueOne: 1, valueTwo: "value2")] + ) + + let updatedContainer = NestedTypeTestModel( + id: container.id, + nestedVal: .init(valueOne: 1), + nullableNestedVal: .init(), + nestedList: [.init(valueTwo: "updatedValue"), .init(valueOne: 1)], + nestedNullableList: [.init(valueOne: 1, valueTwo: "value2")], + nullableNestedList: [], + nullableNestedNullableList: nil + ) let createdModel = try await mutateModel(request: .create(container)) XCTAssertEqual(createdModel, container) @@ -239,8 +262,10 @@ class GraphQLScalarTests: GraphQLTestBase { let updatedModel = try await mutateModel(request: .update(updatedContainer)) XCTAssertEqual(updatedModel, updatedContainer) - guard let queriedModel = try await queryModel(request: .get(NestedTypeTestModel.self, - byId: container.id)) else { + guard let queriedModel = try await queryModel(request: .get( + NestedTypeTestModel.self, + byId: container.id + )) else { XCTFail("Failed to query model") return } @@ -256,7 +281,7 @@ class GraphQLScalarTests: GraphQLTestBase { extension ScalarContainer: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.myInt == rhs.myInt && lhs.myDouble == rhs.myDouble && lhs.myBool == rhs.myBool @@ -268,60 +293,60 @@ extension ScalarContainer: Equatable { && lhs.myJSON == rhs.myJSON && lhs.myPhone == rhs.myPhone && lhs.myURL == rhs.myURL - && lhs.myIPAddress == rhs.myIPAddress) + && lhs.myIPAddress == rhs.myIPAddress } } extension ListIntContainer: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.test == rhs.test && lhs.nullableInt == rhs.nullableInt && lhs.intList == rhs.intList && lhs.intNullableList == rhs.intNullableList && lhs.nullableIntList == rhs.nullableIntList - && lhs.nullableIntNullableList == rhs.nullableIntNullableList) + && lhs.nullableIntNullableList == rhs.nullableIntNullableList } } extension ListStringContainer: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.test == rhs.test && lhs.nullableString == rhs.nullableString && lhs.stringList == rhs.stringList && lhs.stringNullableList == rhs.stringNullableList && lhs.nullableStringList == rhs.nullableStringList - && lhs.nullableStringNullableList == rhs.nullableStringNullableList) + && lhs.nullableStringNullableList == rhs.nullableStringNullableList } } extension EnumTestModel: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.enumVal == rhs.enumVal && lhs.nullableEnumVal == rhs.nullableEnumVal && lhs.enumList == rhs.enumList && lhs.enumNullableList == rhs.enumNullableList && lhs.nullableEnumList == rhs.nullableEnumList - && lhs.nullableEnumNullableList == rhs.nullableEnumNullableList) + && lhs.nullableEnumNullableList == rhs.nullableEnumNullableList } } extension NestedTypeTestModel: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.nestedVal == rhs.nestedVal && lhs.nullableNestedVal == rhs.nullableNestedVal && lhs.nestedList == rhs.nestedList && lhs.nestedNullableList == rhs.nestedNullableList && lhs.nullableNestedList == rhs.nullableNestedList - && lhs.nullableNestedNullableList == rhs.nullableNestedNullableList) + && lhs.nullableNestedNullableList == rhs.nullableNestedNullableList } } extension Nested: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.valueOne == rhs.valueOne - && lhs.valueTwo == rhs.valueTwo) + return lhs.valueOne == rhs.valueOne + && lhs.valueTwo == rhs.valueTwo } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLSyncBased/GraphQLSyncBasedTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLSyncBased/GraphQLSyncBasedTests.swift index d5f0d43668..af8f092f4c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLSyncBased/GraphQLSyncBasedTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLSyncBased/GraphQLSyncBasedTests.swift @@ -6,9 +6,9 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify @testable import APIHostApp +@testable import AWSAPIPlugin // swiftlint:disable type_body_length class GraphQLSyncBasedTests: XCTestCase { @@ -104,8 +104,10 @@ class GraphQLSyncBasedTests: XCTestCase { let completeInvoked = expectation(description: "request completed") var responseFromOperation: GraphQLResponse?>? - let request = GraphQLRequest.query(modelName: createdPost.model.modelName, - byId: createdPost.model.id) + let request = GraphQLRequest.query( + modelName: createdPost.model.modelName, + byId: createdPost.model.id + ) _ = Amplify.API.query(request: request) { event in defer { @@ -169,10 +171,12 @@ class GraphQLSyncBasedTests: XCTestCase { let updatedTitle = title + "Updated" - let modifiedPost = Post(id: createdPost.model["id"] as? String ?? "", - title: updatedTitle, - content: createdPost.model["content"] as? String ?? "", - createdAt: .now()) + let modifiedPost = Post( + id: createdPost.model["id"] as? String ?? "", + title: updatedTitle, + content: createdPost.model["content"] as? String ?? "", + createdAt: .now() + ) let completeInvoked = expectation(description: "request completed") var responseFromOperation: GraphQLResponse>? @@ -239,18 +243,22 @@ class GraphQLSyncBasedTests: XCTestCase { let updatedTitle = title + "Updated" - let modifiedPost = Post(id: createdPost.model["id"] as? String ?? "", - title: updatedTitle, - content: createdPost.model["content"] as? String ?? "", - createdAt: .now()) + let modifiedPost = Post( + id: createdPost.model["id"] as? String ?? "", + title: updatedTitle, + content: createdPost.model["content"] as? String ?? "", + createdAt: .now() + ) let completeInvoked = expectation(description: "request completed") var responseFromOperation: GraphQLResponse>? let queryPredicate = post.title == "Does not match" - let request = GraphQLRequest.updateMutation(of: modifiedPost, - where: queryPredicate.graphQLFilter, - version: 1) + let request = GraphQLRequest.updateMutation( + of: modifiedPost, + where: queryPredicate.graphQLFilter, + version: 1 + ) _ = Amplify.API.mutate(request: request) { event in defer { @@ -280,7 +288,8 @@ class GraphQLSyncBasedTests: XCTestCase { XCTAssertEqual(errors.count, 1) guard let error = errors.first, let extensions = error.extensions, - case let .string(errorTypeValue) = extensions["errorType"] else { + case let .string(errorTypeValue) = extensions["errorType"] + else { XCTFail("Failed to get errorType from extensions of the GraphQL error") return } @@ -311,14 +320,18 @@ class GraphQLSyncBasedTests: XCTestCase { return } let updatedTitle = title + "Updated" - let modifiedPost = Post(id: createdPost.model["id"] as? String ?? "", - title: updatedTitle, - content: createdPost.model["content"] as? String ?? "", - createdAt: .now()) + let modifiedPost = Post( + id: createdPost.model["id"] as? String ?? "", + title: updatedTitle, + content: createdPost.model["content"] as? String ?? "", + createdAt: .now() + ) let firstUpdateSuccess = expectation(description: "first update mutation should be successful") - let request = GraphQLRequest.updateMutation(of: modifiedPost, - version: 1) + let request = GraphQLRequest.updateMutation( + of: modifiedPost, + version: 1 + ) _ = Amplify.API.mutate(request: request) { event in switch event { case .success: @@ -416,10 +429,12 @@ class GraphQLSyncBasedTests: XCTestCase { var responseFromOperation: GraphQLResponse>? let post = Post.keys let predicate = post.title == title - let request = GraphQLRequest.syncQuery(modelType: Post.self, - where: predicate, - limit: 1, - lastSync: 123) + let request = GraphQLRequest.syncQuery( + modelType: Post.self, + where: predicate, + limit: 1, + lastSync: 123 + ) _ = Amplify.API.query(request: request) { event in defer { @@ -514,7 +529,8 @@ class GraphQLSyncBasedTests: XCTestCase { case .success: completedInvoked.fulfill() } - }) + } + ) XCTAssertNotNil(operation) await fulfillment(of: [connectedInvoked], timeout: TestCommonConstants.networkTimeout) @@ -533,9 +549,12 @@ class GraphQLSyncBasedTests: XCTestCase { // MARK: Helpers func createPost(id: String, title: String) -> MutationSyncResult? { - let post = Post(id: id, title: title, - content: "content", - createdAt: .now()) + let post = Post( + id: id, + title: title, + content: "content", + createdAt: .now() + ) return createPost(post: post) } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLSyncBased/GraphQLSyncCustomPrimaryKeyTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLSyncBased/GraphQLSyncCustomPrimaryKeyTests.swift index 114c7ad3c6..6b4142aadf 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLSyncBased/GraphQLSyncCustomPrimaryKeyTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLSyncBased/GraphQLSyncCustomPrimaryKeyTests.swift @@ -6,9 +6,9 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify @testable import APIHostApp +@testable import AWSAPIPlugin class GraphQLSyncCustomPrimaryKeyTests: XCTestCase { @@ -55,9 +55,11 @@ class GraphQLSyncCustomPrimaryKeyTests: XCTestCase { } /// Query order - guard let queryMutationSyncResult = queryCustomerOrder(modelName: CustomerOrder.modelName, - byId: createdCustomerOrder.id, - orderId: createdCustomerOrder.orderId), + guard let queryMutationSyncResult = queryCustomerOrder( + modelName: CustomerOrder.modelName, + byId: createdCustomerOrder.id, + orderId: createdCustomerOrder.orderId + ), var queriedCustomerOrder = queryMutationSyncResult.model.instance as? CustomerOrder else { XCTFail("Failed to query customer order") return @@ -67,9 +69,11 @@ class GraphQLSyncCustomPrimaryKeyTests: XCTestCase { /// Update order queriedCustomerOrder.email = "testnew@abc.com" - guard let updateMutationSyncResult = updateCustomerOrder(of: queriedCustomerOrder, - modelSchema: queriedCustomerOrder.schema, - version: queryMutationSyncResult.syncMetadata.version), + guard let updateMutationSyncResult = updateCustomerOrder( + of: queriedCustomerOrder, + modelSchema: queriedCustomerOrder.schema, + version: queryMutationSyncResult.syncMetadata.version + ), let updatedCustomerOrder = updateMutationSyncResult.model.instance as? CustomerOrder else { XCTFail("Failed to update customer order") return @@ -78,9 +82,11 @@ class GraphQLSyncCustomPrimaryKeyTests: XCTestCase { XCTAssertEqual(customerOrder.id, updatedCustomerOrder.id) /// Delete order - guard let deleteMutationSyncResult = deleteCustomerOrder(of: updatedCustomerOrder, - modelSchema: updatedCustomerOrder.schema, - version: updateMutationSyncResult.syncMetadata.version), + guard let deleteMutationSyncResult = deleteCustomerOrder( + of: updatedCustomerOrder, + modelSchema: updatedCustomerOrder.schema, + version: updateMutationSyncResult.syncMetadata.version + ), let deletedCustomerOrder = deleteMutationSyncResult.model.instance as? CustomerOrder else { XCTFail("Failed to update customer order") return @@ -89,9 +95,11 @@ class GraphQLSyncCustomPrimaryKeyTests: XCTestCase { XCTAssertEqual(customerOrder.id, deletedCustomerOrder.id) /// Query after delete - guard let queryAfterDeleteMutationSyncResult = queryCustomerOrder(modelName: CustomerOrder.modelName, - byId: deletedCustomerOrder.id, - orderId: deletedCustomerOrder.orderId), + guard let queryAfterDeleteMutationSyncResult = queryCustomerOrder( + modelName: CustomerOrder.modelName, + byId: deletedCustomerOrder.id, + orderId: deletedCustomerOrder.orderId + ), let queryDeletedCustomerOrder = queryAfterDeleteMutationSyncResult.model.instance as? CustomerOrder else { XCTFail("Failed to query customer order") return @@ -126,9 +134,11 @@ class GraphQLSyncCustomPrimaryKeyTests: XCTestCase { return result } - func queryCustomerOrder(modelName: String, - byId id: String, - orderId: String) -> MutationSyncResult? { + func queryCustomerOrder( + modelName: String, + byId id: String, + orderId: String + ) -> MutationSyncResult? { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: modelName, operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: ModelIdDecorator(id: id, fields: ["orderId": orderId])) @@ -136,10 +146,12 @@ class GraphQLSyncCustomPrimaryKeyTests: XCTestCase { documentBuilder.add(decorator: AuthRuleDecorator(.query)) let document = documentBuilder.build() - let queryRequest = GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult?.self, - decodePath: document.name) + let queryRequest = GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult?.self, + decodePath: document.name + ) var querySyncResult: MutationSyncResult? let querySuccess = expectation(description: "query successful") _ = Amplify.API.query(request: queryRequest) { event in @@ -160,14 +172,17 @@ class GraphQLSyncCustomPrimaryKeyTests: XCTestCase { return querySyncResult } - func updateCustomerOrder(of model: Model, - modelSchema: ModelSchema, - version: Int) -> MutationSyncResult? { + func updateCustomerOrder( + of model: Model, + modelSchema: ModelSchema, + version: Int + ) -> MutationSyncResult? { let updateSuccess = expectation(description: "update successful") let updateRequest = GraphQLRequest.updateMutation( of: model, modelSchema: modelSchema, - version: version) + version: version + ) var updateSyncResult: MutationSyncResult? _ = Amplify.API.mutate(request: updateRequest) { event in @@ -188,14 +203,17 @@ class GraphQLSyncCustomPrimaryKeyTests: XCTestCase { return updateSyncResult } - func deleteCustomerOrder(of model: Model, - modelSchema: ModelSchema, - version: Int) -> MutationSyncResult? { + func deleteCustomerOrder( + of model: Model, + modelSchema: ModelSchema, + version: Int + ) -> MutationSyncResult? { let deleteSuccess = expectation(description: "delete successful") let deleteRequest = GraphQLRequest.deleteMutation( of: model, modelSchema: modelSchema, - version: version) + version: version + ) var deleteSyncResult: MutationSyncResult? _ = Amplify.API.mutate(request: deleteRequest) { event in diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLTestBase.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLTestBase.swift index 582da2028a..e2f3c08021 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLTestBase.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/GraphQLTestBase.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest #if os(watchOS) @testable import APIWatchApp #else diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/AmplifyModels.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/AmplifyModels.swift index b0f249dd64..21d22a2183 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/AmplifyModels.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/AmplifyModels.swift @@ -1,12 +1,19 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -// Contains the set of classes that conforms to the `Model` protocol. +// Contains the set of classes that conforms to the `Model` protocol. -final public class AmplifyModels: AmplifyModelRegistration { +public final class AmplifyModels: AmplifyModelRegistration { public let version: String = "5ee542e5c6ab0424a858288c724b1322" - + public func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post.self) ModelRegistry.register(modelType: Comment.self) @@ -30,4 +37,4 @@ final public class AmplifyModels: AmplifyModelRegistration { ModelRegistry.register(modelType: EnumTestModel.self) ModelRegistry.register(modelType: NestedTypeTestModel.self) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Blog6+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Blog6+Schema.swift index e2ae53bc53..18a0eb9f2e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Blog6+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Blog6+Schema.swift @@ -1,25 +1,32 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Blog6 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Blog6 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case posts case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let blog6 = Blog6.keys - + model.pluralName = "Blog6s" - + model.fields( .id(), .field(blog6.name, is: .required, ofType: .string), @@ -28,4 +35,4 @@ extension Blog6 { .field(blog6.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Blog6.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Blog6.swift index 87254248e6..32f821132d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Blog6.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Blog6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Blog6: Model { public var posts: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment+Schema.swift index d1274038df..1988a133df 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment+Schema.swift @@ -1,25 +1,32 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case createdAt case post case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment = Comment.keys - + model.pluralName = "Comments" - + model.fields( .id(), .field(comment.content, is: .required, ofType: .string), @@ -28,4 +35,4 @@ extension Comment { .field(comment.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment.swift index 9429276f9f..f6e3f2d0bf 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,26 +15,32 @@ public struct Comment: Model { public var createdAt: Temporal.DateTime public var post: Post? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - createdAt: Temporal.DateTime, - post: Post? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String, + createdAt: Temporal.DateTime, + post: Post? = nil + ) { + self.init( + id: id, content: content, createdAt: createdAt, post: post, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - createdAt: Temporal.DateTime, - post: Post? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + createdAt: Temporal.DateTime, + post: Post? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt self.post = post self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment3+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment3+Schema.swift index 8fbf885ad9..30a30e52be 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment3+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment3+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment3 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment3 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case postID case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment3 = Comment3.keys - + model.pluralName = "Comment3s" - + model.attributes( .index(fields: ["postID", "content"], name: "byPost3") ) - + model.fields( .id(), .field(comment3.postID, is: .required, ofType: .string), @@ -32,4 +39,4 @@ extension Comment3 { .field(comment3.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment3.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment3.swift index 0e18356e52..433ce52a9e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment3.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment3.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Comment3: Model { public var content: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - postID: String, - content: String) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + postID: String, + content: String + ) { + self.init( + id: id, postID: postID, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - postID: String, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + postID: String, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.postID = postID self.content = content self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment4+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment4+Schema.swift index ce30f58729..87f711c6dd 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment4+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment4+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment4 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment4 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment4 = Comment4.keys - + model.pluralName = "Comment4s" - + model.attributes( .index(fields: ["postID", "content"], name: "byPost4") ) - + model.fields( .id(), .field(comment4.content, is: .required, ofType: .string), @@ -32,4 +39,4 @@ extension Comment4 { .field(comment4.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment4.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment4.swift index e6a4cae7c9..35790685c0 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment4.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Comment4: Model { public var post: Post4? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: Post4? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String, + post: Post4? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: Post4? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: Post4? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment6+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment6+Schema.swift index 8b4ffe225d..6e97d92f3f 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment6+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment6+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment6 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment6 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case post case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment6 = Comment6.keys - + model.pluralName = "Comment6s" - + model.attributes( .index(fields: ["postID", "content"], name: "byPost") ) - + model.fields( .id(), .belongsTo(comment6.post, is: .optional, ofType: Post6.self, targetName: "postID"), @@ -32,4 +39,4 @@ extension Comment6 { .field(comment6.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment6.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment6.swift index e7d8dd8c1e..ab6cb6a60d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment6.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Comment6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Comment6: Model { public var content: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - post: Post6? = nil, - content: String) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + post: Post6? = nil, + content: String + ) { + self.init( + id: id, post: post, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - post: Post6? = nil, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + post: Post6? = nil, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.post = post self.content = content self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/EnumTestModel+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/EnumTestModel+Schema.swift index 86e972d90e..12351a88e6 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/EnumTestModel+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/EnumTestModel+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension EnumTestModel { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension EnumTestModel { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case enumVal case nullableEnumVal @@ -15,15 +22,15 @@ extension EnumTestModel { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let enumTestModel = EnumTestModel.keys - + model.pluralName = "EnumTestModels" - + model.fields( .id(), .field(enumTestModel.enumVal, is: .required, ofType: .enum(type: TestEnum.self)), @@ -36,4 +43,4 @@ extension EnumTestModel { .field(enumTestModel.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/EnumTestModel.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/EnumTestModel.swift index 57a45cd219..de9368dd4d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/EnumTestModel.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/EnumTestModel.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct EnumTestModel: Model { public var nullableEnumNullableList: [TestEnum?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - enumVal: TestEnum, - nullableEnumVal: TestEnum? = nil, - enumList: [TestEnum] = [], - enumNullableList: [TestEnum]? = nil, - nullableEnumList: [TestEnum?] = [], - nullableEnumNullableList: [TestEnum?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + enumVal: TestEnum, + nullableEnumVal: TestEnum? = nil, + enumList: [TestEnum] = [], + enumNullableList: [TestEnum]? = nil, + nullableEnumList: [TestEnum?] = [], + nullableEnumNullableList: [TestEnum?]? = nil + ) { + self.init( + id: id, enumVal: enumVal, nullableEnumVal: nullableEnumVal, enumList: enumList, @@ -28,17 +38,20 @@ public struct EnumTestModel: Model { nullableEnumList: nullableEnumList, nullableEnumNullableList: nullableEnumNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - enumVal: TestEnum, - nullableEnumVal: TestEnum? = nil, - enumList: [TestEnum] = [], - enumNullableList: [TestEnum]? = nil, - nullableEnumList: [TestEnum?] = [], - nullableEnumNullableList: [TestEnum?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + enumVal: TestEnum, + nullableEnumVal: TestEnum? = nil, + enumList: [TestEnum] = [], + enumNullableList: [TestEnum]? = nil, + nullableEnumList: [TestEnum?] = [], + nullableEnumNullableList: [TestEnum?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.enumVal = enumVal self.nullableEnumVal = nullableEnumVal @@ -49,4 +62,4 @@ public struct EnumTestModel: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListIntContainer+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListIntContainer+Schema.swift index ebf312ae68..14aace5cdf 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListIntContainer+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListIntContainer+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ListIntContainer { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ListIntContainer { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case test case nullableInt @@ -15,15 +22,15 @@ extension ListIntContainer { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let listIntContainer = ListIntContainer.keys - + model.pluralName = "ListIntContainers" - + model.fields( .id(), .field(listIntContainer.test, is: .required, ofType: .int), @@ -36,4 +43,4 @@ extension ListIntContainer { .field(listIntContainer.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListIntContainer.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListIntContainer.swift index 040edd16e8..efb53081d8 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListIntContainer.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListIntContainer.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct ListIntContainer: Model { public var nullableIntNullableList: [Int?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - test: Int, - nullableInt: Int? = nil, - intList: [Int] = [], - intNullableList: [Int]? = nil, - nullableIntList: [Int?] = [], - nullableIntNullableList: [Int?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + test: Int, + nullableInt: Int? = nil, + intList: [Int] = [], + intNullableList: [Int]? = nil, + nullableIntList: [Int?] = [], + nullableIntNullableList: [Int?]? = nil + ) { + self.init( + id: id, test: test, nullableInt: nullableInt, intList: intList, @@ -28,17 +38,20 @@ public struct ListIntContainer: Model { nullableIntList: nullableIntList, nullableIntNullableList: nullableIntNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - test: Int, - nullableInt: Int? = nil, - intList: [Int] = [], - intNullableList: [Int]? = nil, - nullableIntList: [Int?] = [], - nullableIntNullableList: [Int?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + test: Int, + nullableInt: Int? = nil, + intList: [Int] = [], + intNullableList: [Int]? = nil, + nullableIntList: [Int?] = [], + nullableIntNullableList: [Int?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.test = test self.nullableInt = nullableInt @@ -49,4 +62,4 @@ public struct ListIntContainer: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListStringContainer+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListStringContainer+Schema.swift index d233dd6642..691fbef988 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListStringContainer+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListStringContainer+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ListStringContainer { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ListStringContainer { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case test case nullableString @@ -15,15 +22,15 @@ extension ListStringContainer { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let listStringContainer = ListStringContainer.keys - + model.pluralName = "ListStringContainers" - + model.fields( .id(), .field(listStringContainer.test, is: .required, ofType: .string), @@ -36,4 +43,4 @@ extension ListStringContainer { .field(listStringContainer.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListStringContainer.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListStringContainer.swift index cfe1107366..d08e28aa86 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListStringContainer.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ListStringContainer.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct ListStringContainer: Model { public var nullableStringNullableList: [String?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - test: String, - nullableString: String? = nil, - stringList: [String] = [], - stringNullableList: [String]? = nil, - nullableStringList: [String?] = [], - nullableStringNullableList: [String?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + test: String, + nullableString: String? = nil, + stringList: [String] = [], + stringNullableList: [String]? = nil, + nullableStringList: [String?] = [], + nullableStringNullableList: [String?]? = nil + ) { + self.init( + id: id, test: test, nullableString: nullableString, stringList: stringList, @@ -28,17 +38,20 @@ public struct ListStringContainer: Model { nullableStringList: nullableStringList, nullableStringNullableList: nullableStringNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - test: String, - nullableString: String? = nil, - stringList: [String] = [], - stringNullableList: [String]? = nil, - nullableStringList: [String?] = [], - nullableStringNullableList: [String?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + test: String, + nullableString: String? = nil, + stringList: [String] = [], + stringNullableList: [String]? = nil, + nullableStringList: [String?] = [], + nullableStringNullableList: [String?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.test = test self.nullableString = nullableString @@ -49,4 +62,4 @@ public struct ListStringContainer: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Nested+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Nested+Schema.swift index 1c83d051d7..d2cd8eeea4 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Nested+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Nested+Schema.swift @@ -1,25 +1,32 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Nested { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Nested { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case valueOne case valueTwo } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let nested = Nested.keys - + model.pluralName = "Nesteds" - + model.fields( .field(nested.valueOne, is: .optional, ofType: .int), .field(nested.valueTwo, is: .optional, ofType: .string) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Nested.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Nested.swift index 37415d4550..19da9762a3 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Nested.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Nested.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,4 +12,4 @@ import Foundation public struct Nested: Embeddable { var valueOne: Int? var valueTwo: String? -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/NestedTypeTestModel+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/NestedTypeTestModel+Schema.swift index 7d179f4aa7..97e08bff55 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/NestedTypeTestModel+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/NestedTypeTestModel+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension NestedTypeTestModel { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension NestedTypeTestModel { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case nestedVal case nullableNestedVal @@ -15,15 +22,15 @@ extension NestedTypeTestModel { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let nestedTypeTestModel = NestedTypeTestModel.keys - + model.pluralName = "NestedTypeTestModels" - + model.fields( .id(), .field(nestedTypeTestModel.nestedVal, is: .required, ofType: .embedded(type: Nested.self)), @@ -36,4 +43,4 @@ extension NestedTypeTestModel { .field(nestedTypeTestModel.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/NestedTypeTestModel.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/NestedTypeTestModel.swift index 2167581607..bd5c875239 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/NestedTypeTestModel.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/NestedTypeTestModel.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct NestedTypeTestModel: Model { public var nullableNestedNullableList: [Nested?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - nestedVal: Nested, - nullableNestedVal: Nested? = nil, - nestedList: [Nested] = [], - nestedNullableList: [Nested]? = nil, - nullableNestedList: [Nested?] = [], - nullableNestedNullableList: [Nested?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + nestedVal: Nested, + nullableNestedVal: Nested? = nil, + nestedList: [Nested] = [], + nestedNullableList: [Nested]? = nil, + nullableNestedList: [Nested?] = [], + nullableNestedNullableList: [Nested?]? = nil + ) { + self.init( + id: id, nestedVal: nestedVal, nullableNestedVal: nullableNestedVal, nestedList: nestedList, @@ -28,17 +38,20 @@ public struct NestedTypeTestModel: Model { nullableNestedList: nullableNestedList, nullableNestedNullableList: nullableNestedNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - nestedVal: Nested, - nullableNestedVal: Nested? = nil, - nestedList: [Nested] = [], - nestedNullableList: [Nested]? = nil, - nullableNestedList: [Nested?] = [], - nullableNestedNullableList: [Nested?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + nestedVal: Nested, + nullableNestedVal: Nested? = nil, + nestedList: [Nested] = [], + nestedNullableList: [Nested]? = nil, + nullableNestedList: [Nested?] = [], + nullableNestedNullableList: [Nested?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.nestedVal = nestedVal self.nullableNestedVal = nullableNestedVal @@ -49,4 +62,4 @@ public struct NestedTypeTestModel: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post+Schema.swift index a0b8083af8..3f7cdf6d04 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case content @@ -15,15 +22,15 @@ extension Post { case status case comments } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post = Post.keys - + model.pluralName = "Posts" - + model.fields( .id(), .field(post.title, is: .required, ofType: .string), @@ -36,4 +43,4 @@ extension Post { .hasMany(post.comments, is: .optional, ofType: Comment.self, associatedWith: Comment.keys.post) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post.swift index 8b7bb7c7b2..7c43a79452 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,8 +19,9 @@ public struct Post: Model { public var rating: Double? public var status: PostStatus? public var comments: List? - - public init(id: String = UUID().uuidString, + + public init( + id: String = UUID().uuidString, title: String, content: String, createdAt: Temporal.DateTime, @@ -21,7 +29,8 @@ public struct Post: Model { draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, - comments: List? = []) { + comments: List? = [] + ) { self.id = id self.title = title self.content = content @@ -32,4 +41,4 @@ public struct Post: Model { self.status = status self.comments = comments } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post3+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post3+Schema.swift index 75ebd10d14..89cdb79d89 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post3+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post3+Schema.swift @@ -1,25 +1,32 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post3 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post3 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post3 = Post3.keys - + model.pluralName = "Post3s" - + model.fields( .id(), .field(post3.title, is: .required, ofType: .string), @@ -28,4 +35,4 @@ extension Post3 { .field(post3.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post3.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post3.swift index 5ef0d6e3fc..a52879301a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post3.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post3.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post3: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post4+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post4+Schema.swift index 1c387d0beb..288d863f58 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post4+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post4+Schema.swift @@ -1,25 +1,32 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post4 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post4 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post4 = Post4.keys - + model.pluralName = "Post4s" - + model.fields( .id(), .field(post4.title, is: .required, ofType: .string), @@ -28,4 +35,4 @@ extension Post4 { .field(post4.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post4.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post4.swift index 490e66612a..568c276a51 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post4.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post4: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post5+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post5+Schema.swift index eb35a225e4..8d0f270b8b 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post5+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post5+Schema.swift @@ -1,25 +1,32 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post5 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post5 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case editors case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post5 = Post5.keys - + model.pluralName = "Post5s" - + model.fields( .id(), .field(post5.title, is: .required, ofType: .string), @@ -28,4 +35,4 @@ extension Post5 { .field(post5.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post5.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post5.swift index d679aab098..eb4b6de060 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post5.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post5.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post5: Model { public var editors: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - editors: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + editors: List? = [] + ) { + self.init( + id: id, title: title, editors: editors, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - editors: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + editors: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.editors = editors self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post6+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post6+Schema.swift index 2b46ba95b4..97877b60f3 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post6+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post6+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post6 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post6 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case blog @@ -12,19 +19,19 @@ extension Post6 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post6 = Post6.keys - + model.pluralName = "Post6s" - + model.attributes( .index(fields: ["blogID"], name: "byBlog") ) - + model.fields( .id(), .field(post6.title, is: .required, ofType: .string), @@ -34,4 +41,4 @@ extension Post6 { .field(post6.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post6.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post6.swift index 5ef29766ed..6fa200740c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post6.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Post6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Post6: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - blog: Blog6? = nil, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + blog: Blog6? = nil, + comments: List? = [] + ) { + self.init( + id: id, title: title, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - blog: Blog6? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + blog: Blog6? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.blog = blog @@ -34,4 +47,4 @@ public struct Post6: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/PostEditor5+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/PostEditor5+Schema.swift index e71af25b39..19a150f67a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/PostEditor5+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/PostEditor5+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostEditor5 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension PostEditor5 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case post case editor case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let postEditor5 = PostEditor5.keys - + model.pluralName = "PostEditor5s" - + model.attributes( .index(fields: ["postID", "editorID"], name: "byPost5"), .index(fields: ["editorID", "postID"], name: "byEditor5") ) - + model.fields( .id(), .belongsTo(postEditor5.post, is: .required, ofType: Post5.self, targetName: "postID"), @@ -33,4 +40,4 @@ extension PostEditor5 { .field(postEditor5.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/PostEditor5.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/PostEditor5.swift index 137855324e..811e733d87 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/PostEditor5.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/PostEditor5.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostEditor5: Model { public var editor: User5 public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - post: Post5, - editor: User5) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + post: Post5, + editor: User5 + ) { + self.init( + id: id, post: post, editor: editor, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - post: Post5, - editor: User5, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + post: Post5, + editor: User5, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.post = post self.editor = editor self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/PostStatus.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/PostStatus.swift index 028109105e..8233e7fa11 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/PostStatus.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/PostStatus.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -6,4 +13,4 @@ public enum PostStatus: String, EnumPersistable { case `private` = "PRIVATE" case draft = "DRAFT" case published = "PUBLISHED" -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project1+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project1+Schema.swift index 685894c1e4..d18c0e1430 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project1+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project1+Schema.swift @@ -1,25 +1,32 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project1 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Project1 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case team case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let project1 = Project1.keys - + model.pluralName = "Project1s" - + model.fields( .id(), .field(project1.name, is: .optional, ofType: .string), @@ -28,4 +35,4 @@ extension Project1 { .field(project1.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project1.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project1.swift index 2976be7151..281da8c4a9 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project1.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project1.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Project1: Model { public var team: Team1? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String? = nil, - team: Team1? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team1? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team1? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team1? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.team = team self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project2+Schema.swift index d49e19a581..80b1991ba6 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project2+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Project2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case teamID @@ -12,15 +19,15 @@ extension Project2 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let project2 = Project2.keys - + model.pluralName = "Project2s" - + model.fields( .id(), .field(project2.name, is: .optional, ofType: .string), @@ -30,4 +37,4 @@ extension Project2 { .field(project2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project2.swift index bbbd615678..36ce1f4487 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Project2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Project2: Model { public var team: Team2? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2? = nil + ) { + self.init( + id: id, name: name, teamID: teamID, team: team, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.teamID = teamID @@ -34,4 +47,4 @@ public struct Project2: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ScalarContainer+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ScalarContainer+Schema.swift index 0efe2b05ba..6f0d8ff99e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ScalarContainer+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ScalarContainer+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ScalarContainer { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ScalarContainer { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case myString case myInt @@ -22,15 +29,15 @@ extension ScalarContainer { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let scalarContainer = ScalarContainer.keys - + model.pluralName = "ScalarContainers" - + model.fields( .id(), .field(scalarContainer.myString, is: .optional, ofType: .string), @@ -50,4 +57,4 @@ extension ScalarContainer { .field(scalarContainer.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ScalarContainer.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ScalarContainer.swift index 9559211652..ee87c57ecd 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ScalarContainer.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/ScalarContainer.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -19,22 +26,25 @@ public struct ScalarContainer: Model { public var myIPAddress: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - myString: String? = nil, - myInt: Int? = nil, - myDouble: Double? = nil, - myBool: Bool? = nil, - myDate: Temporal.Date? = nil, - myTime: Temporal.Time? = nil, - myDateTime: Temporal.DateTime? = nil, - myTimeStamp: Int? = nil, - myEmail: String? = nil, - myJSON: String? = nil, - myPhone: String? = nil, - myURL: String? = nil, - myIPAddress: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + myString: String? = nil, + myInt: Int? = nil, + myDouble: Double? = nil, + myBool: Bool? = nil, + myDate: Temporal.Date? = nil, + myTime: Temporal.Time? = nil, + myDateTime: Temporal.DateTime? = nil, + myTimeStamp: Int? = nil, + myEmail: String? = nil, + myJSON: String? = nil, + myPhone: String? = nil, + myURL: String? = nil, + myIPAddress: String? = nil + ) { + self.init( + id: id, myString: myString, myInt: myInt, myDouble: myDouble, @@ -49,24 +59,27 @@ public struct ScalarContainer: Model { myURL: myURL, myIPAddress: myIPAddress, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - myString: String? = nil, - myInt: Int? = nil, - myDouble: Double? = nil, - myBool: Bool? = nil, - myDate: Temporal.Date? = nil, - myTime: Temporal.Time? = nil, - myDateTime: Temporal.DateTime? = nil, - myTimeStamp: Int? = nil, - myEmail: String? = nil, - myJSON: String? = nil, - myPhone: String? = nil, - myURL: String? = nil, - myIPAddress: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + myString: String? = nil, + myInt: Int? = nil, + myDouble: Double? = nil, + myBool: Bool? = nil, + myDate: Temporal.Date? = nil, + myTime: Temporal.Time? = nil, + myDateTime: Temporal.DateTime? = nil, + myTimeStamp: Int? = nil, + myEmail: String? = nil, + myJSON: String? = nil, + myPhone: String? = nil, + myURL: String? = nil, + myIPAddress: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.myString = myString self.myInt = myInt @@ -84,4 +97,4 @@ public struct ScalarContainer: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team1+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team1+Schema.swift index 9a0e3f9707..f589eb16ec 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team1+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team1+Schema.swift @@ -1,24 +1,31 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team1 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team1 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team1 = Team1.keys - + model.pluralName = "Team1s" - + model.fields( .id(), .field(team1.name, is: .required, ofType: .string), @@ -26,4 +33,4 @@ extension Team1 { .field(team1.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team1.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team1.swift index 5a641dd9c9..8f5c0b9f44 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team1.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team1.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Team1: Model { public var name: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team2+Schema.swift index 684253fe6a..aebd17466a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team2+Schema.swift @@ -1,24 +1,31 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team2 = Team2.keys - + model.pluralName = "Team2s" - + model.fields( .id(), .field(team2.name, is: .required, ofType: .string), @@ -26,4 +33,4 @@ extension Team2 { .field(team2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team2.swift index 3c5ab9f91c..cec6e39d68 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/Team2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Team2: Model { public var name: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/TestEnum.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/TestEnum.swift index 8c0fdf51ef..774eca554f 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/TestEnum.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/TestEnum.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,4 +12,4 @@ import Foundation public enum TestEnum: String, EnumPersistable { case valueOne = "VALUE_ONE" case valueTwo = "VALUE_TWO" -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/User5+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/User5+Schema.swift index 82e4c569db..60f0678b52 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/User5+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/User5+Schema.swift @@ -1,25 +1,32 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension User5 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension User5 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case username case posts case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let user5 = User5.keys - + model.pluralName = "User5s" - + model.fields( .id(), .field(user5.username, is: .required, ofType: .string), @@ -28,4 +35,4 @@ extension User5 { .field(user5.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/User5.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/User5.swift index ff56db1e40..32727a0c3c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/User5.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Models/User5.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct User5: Model { public var posts: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - username: String, - posts: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + username: String, + posts: List? = [] + ) { + self.init( + id: id, username: username, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - username: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + username: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.username = username self.posts = posts self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Todo.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Todo.swift index 2a88d92570..0c6e1cb0de 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Todo.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginFunctionalTests/Todo.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct Todo: Decodable { let typename: String @@ -48,15 +48,15 @@ class CreateTodoMutation { static func variables(id: String? = nil, name: String?, description: String? = nil) -> [String: Any] { var input: [String: Any] = [:] - if let id = id { + if let id { input.updateValue(id, forKey: "id") } - if let name = name { + if let name { input.updateValue(name, forKey: "name") } - if let description = description { + if let description { input.updateValue(description, forKey: "description") } @@ -92,10 +92,10 @@ class UpdateTodoMutation { static func variables(id: String, name: String? = nil, description: String? = nil) -> [String: Any] { var input: [String: Any] = [:] input.updateValue(id, forKey: "id") - if let name = name { + if let name { input.updateValue(name, forKey: "name") } - if let description = description { + if let description { input.updateValue(description, forKey: "description") } return ["input": input] @@ -119,7 +119,7 @@ class DeleteTodoMutation { static func variables(id: String?) -> [String: Any] { var input: [String: Any] = [:] - if let id = id { + if let id { input.updateValue(id, forKey: "id") } @@ -166,20 +166,22 @@ class ListTodosQuery { }\n} """ - static func variables(filter: [String: Any]? = nil, - limit: Int? = nil, - nextToken: String? = nil) -> [String: Any] { + static func variables( + filter: [String: Any]? = nil, + limit: Int? = nil, + nextToken: String? = nil + ) -> [String: Any] { var input: [String: Any] = [:] - if let filter = filter { + if let filter { input.updateValue(filter, forKey: "filter") } - if let limit = limit { + if let limit { input.updateValue(limit, forKey: "limit") } - if let nextToken = nextToken { + if let nextToken { input.updateValue(nextToken, forKey: "nextToken") } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/AWSAPIPluginGen2GraphQLBaseTest.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/AWSAPIPluginGen2GraphQLBaseTest.swift index b3ae499f53..5e19af4f0c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/AWSAPIPluginGen2GraphQLBaseTest.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/AWSAPIPluginGen2GraphQLBaseTest.swift @@ -5,17 +5,17 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import AWSAPIPlugin @_spi(InternalAmplifyConfiguration) @testable import Amplify @testable import APIHostApp @testable import AWSPluginsCore -import AWSCognitoAuthPlugin class AWSAPIPluginGen2GraphQLBaseTest: XCTestCase { var defaultTestEmail = "test-\(UUID().uuidString)@amazon.com" - + var amplifyConfig: AmplifyOutputsData! override func setUp() { @@ -41,9 +41,11 @@ class AWSAPIPluginGen2GraphQLBaseTest: XCTestCase { /// Setup API with given models /// - Parameter models: DataStore models - func setup(withModels models: AmplifyModelRegistration, - logLevel: LogLevel = .verbose, - withAuthPlugin: Bool = false) async { + func setup( + withModels models: AmplifyModelRegistration, + logLevel: LogLevel = .verbose, + withAuthPlugin: Bool = false + ) async { do { setupConfig() Amplify.Logging.logLevel = logLevel @@ -110,8 +112,10 @@ class AWSAPIPluginGen2GraphQLBaseTest: XCTestCase { case loaded(model: M?) } - func assertLazyReference(_ lazyModel: LazyReference, - state: AssertLazyModelState) { + func assertLazyReference( + _ lazyModel: LazyReference, + state: AssertLazyModelState + ) { switch state { case .notLoaded(let expectedIdentifiers): if case .notLoaded(let identifiers) = lazyModel.modelProvider.getState() { @@ -121,7 +125,7 @@ class AWSAPIPluginGen2GraphQLBaseTest: XCTestCase { } case .loaded(let expectedModel): if case .loaded(let model) = lazyModel.modelProvider.getState() { - guard let expectedModel = expectedModel, let model = model else { + guard let expectedModel, let model else { XCTAssertNil(model) return } @@ -137,7 +141,7 @@ class AWSAPIPluginGen2GraphQLBaseTest: XCTestCase { case isLoaded(count: Int) } - func assertList(_ list: List, state: AssertListState) { + func assertList(_ list: List, state: AssertListState) { switch state { case .isNotLoaded(let expectedAssociatedIdentifiers, let expectedAssociatedFields): if case .notLoaded(let associatedIdentifiers, let associatedFields) = list.listProvider.getState() { @@ -155,12 +159,12 @@ class AWSAPIPluginGen2GraphQLBaseTest: XCTestCase { } } - func assertModelExists(_ model: M) async throws { + func assertModelExists(_ model: some Model) async throws { let modelExists = try await query(for: model) != nil XCTAssertTrue(modelExists) } - func assertModelDoesNotExist(_ model: M) async throws { + func assertModelDoesNotExist(_ model: some Model) async throws { let modelExists = try await query(for: model) != nil XCTAssertFalse(modelExists) } @@ -168,8 +172,10 @@ class AWSAPIPluginGen2GraphQLBaseTest: XCTestCase { func query(for model: M, includes: IncludedAssociations = { _ in [] }) async throws -> M? { let id = M.identifier(model)(schema: model.schema) - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: model.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: model.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) if let modelPath = M.rootPath as? ModelPath { @@ -179,10 +185,12 @@ class AWSAPIPluginGen2GraphQLBaseTest: XCTestCase { documentBuilder.add(decorator: ModelIdDecorator(identifierFields: id.fields)) let document = documentBuilder.build() - let request = GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: M?.self, - decodePath: document.name) + let request = GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: M?.self, + decodePath: document.name + ) return try await query(request) } @@ -206,8 +214,7 @@ class AWSAPIPluginGen2GraphQLBaseTest: XCTestCase { } if let data = subscriptionEvent.extractData(), - try await verifyChange(data) - { + try await verifyChange(data) { eventReceived.fulfill() } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/AuthSignInHelper.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/AuthSignInHelper.swift index 768145ee0b..fe0547ea0f 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/AuthSignInHelper.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/AuthSignInHelper.swift @@ -21,13 +21,14 @@ enum AuthSignInHelper { username: String, password: String, email: String, - phoneNumber: String? = nil) async throws -> Bool { + phoneNumber: String? = nil + ) async throws -> Bool { var userAttributes = [ AuthUserAttribute(.email, value: email) ] - if let phoneNumber = phoneNumber { + if let phoneNumber { userAttributes.append(AuthUserAttribute(.phoneNumber, value: phoneNumber)) } @@ -45,13 +46,15 @@ enum AuthSignInHelper { username: String, password: String, email: String, - phoneNumber: String? = nil) async throws -> Bool { + phoneNumber: String? = nil + ) async throws -> Bool { await signOut() let signedUp = try await AuthSignInHelper.signUpUser( username: username, password: password, email: email, - phoneNumber: phoneNumber) + phoneNumber: phoneNumber + ) guard signedUp else { throw AuthError.invalidState("Auth sign up failed", "", nil) } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/GraphQLLocationPostUser1Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/GraphQLLocationPostUser1Tests.swift index 65fdc898ab..711321ee4a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/GraphQLLocationPostUser1Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/GraphQLLocationPostUser1Tests.swift @@ -19,7 +19,8 @@ final class GraphQLLocationPostUser1Tests: AWSAPIPluginGen2GraphQLBaseTest { let post = Post( location: .init( lat: 48.837006, - long: 8.28245)) + long: 8.28245 + )) let createdPost = try await Amplify.API.mutate(request: .create(post)).get() print("\(createdPost)") diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Location1+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Location1+Schema.swift index c3ecfd312c..b6f4d2b8af 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Location1+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Location1+Schema.swift @@ -1,26 +1,33 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Location1 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Location1 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case lat case long } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let location1 = Location1.keys - + model.listPluralName = "Location1s" model.syncPluralName = "Location1s" - + model.fields( .field(location1.lat, is: .optional, ofType: .double), .field(location1.long, is: .optional, ofType: .double) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Location1.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Location1.swift index c7bb5ace84..a47c2eaa28 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Location1.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Location1.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,4 +12,4 @@ import Foundation public struct Location1: Embeddable { var lat: Double? var long: Double? -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Post1+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Post1+Schema.swift index d6d325cb6d..f191f0f6d7 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Post1+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Post1+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post1 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post1 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case location case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post1 = Post1.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Post1s" model.syncPluralName = "Post1s" - + model.attributes( .primaryKey(fields: [post1.id]) ) - + model.fields( .field(post1.id, is: .required, ofType: .string), .field(post1.location, is: .optional, ofType: .embedded(type: Location1.self)), @@ -37,26 +44,26 @@ extension Post1 { .field(post1.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post1: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Post1 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Post1 { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Post1.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Post1.swift index 49096a3269..ff4b0e535c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Post1.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/Post1.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post1: Model { public var content: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - location: Location1? = nil, - content: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + location: Location1? = nil, + content: String? = nil + ) { + self.init( + id: id, location: location, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - location: Location1? = nil, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + location: Location1? = nil, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.location = location self.content = content self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/User1+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/User1+Schema.swift index cf451f68a5..2b63193c75 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/User1+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/User1+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension User1 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension User1 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case lastKnownLocation case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let user1 = User1.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "User1s" model.syncPluralName = "User1s" - + model.attributes( .primaryKey(fields: [user1.id]) ) - + model.fields( .field(user1.id, is: .required, ofType: .string), .field(user1.lastKnownLocation, is: .optional, ofType: .embedded(type: Location1.self)), @@ -35,23 +42,23 @@ extension User1 { .field(user1.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension User1: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == User1 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == User1 { + var id: FieldPath { + string("id") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/User1.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/User1.swift index fffb5a42e5..a292eda4ea 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/User1.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_1/User1.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct User1: Model { public var lastKnownLocation: Location1? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - lastKnownLocation: Location1? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + lastKnownLocation: Location1? = nil + ) { + self.init( + id: id, lastKnownLocation: lastKnownLocation, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - lastKnownLocation: Location1? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + lastKnownLocation: Location1? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.lastKnownLocation = lastKnownLocation self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_10/Customer10+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_10/Customer10+Schema.swift index 089a6a3d61..1f343cfdcb 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_10/Customer10+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_10/Customer10+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Customer10 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Customer10 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case phoneNumber @@ -12,25 +19,25 @@ extension Customer10 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let customer10 = Customer10.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Customer10s" model.syncPluralName = "Customer10s" - + model.attributes( .index(fields: ["accountRepresentativeId"], name: "customer10sByAccountRepresentativeId"), .primaryKey(fields: [customer10.id]) ) - + model.fields( .field(customer10.id, is: .required, ofType: .string), .field(customer10.name, is: .optional, ofType: .string), @@ -40,32 +47,32 @@ extension Customer10 { .field(customer10.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Customer10: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Customer10 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Customer10 { + var id: FieldPath { + string("id") } - public var name: FieldPath { - string("name") + var name: FieldPath { + string("name") } - public var phoneNumber: FieldPath { - string("phoneNumber") + var phoneNumber: FieldPath { + string("phoneNumber") } - public var accountRepresentativeId: FieldPath { - string("accountRepresentativeId") + var accountRepresentativeId: FieldPath { + string("accountRepresentativeId") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_10/Customer10.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_10/Customer10.swift index 5d5d2a959b..9920d1533a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_10/Customer10.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_10/Customer10.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Customer10: Model { public var accountRepresentativeId: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String? = nil, - phoneNumber: String? = nil, - accountRepresentativeId: String) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String? = nil, + phoneNumber: String? = nil, + accountRepresentativeId: String + ) { + self.init( + id: id, name: name, phoneNumber: phoneNumber, accountRepresentativeId: accountRepresentativeId, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - phoneNumber: String? = nil, - accountRepresentativeId: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + phoneNumber: String? = nil, + accountRepresentativeId: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.phoneNumber = phoneNumber @@ -34,4 +47,4 @@ public struct Customer10: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_10/GraphQLCustomer10Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_10/GraphQLCustomer10Tests.swift index 80cacd0df2..b0d8225fdc 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_10/GraphQLCustomer10Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_10/GraphQLCustomer10Tests.swift @@ -5,13 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLCustomer10Tests: AWSAPIPluginGen2GraphQLBaseTest { @@ -49,13 +48,14 @@ final class GraphQLCustomer10Tests: AWSAPIPluginGen2GraphQLBaseTest { let request = GraphQLRequest>( document: document, responseType: PaginatedList.self, - decodePath: operationName) + decodePath: operationName + ) let queriedCustomers = try await Amplify.API.query( request: request).get() // Code Snippet Ends - XCTAssertTrue(queriedCustomers.items.count != 0 || queriedCustomers.nextToken != nil) + XCTAssertTrue(!queriedCustomers.items.isEmpty || queriedCustomers.nextToken != nil) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_11/GraphQLPost11Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_11/GraphQLPost11Tests.swift index f8960e9fb0..1c8950f090 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_11/GraphQLPost11Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_11/GraphQLPost11Tests.swift @@ -21,7 +21,8 @@ final class GraphQLPost11Tests: AWSAPIPluginGen2GraphQLBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) } catch { XCTFail("Could not sign up and sign in user \(error)") } @@ -31,7 +32,8 @@ final class GraphQLPost11Tests: AWSAPIPluginGen2GraphQLBaseTest { let post = Post(title: "Hello World") let createdTodo = try await Amplify.API.mutate(request: .create( post, - authMode: .amazonCognitoUserPools)).get() + authMode: .amazonCognitoUserPools + )).get() } catch { print("Failed to create post", error) // Code Snippet Ends @@ -46,11 +48,12 @@ final class GraphQLPost11Tests: AWSAPIPluginGen2GraphQLBaseTest { do { let queriedPosts = try await Amplify.API.query(request: .list( Post.self, - authMode: .awsIAM)).get() + authMode: .awsIAM + )).get() print("Number of posts:", queriedPosts.count) // Code Snippet Ends - XCTAssertTrue(queriedPosts.count > 0 || queriedPosts.hasNextPage()) + XCTAssertTrue(!queriedPosts.isEmpty || queriedPosts.hasNextPage()) // Code Snippet Begins } catch { print("Failed to list posts", error) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_11/Post11+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_11/Post11+Schema.swift index 874efebc20..71252b983b 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_11/Post11+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_11/Post11+Schema.swift @@ -1,35 +1,42 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post11 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post11 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post11 = Post11.keys - + model.authRules = [ rule(allow: .public, provider: .iam, operations: [.read]), rule(allow: .owner, ownerField: "owner", identityClaim: "cognito:username", provider: .userPools, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Post11s" model.syncPluralName = "Post11s" - + model.attributes( .primaryKey(fields: [post11.id]) ) - + model.fields( .field(post11.id, is: .required, ofType: .string), .field(post11.title, is: .optional, ofType: .string), @@ -38,29 +45,29 @@ extension Post11 { .field(post11.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post11: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Post11 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Post11 { + var id: FieldPath { + string("id") } - public var title: FieldPath { - string("title") + var title: FieldPath { + string("title") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_11/Post11.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_11/Post11.swift index 11b513d670..b19d8e9999 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_11/Post11.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_11/Post11.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post11: Model { public var content: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String? = nil, - content: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String? = nil, + content: String? = nil + ) { + self.init( + id: id, title: title, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String? = nil, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String? = nil, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.content = content self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_12/GraphQLTodo12Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_12/GraphQLTodo12Tests.swift index 60faaadefa..d52bf9a78e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_12/GraphQLTodo12Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_12/GraphQLTodo12Tests.swift @@ -15,13 +15,14 @@ final class GraphQLTodo12Tests: AWSAPIPluginGen2GraphQLBaseTest { // https://docs.amplify.aws/react/build-a-backend/data/customize-authz/public-data-access/#add-public-authorization-rule-using-api-key-based-authentication func testCodeSnippet() async throws { await setup(withModels: Todo12Models()) - + // Code Snippet begins do { let todo = Todo(content: "My new todo") let createdTodo = try await Amplify.API.mutate(request: .create( todo, - authMode: .apiKey)).get() + authMode: .apiKey + )).get() } catch { print("Failed to create todo", error) // Code Snippet Ends diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_12/Todo12+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_12/Todo12+Schema.swift index a9ded86979..201ea658f8 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_12/Todo12+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_12/Todo12+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Todo12 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Todo12 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let todo12 = Todo12.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Todo12s" model.syncPluralName = "Todo12s" - + model.attributes( .primaryKey(fields: [todo12.id]) ) - + model.fields( .field(todo12.id, is: .required, ofType: .string), .field(todo12.content, is: .optional, ofType: .string), @@ -35,26 +42,26 @@ extension Todo12 { .field(todo12.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Todo12: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Todo12 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Todo12 { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_12/Todo12.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_12/Todo12.swift index 34639f2153..0f24e2a5f4 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_12/Todo12.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_12/Todo12.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Todo12: Model { public var content: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_13/GraphQLTodo13Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_13/GraphQLTodo13Tests.swift index dc81e3aecd..cb3556882d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_13/GraphQLTodo13Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_13/GraphQLTodo13Tests.swift @@ -21,7 +21,8 @@ final class GraphQLTodo13Tests: AWSAPIPluginGen2GraphQLBaseTest { let todo = Todo(content: "My new todo") let createdTodo = try await Amplify.API.mutate(request: .create( todo, - authMode: .awsIAM)).get() + authMode: .awsIAM + )).get() // Code Snippet Ends XCTAssertEqual(createdTodo.id, todo.id) // Code Snippet Begins diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_13/Todo13+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_13/Todo13+Schema.swift index f8646c9a76..37aa1af60a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_13/Todo13+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_13/Todo13+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Todo13 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Todo13 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let todo13 = Todo13.keys - + model.authRules = [ rule(allow: .public, provider: .iam, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Todo13s" model.syncPluralName = "Todo13s" - + model.attributes( .primaryKey(fields: [todo13.id]) ) - + model.fields( .field(todo13.id, is: .required, ofType: .string), .field(todo13.content, is: .optional, ofType: .string), @@ -35,26 +42,26 @@ extension Todo13 { .field(todo13.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Todo13: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Todo13 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Todo13 { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_13/Todo13.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_13/Todo13.swift index cce0e45d70..2485b1d811 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_13/Todo13.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_13/Todo13.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Todo13: Model { public var content: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_14/GraphQLTodo14Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_14/GraphQLTodo14Tests.swift index dcb9fa2e6d..3752e50008 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_14/GraphQLTodo14Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_14/GraphQLTodo14Tests.swift @@ -21,7 +21,8 @@ final class GraphQLTodo14Tests: AWSAPIPluginGen2GraphQLBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) } catch { XCTFail("Could not sign up and sign in user \(error)") } @@ -31,7 +32,8 @@ final class GraphQLTodo14Tests: AWSAPIPluginGen2GraphQLBaseTest { let todo = Todo(content: "My new todo") let createdTodo = try await Amplify.API.mutate(request: .create( todo, - authMode: .amazonCognitoUserPools)).get() + authMode: .amazonCognitoUserPools + )).get() // Code Snippet Ends XCTAssertEqual(createdTodo.id, todo.id) // Code Snippet Begins diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_14/Todo14+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_14/Todo14+Schema.swift index c7b1cb8a9a..5be8993e1d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_14/Todo14+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_14/Todo14+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Todo14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Todo14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let todo14 = Todo14.keys - + model.authRules = [ rule(allow: .owner, ownerField: "owner", identityClaim: "cognito:username", provider: .userPools, operations: [.create, .read, .update]) ] - + model.listPluralName = "Todo14s" model.syncPluralName = "Todo14s" - + model.attributes( .primaryKey(fields: [todo14.id]) ) - + model.fields( .field(todo14.id, is: .required, ofType: .string), .field(todo14.content, is: .optional, ofType: .string), @@ -35,26 +42,26 @@ extension Todo14 { .field(todo14.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Todo14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Todo14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Todo14 { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_14/Todo14.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_14/Todo14.swift index 27d172c39b..887686110d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_14/Todo14.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_14/Todo14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Todo14: Model { public var content: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_15/GraphQLTodo15Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_15/GraphQLTodo15Tests.swift index d7cd68305f..be24132344 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_15/GraphQLTodo15Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_15/GraphQLTodo15Tests.swift @@ -21,7 +21,8 @@ final class GraphQLTodo15Tests: AWSAPIPluginGen2GraphQLBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) } catch { XCTFail("Could not sign up and sign in user \(error)") } @@ -31,7 +32,8 @@ final class GraphQLTodo15Tests: AWSAPIPluginGen2GraphQLBaseTest { let todo = Todo(content: "My new todo") let createdTodo = try await Amplify.API.mutate(request: .create( todo, - authMode: .amazonCognitoUserPools)).get() + authMode: .amazonCognitoUserPools + )).get() // Code Snippet Ends XCTAssertEqual(createdTodo.id, todo.id) // Code Snippet Begins @@ -51,14 +53,16 @@ final class GraphQLTodo15Tests: AWSAPIPluginGen2GraphQLBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) } catch { XCTFail("Could not sign up and sign in user \(error)") } let todo = Todo(content: "My new todo") var createdTodo = try await Amplify.API.mutate(request: .create( todo, - authMode: .amazonCognitoUserPools)).get() + authMode: .amazonCognitoUserPools + )).get() let otherUserId = "otherUserId" // Code Snippet begins @@ -66,7 +70,8 @@ final class GraphQLTodo15Tests: AWSAPIPluginGen2GraphQLBaseTest { createdTodo.owners?.append(otherUserId) let updatedTodo = try await Amplify.API.mutate(request: .update( createdTodo, - authMode: .amazonCognitoUserPools)).get() + authMode: .amazonCognitoUserPools + )).get() // Code Snippet Ends XCTAssertEqual(updatedTodo.id, todo.id) XCTAssertEqual(updatedTodo.owners?.count, 2) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_15/Todo15+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_15/Todo15+Schema.swift index 8b271ff315..a1fbbdb25f 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_15/Todo15+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_15/Todo15+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Todo15 { +public extension Todo15 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case owners @@ -12,10 +19,10 @@ extension Todo15 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todo15 = Todo15.keys model.authRules = [ @@ -37,29 +44,29 @@ extension Todo15 { .field(todo15.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } + class Path: ModelPath { } - public static var rootPath: PropertyContainerPath? { Path() } + static var rootPath: PropertyContainerPath? { Path() } } extension Todo15: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Todo15 { - public var id: FieldPath { +public extension ModelPath where ModelType == Todo15 { + var id: FieldPath { string("id") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var owners: FieldPath { + var owners: FieldPath { string("owners") } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_15/Todo15.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_15/Todo15.swift index 4e68848094..b61b3e4109 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_15/Todo15.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_15/Todo15.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,20 +16,26 @@ public struct Todo15: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil, - owners: [String?]? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil, + owners: [String?]? = nil + ) { + self.init( + id: id, content: content, owners: owners, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - owners: [String?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + owners: [String?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.owners = owners diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_16/GraphQLTodo16Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_16/GraphQLTodo16Tests.swift index 5ccc18db98..6da1157b4a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_16/GraphQLTodo16Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_16/GraphQLTodo16Tests.swift @@ -21,7 +21,8 @@ final class GraphQLTodo16Tests: AWSAPIPluginGen2GraphQLBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) } catch { XCTFail("Could not sign up and sign in user \(error)") } @@ -31,7 +32,8 @@ final class GraphQLTodo16Tests: AWSAPIPluginGen2GraphQLBaseTest { let todo = Todo(content: "My new todo") let createdTodo = try await Amplify.API.mutate(request: .create( todo, - authMode: .amazonCognitoUserPools)).get() + authMode: .amazonCognitoUserPools + )).get() // Code Snippet Ends XCTAssertEqual(createdTodo.id, todo.id) // Code Snippet Begins diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_16/Todo16+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_16/Todo16+Schema.swift index f7cc2e55f8..c0183e14cf 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_16/Todo16+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_16/Todo16+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Todo16 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Todo16 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let todo16 = Todo16.keys - + model.authRules = [ rule(allow: .private, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Todo16s" model.syncPluralName = "Todo16s" - + model.attributes( .primaryKey(fields: [todo16.id]) ) - + model.fields( .field(todo16.id, is: .required, ofType: .string), .field(todo16.content, is: .optional, ofType: .string), @@ -35,26 +42,26 @@ extension Todo16 { .field(todo16.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Todo16: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Todo16 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Todo16 { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_16/Todo16.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_16/Todo16.swift index 11fc206310..b4b403f17e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_16/Todo16.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_16/Todo16.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Todo16: Model { public var content: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_17/GraphQLTodo17Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_17/GraphQLTodo17Tests.swift index c1199f82a8..d0c9ecf8b2 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_17/GraphQLTodo17Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_17/GraphQLTodo17Tests.swift @@ -21,7 +21,8 @@ final class GraphQLTodo17Tests: AWSAPIPluginGen2GraphQLBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) } catch { XCTFail("Could not sign up and sign in user \(error)") } @@ -31,7 +32,8 @@ final class GraphQLTodo17Tests: AWSAPIPluginGen2GraphQLBaseTest { let todo = Todo(content: "My new todo") let createdTodo = try await Amplify.API.mutate(request: .create( todo, - authMode: .awsIAM)).get() + authMode: .awsIAM + )).get() // Code Snippet Ends XCTAssertEqual(createdTodo.id, todo.id) // Code Snippet Begins diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_17/Todo17+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_17/Todo17+Schema.swift index 49fc0d8cf8..a4077df7d7 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_17/Todo17+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_17/Todo17+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Todo17 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Todo17 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let todo17 = Todo17.keys - + model.authRules = [ rule(allow: .private, provider: .iam, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Todo17s" model.syncPluralName = "Todo17s" - + model.attributes( .primaryKey(fields: [todo17.id]) ) - + model.fields( .field(todo17.id, is: .required, ofType: .string), .field(todo17.content, is: .optional, ofType: .string), @@ -35,26 +42,26 @@ extension Todo17 { .field(todo17.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Todo17: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Todo17 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Todo17 { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_17/Todo17.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_17/Todo17.swift index 5e7f05fb8f..75e8f0fb40 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_17/Todo17.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_17/Todo17.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Todo17: Model { public var content: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_18/GraphQLSalary18Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_18/GraphQLSalary18Tests.swift index 83fd00da50..7ee12d0b0f 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_18/GraphQLSalary18Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_18/GraphQLSalary18Tests.swift @@ -20,19 +20,22 @@ final class GraphQLSalary18Tests: AWSAPIPluginGen2GraphQLBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) } catch { XCTFail("Could not sign up and sign in user \(error)") } - + // Code Snippet begins do { let salary = Salary( wage: 50.25, - currency: "USD") + currency: "USD" + ) let createdSalary = try await Amplify.API.mutate(request: .create( salary, - authMode: .amazonCognitoUserPools)).get() + authMode: .amazonCognitoUserPools + )).get() // Code Snippet Ends XCTFail("Should not make it to here. Expected to catch failure since user is not in the Admin group.") // Code Snippet begins diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_18/Salary18+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_18/Salary18+Schema.swift index c38405bfa8..bbcf7fca0f 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_18/Salary18+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_18/Salary18+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Salary18 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Salary18 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case wage case currency case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let salary18 = Salary18.keys - + model.authRules = [ rule(allow: .groups, groupClaim: "cognito:groups", groups: ["Admin"], provider: .userPools, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Salary18s" model.syncPluralName = "Salary18s" - + model.attributes( .primaryKey(fields: [salary18.id]) ) - + model.fields( .field(salary18.id, is: .required, ofType: .string), .field(salary18.wage, is: .optional, ofType: .double), @@ -37,29 +44,29 @@ extension Salary18 { .field(salary18.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Salary18: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Salary18 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Salary18 { + var id: FieldPath { + string("id") } - public var wage: FieldPath { - double("wage") + var wage: FieldPath { + double("wage") } - public var currency: FieldPath { - string("currency") + var currency: FieldPath { + string("currency") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_18/Salary18.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_18/Salary18.swift index 041e8faaea..4ff6dc5a64 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_18/Salary18.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_18/Salary18.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Salary18: Model { public var currency: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - wage: Double? = nil, - currency: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + wage: Double? = nil, + currency: String? = nil + ) { + self.init( + id: id, wage: wage, currency: currency, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - wage: Double? = nil, - currency: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + wage: Double? = nil, + currency: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.wage = wage self.currency = currency self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/GraphQLPostVideoPrivacySetting2Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/GraphQLPostVideoPrivacySetting2Tests.swift index 45d7c66a1b..53711d8dd7 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/GraphQLPostVideoPrivacySetting2Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/GraphQLPostVideoPrivacySetting2Tests.swift @@ -19,7 +19,8 @@ final class GraphQLPostVideoPrivacySettings2Tests: AWSAPIPluginGen2GraphQLBaseTe // Code Snippet Begins let post = Post( content: "hello", - privacySetting: .private) + privacySetting: .private + ) let createdPost = try await Amplify.API.mutate(request: .create(post)).get() // Code Snippet Ends diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Post2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Post2+Schema.swift index f8aaae10fc..e5164fec5f 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Post2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Post2+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case privacySetting case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post2 = Post2.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Post2s" model.syncPluralName = "Post2s" - + model.attributes( .primaryKey(fields: [post2.id]) ) - + model.fields( .field(post2.id, is: .required, ofType: .string), .field(post2.content, is: .optional, ofType: .string), @@ -37,26 +44,26 @@ extension Post2 { .field(post2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Post2 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Post2 { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Post2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Post2.swift index 9ed7b58d6b..22e22e02e1 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Post2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Post2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post2: Model { public var privacySetting: PrivacySetting2? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - privacySetting: PrivacySetting2? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + privacySetting: PrivacySetting2? = nil + ) { + self.init( + id: id, content: content, privacySetting: privacySetting, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - privacySetting: PrivacySetting2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + privacySetting: PrivacySetting2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.privacySetting = privacySetting self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/PrivacySetting2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/PrivacySetting2.swift index a3cbe56cc4..282b318fc1 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/PrivacySetting2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/PrivacySetting2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -6,4 +13,4 @@ public enum PrivacySetting2: String, EnumPersistable { case `private` = "PRIVATE" case friendsOnly = "FRIENDS_ONLY" case `public` = "PUBLIC" -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Video2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Video2+Schema.swift index ae333846a0..568798cf1e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Video2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Video2+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Video2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Video2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case privacySetting case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let video2 = Video2.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Video2s" model.syncPluralName = "Video2s" - + model.attributes( .primaryKey(fields: [video2.id]) ) - + model.fields( .field(video2.id, is: .required, ofType: .string), .field(video2.privacySetting, is: .optional, ofType: .enum(type: PrivacySetting2.self)), @@ -35,23 +42,23 @@ extension Video2 { .field(video2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Video2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Video2 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Video2 { + var id: FieldPath { + string("id") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Video2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Video2.swift index c066eefa31..c0509ab14c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Video2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_2/Video2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Video2: Model { public var privacySetting: PrivacySetting2? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - privacySetting: PrivacySetting2? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + privacySetting: PrivacySetting2? = nil + ) { + self.init( + id: id, privacySetting: privacySetting, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - privacySetting: PrivacySetting2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + privacySetting: PrivacySetting2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.privacySetting = privacySetting self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/GraphQLTeamMember3Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/GraphQLTeamMember3Tests.swift index 1ae35afd0d..7829c0f5be 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/GraphQLTeamMember3Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/GraphQLTeamMember3Tests.swift @@ -24,7 +24,8 @@ final class GraphQLTeamMember3Tests: AWSAPIPluginGen2GraphQLBaseTest { let member = Member( name: "Tim", - team: createdTeam) // Directly pass in the team instance + team: createdTeam + ) // Directly pass in the team instance let createdMember = try await Amplify.API.mutate(request: .create(member)) } catch { print("Create team or member failed", error) @@ -44,7 +45,8 @@ final class GraphQLTeamMember3Tests: AWSAPIPluginGen2GraphQLBaseTest { let oldTeamCreated = try await Amplify.API.mutate(request: .create(oldTeam)).get() let member = Member( name: "Tim", - team: oldTeamCreated) // Directly pass in the post instance + team: oldTeamCreated + ) // Directly pass in the post instance var existingMember = try await Amplify.API.mutate(request: .create(member)).get() // Code Snippet Begins @@ -79,7 +81,8 @@ final class GraphQLTeamMember3Tests: AWSAPIPluginGen2GraphQLBaseTest { let teamCreated = try await Amplify.API.mutate(request: .create(team)).get() let member = Member( name: "Tim", - team: teamCreated) // Directly pass in the post instance + team: teamCreated + ) // Directly pass in the post instance var existingMember = try await Amplify.API.mutate(request: .create(member)).get() // Code Snippet Begins @@ -102,7 +105,8 @@ final class GraphQLTeamMember3Tests: AWSAPIPluginGen2GraphQLBaseTest { let teamCreated = try await Amplify.API.mutate(request: .create(team)).get() let member = Member( name: "Tim", - team: teamCreated) // Directly pass in the post instance + team: teamCreated + ) // Directly pass in the post instance _ = try await Amplify.API.mutate(request: .create(member)).get() // Code Snippet Begins @@ -110,7 +114,8 @@ final class GraphQLTeamMember3Tests: AWSAPIPluginGen2GraphQLBaseTest { let queriedTeam = try await Amplify.API.query( request: .get( Team.self, - byIdentifier: team.identifier)).get() + byIdentifier: team.identifier + )).get() guard let queriedTeam, let members = queriedTeam.members else { print("Missing team or members") @@ -122,7 +127,7 @@ final class GraphQLTeamMember3Tests: AWSAPIPluginGen2GraphQLBaseTest { try await members.fetch() print("Number of members: \(members.count)") // Code Snippet Ends - XCTAssertTrue(members.count > 0) + XCTAssertTrue(!members.isEmpty) // Code Snippet Begins } catch { print("Failed to fetch team or members", error) @@ -140,7 +145,8 @@ final class GraphQLTeamMember3Tests: AWSAPIPluginGen2GraphQLBaseTest { let teamCreated = try await Amplify.API.mutate(request: .create(team)).get() let member = Member( name: "Tim", - team: teamCreated) // Directly pass in the post instance + team: teamCreated + ) // Directly pass in the post instance _ = try await Amplify.API.mutate(request: .create(member)).get() // Code Snippet Begins @@ -149,7 +155,8 @@ final class GraphQLTeamMember3Tests: AWSAPIPluginGen2GraphQLBaseTest { request: .get( Team.self, byIdentifier: team.identifier, - includes: { team in [team.members]})) + includes: { team in [team.members]} + )) .get() guard let queriedTeamWithMembers, let members = queriedTeamWithMembers.members else { print("Missing team or members") @@ -160,7 +167,7 @@ final class GraphQLTeamMember3Tests: AWSAPIPluginGen2GraphQLBaseTest { } print("Number of members: \(members.count)") // Code Snippet Ends - XCTAssertTrue(members.count > 0) + XCTAssertTrue(!members.isEmpty) // Code Snippet Begins } catch { print("Failed to fetch team with members", error) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Member3+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Member3+Schema.swift index e288a808c0..13bb3215c2 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Member3+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Member3+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Member3 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Member3 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case team case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let member3 = Member3.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Member3s" model.syncPluralName = "Member3s" - + model.attributes( .primaryKey(fields: [member3.id]) ) - + model.fields( .field(member3.id, is: .required, ofType: .string), .field(member3.name, is: .required, ofType: .string), @@ -37,29 +44,29 @@ extension Member3 { .field(member3.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Member3: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Member3 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Member3 { + var id: FieldPath { + string("id") } - public var name: FieldPath { - string("name") + var name: FieldPath { + string("name") } - public var team: ModelPath { - Team3.Path(name: "team", parent: self) + var team: ModelPath { + Team3.Path(name: "team", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Member3.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Member3.swift index 10f6c94442..fbaa6047b1 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Member3.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Member3.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,29 +12,35 @@ import Foundation public struct Member3: Model { public let id: String public var name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team3? { - get async throws { + get async throws { try await _team.get() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - team: Team3? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + team: Team3? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - team: Team3? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + team: Team3? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self._team = LazyReference(team) @@ -35,15 +48,15 @@ public struct Member3: Model { self.updatedAt = updatedAt } public mutating func setTeam(_ team: Team3? = nil) { - self._team = LazyReference(team) + _team = LazyReference(team) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -53,4 +66,4 @@ public struct Member3: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Team3+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Team3+Schema.swift index b09f9b50ea..9a22d2dca0 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Team3+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Team3+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team3 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team3 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case mantra case members case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team3 = Team3.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Team3s" model.syncPluralName = "Team3s" - + model.attributes( .primaryKey(fields: [team3.id]) ) - + model.fields( .field(team3.id, is: .required, ofType: .string), .field(team3.mantra, is: .required, ofType: .string), @@ -37,29 +44,29 @@ extension Team3 { .field(team3.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team3: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Team3 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Team3 { + var id: FieldPath { + string("id") } - public var mantra: FieldPath { - string("mantra") + var mantra: FieldPath { + string("mantra") } - public var members: ModelPath { - Member3.Path(name: "members", isCollection: true, parent: self) + var members: ModelPath { + Member3.Path(name: "members", isCollection: true, parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Team3.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Team3.swift index 2cf2dba585..78f496c7e6 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Team3.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_3/Team3.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Team3: Model { public var members: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - mantra: String, - members: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + mantra: String, + members: List? = [] + ) { + self.init( + id: id, mantra: mantra, members: members, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - mantra: String, - members: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + mantra: String, + members: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.mantra = mantra self.members = members self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Cart4+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Cart4+Schema.swift index f524ceab99..1e54d58520 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Cart4+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Cart4+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Cart4 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Cart4 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case items case customer case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let cart4 = Cart4.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Cart4s" model.syncPluralName = "Cart4s" - + model.attributes( .primaryKey(fields: [cart4.id]) ) - + model.fields( .field(cart4.id, is: .required, ofType: .string), .field(cart4.items, is: .optional, ofType: .embeddedCollection(of: String.self)), @@ -37,29 +44,29 @@ extension Cart4 { .field(cart4.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Cart4: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Cart4 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Cart4 { + var id: FieldPath { + string("id") } - public var items: FieldPath { - string("items") + var items: FieldPath { + string("items") } - public var customer: ModelPath { - Customer4.Path(name: "customer", parent: self) + var customer: ModelPath { + Customer4.Path(name: "customer", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Cart4.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Cart4.swift index 31d636fd1e..3493796d0a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Cart4.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Cart4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,29 +12,35 @@ import Foundation public struct Cart4: Model { public let id: String public var items: [String]? - internal var _customer: LazyReference + var _customer: LazyReference public var customer: Customer4? { - get async throws { + get async throws { try await _customer.get() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - items: [String]? = nil, - customer: Customer4? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + items: [String]? = nil, + customer: Customer4? = nil + ) { + self.init( + id: id, items: items, customer: customer, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - items: [String]? = nil, - customer: Customer4? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + items: [String]? = nil, + customer: Customer4? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.items = items self._customer = LazyReference(customer) @@ -35,15 +48,15 @@ public struct Cart4: Model { self.updatedAt = updatedAt } public mutating func setCustomer(_ customer: Customer4? = nil) { - self._customer = LazyReference(customer) + _customer = LazyReference(customer) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - items = try values.decode([String].self, forKey: .items) - _customer = try values.decodeIfPresent(LazyReference.self, forKey: .customer) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.items = try values.decode([String].self, forKey: .items) + self._customer = try values.decodeIfPresent(LazyReference.self, forKey: .customer) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -53,4 +66,4 @@ public struct Cart4: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Customer4+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Customer4+Schema.swift index 56b085c0c3..e003f2a098 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Customer4+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Customer4+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Customer4 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Customer4 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case activeCart case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let customer4 = Customer4.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Customer4s" model.syncPluralName = "Customer4s" - + model.attributes( .primaryKey(fields: [customer4.id]) ) - + model.fields( .field(customer4.id, is: .required, ofType: .string), .field(customer4.name, is: .optional, ofType: .string), @@ -37,29 +44,29 @@ extension Customer4 { .field(customer4.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Customer4: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Customer4 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Customer4 { + var id: FieldPath { + string("id") } - public var name: FieldPath { - string("name") + var name: FieldPath { + string("name") } - public var activeCart: ModelPath { - Cart4.Path(name: "activeCart", parent: self) + var activeCart: ModelPath { + Cart4.Path(name: "activeCart", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Customer4.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Customer4.swift index 13ee66321a..8ae99d8a47 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Customer4.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Customer4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,29 +12,35 @@ import Foundation public struct Customer4: Model { public let id: String public var name: String? - internal var _activeCart: LazyReference + var _activeCart: LazyReference public var activeCart: Cart4? { - get async throws { + get async throws { try await _activeCart.get() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String? = nil, - activeCart: Cart4? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String? = nil, + activeCart: Cart4? = nil + ) { + self.init( + id: id, name: name, activeCart: activeCart, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - activeCart: Cart4? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + activeCart: Cart4? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self._activeCart = LazyReference(activeCart) @@ -35,15 +48,15 @@ public struct Customer4: Model { self.updatedAt = updatedAt } public mutating func setActiveCart(_ activeCart: Cart4? = nil) { - self._activeCart = LazyReference(activeCart) + _activeCart = LazyReference(activeCart) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - name = try? values.decode(String?.self, forKey: .name) - _activeCart = try values.decodeIfPresent(LazyReference.self, forKey: .activeCart) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.name = try? values.decode(String?.self, forKey: .name) + self._activeCart = try values.decodeIfPresent(LazyReference.self, forKey: .activeCart) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -53,4 +66,4 @@ public struct Customer4: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/GraphQLPostPerson41Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/GraphQLPostPerson41Tests.swift index 603ad7a259..c24ba889ea 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/GraphQLPostPerson41Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/GraphQLPostPerson41Tests.swift @@ -24,7 +24,8 @@ final class GraphQLPostPerson41Tests: AWSAPIPluginGen2GraphQLBaseTest { title: "title", content: "content", author: author, - editor: editor) + editor: editor + ) _ = try await Amplify.API.mutate(request: .create(post)) // Code Snippet Begins @@ -32,7 +33,8 @@ final class GraphQLPostPerson41Tests: AWSAPIPluginGen2GraphQLBaseTest { guard let queriedPost = try await Amplify.API.query( request: .get( Post.self, - byIdentifier: post.identifier)).get() else { + byIdentifier: post.identifier + )).get() else { print("Missing post") // Code Snippet Ends XCTFail("Missing post") diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Person41+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Person41+Schema.swift index 67f028ed2e..e44ce5b2b4 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Person41+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Person41+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Person41 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Person41 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case editedPosts @@ -12,24 +19,24 @@ extension Person41 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let person41 = Person41.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Person41s" model.syncPluralName = "Person41s" - + model.attributes( .primaryKey(fields: [person41.id]) ) - + model.fields( .field(person41.id, is: .required, ofType: .string), .field(person41.name, is: .optional, ofType: .string), @@ -39,32 +46,32 @@ extension Person41 { .field(person41.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Person41: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Person41 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Person41 { + var id: FieldPath { + string("id") } - public var name: FieldPath { - string("name") + var name: FieldPath { + string("name") } - public var editedPosts: ModelPath { - Post41.Path(name: "editedPosts", isCollection: true, parent: self) + var editedPosts: ModelPath { + Post41.Path(name: "editedPosts", isCollection: true, parent: self) } - public var authoredPosts: ModelPath { - Post41.Path(name: "authoredPosts", isCollection: true, parent: self) + var authoredPosts: ModelPath { + Post41.Path(name: "authoredPosts", isCollection: true, parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Person41.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Person41.swift index 4c7858347c..4751a1ef51 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Person41.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Person41.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Person41: Model { public var authoredPosts: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String? = nil, - editedPosts: List? = [], - authoredPosts: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String? = nil, + editedPosts: List? = [], + authoredPosts: List? = [] + ) { + self.init( + id: id, name: name, editedPosts: editedPosts, authoredPosts: authoredPosts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - editedPosts: List? = [], - authoredPosts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + editedPosts: List? = [], + authoredPosts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.editedPosts = editedPosts @@ -34,4 +47,4 @@ public struct Person41: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Post41+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Post41+Schema.swift index 4fb0d7e363..7e648e19b7 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Post41+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Post41+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post41 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post41 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case content @@ -13,24 +20,24 @@ extension Post41 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post41 = Post41.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Post41s" model.syncPluralName = "Post41s" - + model.attributes( .primaryKey(fields: [post41.id]) ) - + model.fields( .field(post41.id, is: .required, ofType: .string), .field(post41.title, is: .required, ofType: .string), @@ -41,35 +48,35 @@ extension Post41 { .field(post41.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post41: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Post41 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Post41 { + var id: FieldPath { + string("id") } - public var title: FieldPath { - string("title") + var title: FieldPath { + string("title") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var author: ModelPath { - Person41.Path(name: "author", parent: self) + var author: ModelPath { + Person41.Path(name: "author", parent: self) } - public var editor: ModelPath { - Person41.Path(name: "editor", parent: self) + var editor: ModelPath { + Person41.Path(name: "editor", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Post41.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Post41.swift index f81d4ebb4c..f7a3bf8004 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Post41.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/Gen2_41/Post41.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -6,41 +13,47 @@ public struct Post41: Model { public let id: String public var title: String public var content: String - internal var _author: LazyReference + var _author: LazyReference public var author: Person41? { - get async throws { + get async throws { try await _author.get() - } + } } - internal var _editor: LazyReference + var _editor: LazyReference public var editor: Person41? { - get async throws { + get async throws { try await _editor.get() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - content: String, - author: Person41? = nil, - editor: Person41? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + content: String, + author: Person41? = nil, + editor: Person41? = nil + ) { + self.init( + id: id, title: title, content: content, author: author, editor: editor, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - content: String, - author: Person41? = nil, - editor: Person41? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + content: String, + author: Person41? = nil, + editor: Person41? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.content = content @@ -50,20 +63,20 @@ public struct Post41: Model { self.updatedAt = updatedAt } public mutating func setAuthor(_ author: Person41? = nil) { - self._author = LazyReference(author) + _author = LazyReference(author) } public mutating func setEditor(_ editor: Person41? = nil) { - self._editor = LazyReference(editor) + _editor = LazyReference(editor) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - title = try values.decode(String.self, forKey: .title) - content = try values.decode(String.self, forKey: .content) - _author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) - _editor = try values.decodeIfPresent(LazyReference.self, forKey: .editor) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.title = try values.decode(String.self, forKey: .title) + self.content = try values.decode(String.self, forKey: .content) + self._author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) + self._editor = try values.decodeIfPresent(LazyReference.self, forKey: .editor) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -75,4 +88,4 @@ public struct Post41: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/GraphQLCartCustomer4Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/GraphQLCartCustomer4Tests.swift index da49e94714..34eb637591 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/GraphQLCartCustomer4Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_4/GraphQLCartCustomer4Tests.swift @@ -24,7 +24,8 @@ final class GraphQLCartCustomer4Tests: AWSAPIPluginGen2GraphQLBaseTest { let cart = Cart( items: ["Tomato", "Ice", "Mint"], - customer: createdCustomer) + customer: createdCustomer + ) let createdCart = try await Amplify.API.mutate(request: .create(cart)).get() // Code Snippet Ends @@ -47,7 +48,8 @@ final class GraphQLCartCustomer4Tests: AWSAPIPluginGen2GraphQLBaseTest { let createdCustomer = try await Amplify.API.mutate(request: .create(customer)).get() let cart = Cart( items: ["Tomato", "Ice", "Mint"], - customer: createdCustomer) + customer: createdCustomer + ) var existingCart = try await Amplify.API.mutate(request: .create(cart)).get() // Code Snippet Begins @@ -77,7 +79,8 @@ final class GraphQLCartCustomer4Tests: AWSAPIPluginGen2GraphQLBaseTest { let createdCustomer = try await Amplify.API.mutate(request: .create(customer)).get() let cart = Cart( items: ["Tomato", "Ice", "Mint"], - customer: createdCustomer) + customer: createdCustomer + ) var existingCart = try await Amplify.API.mutate(request: .create(cart)).get() // Code Snippet Begins @@ -105,7 +108,8 @@ final class GraphQLCartCustomer4Tests: AWSAPIPluginGen2GraphQLBaseTest { let createdCustomer = try await Amplify.API.mutate(request: .create(customer)).get() let cart = Cart( items: ["Tomato", "Ice", "Mint"], - customer: createdCustomer) + customer: createdCustomer + ) var existingCart = try await Amplify.API.mutate(request: .create(cart)).get() // Code Snippet Begins @@ -113,7 +117,8 @@ final class GraphQLCartCustomer4Tests: AWSAPIPluginGen2GraphQLBaseTest { guard let queriedCart = try await Amplify.API.query( request: .get( Cart.self, - byIdentifier: existingCart.identifier)).get() else { + byIdentifier: existingCart.identifier + )).get() else { print("Missing cart") // Code Snippet Ends XCTFail("Missing cart") diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_5/GraphQLTodo5Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_5/GraphQLTodo5Tests.swift index 24213e89e3..ce0c538643 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_5/GraphQLTodo5Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_5/GraphQLTodo5Tests.swift @@ -20,7 +20,8 @@ final class GraphQLTodo5Tests: AWSAPIPluginGen2GraphQLBaseTest { // Code Snippet Begins let todo = Todo( content: "Buy Milk", - completed: false) + completed: false + ) let createdTodo = try await Amplify.API.mutate(request: .create(todo)).get() print("New Todo created: \(createdTodo)") // Code Snippet Ends diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_5/Todo5+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_5/Todo5+Schema.swift index 74023717f2..4165e342b3 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_5/Todo5+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_5/Todo5+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Todo5 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Todo5 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case completed case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let todo5 = Todo5.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Todo5s" model.syncPluralName = "Todo5s" - + model.attributes( .primaryKey(fields: [todo5.id]) ) - + model.fields( .field(todo5.id, is: .required, ofType: .string), .field(todo5.content, is: .optional, ofType: .string), @@ -37,29 +44,29 @@ extension Todo5 { .field(todo5.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Todo5: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Todo5 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Todo5 { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var completed: FieldPath { - bool("completed") + var completed: FieldPath { + bool("completed") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_5/Todo5.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_5/Todo5.swift index d10de7e4e0..17b885ec81 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_5/Todo5.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_5/Todo5.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Todo5: Model { public var completed: Bool? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - completed: Bool? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + completed: Bool? = nil + ) { + self.init( + id: id, content: content, completed: completed, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - completed: Bool? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + completed: Bool? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.completed = completed self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_6/GraphQLTodo6Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_6/GraphQLTodo6Tests.swift index 82b8c32ca1..e69f9f0064 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_6/GraphQLTodo6Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_6/GraphQLTodo6Tests.swift @@ -21,7 +21,8 @@ final class GraphQLTodo6Tests: AWSAPIPluginGen2GraphQLBaseTest { let todo = Todo( todoId: "MyUniqueTodoId", content: "Buy Milk", - completed: false) + completed: false + ) let createdTodo = try await Amplify.API.mutate(request: .create(todo)).get() print("New Todo created: \(createdTodo)") // Code Snippet Ends diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_6/Todo6+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_6/Todo6+Schema.swift index 6e92724406..8a897680ce 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_6/Todo6+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_6/Todo6+Schema.swift @@ -1,35 +1,42 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Todo6 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Todo6 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case todoId case content case completed case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let todo6 = Todo6.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Todo6s" model.syncPluralName = "Todo6s" - + model.attributes( .index(fields: ["todoId"], name: nil), .primaryKey(fields: [todo6.todoId]) ) - + model.fields( .field(todo6.todoId, is: .required, ofType: .string), .field(todo6.content, is: .optional, ofType: .string), @@ -38,9 +45,9 @@ extension Todo6 { .field(todo6.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Todo6: ModelIdentifiable { @@ -48,25 +55,25 @@ extension Todo6: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Todo6.IdentifierProtocol { - public static func identifier(todoId: String) -> Self { - .make(fields:[(name: "todoId", value: todoId)]) +public extension Todo6.IdentifierProtocol { + static func identifier(todoId: String) -> Self { + .make(fields: [(name: "todoId", value: todoId)]) } } -extension ModelPath where ModelType == Todo6 { - public var todoId: FieldPath { - string("todoId") +public extension ModelPath where ModelType == Todo6 { + var todoId: FieldPath { + string("todoId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var completed: FieldPath { - bool("completed") + var completed: FieldPath { + bool("completed") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_6/Todo6.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_6/Todo6.swift index 04c2eea180..4a8bdf0f02 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_6/Todo6.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_6/Todo6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Todo6: Model { public var completed: Bool? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(todoId: String, - content: String? = nil, - completed: Bool? = nil) { - self.init(todoId: todoId, + + public init( + todoId: String, + content: String? = nil, + completed: Bool? = nil + ) { + self.init( + todoId: todoId, content: content, completed: completed, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(todoId: String, - content: String? = nil, - completed: Bool? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + todoId: String, + content: String? = nil, + completed: Bool? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.todoId = todoId self.content = content self.completed = completed self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_7/GraphQLStoreBranch7Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_7/GraphQLStoreBranch7Tests.swift index 7b5456085e..9836ca8547 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_7/GraphQLStoreBranch7Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_7/GraphQLStoreBranch7Tests.swift @@ -5,13 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLStoreBranch7Tests: AWSAPIPluginGen2GraphQLBaseTest { @@ -25,7 +24,9 @@ final class GraphQLStoreBranch7Tests: AWSAPIPluginGen2GraphQLBaseTest { StoreBranch.self, byIdentifier: .identifier( tenantId: "123", - name: "Downtown"))) + name: "Downtown" + ) + )) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_7/StoreBranch7+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_7/StoreBranch7+Schema.swift index 9ef1b980a9..35d6e087b1 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_7/StoreBranch7+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_7/StoreBranch7+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension StoreBranch7 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension StoreBranch7 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case tenantId case name case country @@ -15,25 +22,25 @@ extension StoreBranch7 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let storeBranch7 = StoreBranch7.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "StoreBranch7s" model.syncPluralName = "StoreBranch7s" - + model.attributes( .index(fields: ["tenantId", "name"], name: nil), .primaryKey(fields: [storeBranch7.tenantId, storeBranch7.name]) ) - + model.fields( .field(storeBranch7.tenantId, is: .required, ofType: .string), .field(storeBranch7.name, is: .required, ofType: .string), @@ -46,9 +53,9 @@ extension StoreBranch7 { .field(storeBranch7.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension StoreBranch7: ModelIdentifiable { @@ -56,38 +63,40 @@ extension StoreBranch7: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension StoreBranch7.IdentifierProtocol { - public static func identifier(tenantId: String, - name: String) -> Self { - .make(fields:[(name: "tenantId", value: tenantId), (name: "name", value: name)]) +public extension StoreBranch7.IdentifierProtocol { + static func identifier( + tenantId: String, + name: String + ) -> Self { + .make(fields: [(name: "tenantId", value: tenantId), (name: "name", value: name)]) } } -extension ModelPath where ModelType == StoreBranch7 { - public var tenantId: FieldPath { - string("tenantId") +public extension ModelPath where ModelType == StoreBranch7 { + var tenantId: FieldPath { + string("tenantId") } - public var name: FieldPath { - string("name") + var name: FieldPath { + string("name") } - public var country: FieldPath { - string("country") + var country: FieldPath { + string("country") } - public var state: FieldPath { - string("state") + var state: FieldPath { + string("state") } - public var city: FieldPath { - string("city") + var city: FieldPath { + string("city") } - public var zipCode: FieldPath { - string("zipCode") + var zipCode: FieldPath { + string("zipCode") } - public var streetAddress: FieldPath { - string("streetAddress") + var streetAddress: FieldPath { + string("streetAddress") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_7/StoreBranch7.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_7/StoreBranch7.swift index 5dd00d59a1..8a82d452f9 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_7/StoreBranch7.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_7/StoreBranch7.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct StoreBranch7: Model { public var streetAddress: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(tenantId: String, - name: String, - country: String? = nil, - state: String? = nil, - city: String? = nil, - zipCode: String? = nil, - streetAddress: String? = nil) { - self.init(tenantId: tenantId, + + public init( + tenantId: String, + name: String, + country: String? = nil, + state: String? = nil, + city: String? = nil, + zipCode: String? = nil, + streetAddress: String? = nil + ) { + self.init( + tenantId: tenantId, name: name, country: country, state: state, @@ -28,17 +38,20 @@ public struct StoreBranch7: Model { zipCode: zipCode, streetAddress: streetAddress, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(tenantId: String, - name: String, - country: String? = nil, - state: String? = nil, - city: String? = nil, - zipCode: String? = nil, - streetAddress: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + tenantId: String, + name: String, + country: String? = nil, + state: String? = nil, + city: String? = nil, + zipCode: String? = nil, + streetAddress: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.tenantId = tenantId self.name = name self.country = country @@ -49,4 +62,4 @@ public struct StoreBranch7: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_8/Customer8+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_8/Customer8+Schema.swift index be4fe91412..5442031204 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_8/Customer8+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_8/Customer8+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Customer8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Customer8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case phoneNumber @@ -12,25 +19,25 @@ extension Customer8 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let customer8 = Customer8.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Customer8s" model.syncPluralName = "Customer8s" - + model.attributes( .index(fields: ["accountRepresentativeId"], name: "customer8sByAccountRepresentativeId"), .primaryKey(fields: [customer8.id]) ) - + model.fields( .field(customer8.id, is: .required, ofType: .string), .field(customer8.name, is: .optional, ofType: .string), @@ -40,32 +47,32 @@ extension Customer8 { .field(customer8.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Customer8: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Customer8 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Customer8 { + var id: FieldPath { + string("id") } - public var name: FieldPath { - string("name") + var name: FieldPath { + string("name") } - public var phoneNumber: FieldPath { - string("phoneNumber") + var phoneNumber: FieldPath { + string("phoneNumber") } - public var accountRepresentativeId: FieldPath { - string("accountRepresentativeId") + var accountRepresentativeId: FieldPath { + string("accountRepresentativeId") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_8/Customer8.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_8/Customer8.swift index a944b2c99b..39c2db63f7 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_8/Customer8.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_8/Customer8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Customer8: Model { public var accountRepresentativeId: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String? = nil, - phoneNumber: String? = nil, - accountRepresentativeId: String) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String? = nil, + phoneNumber: String? = nil, + accountRepresentativeId: String + ) { + self.init( + id: id, name: name, phoneNumber: phoneNumber, accountRepresentativeId: accountRepresentativeId, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - phoneNumber: String? = nil, - accountRepresentativeId: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + phoneNumber: String? = nil, + accountRepresentativeId: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.phoneNumber = phoneNumber @@ -34,4 +47,4 @@ public struct Customer8: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_8/GraphQLCustomer8Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_8/GraphQLCustomer8Tests.swift index affb93019f..b155318d1d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_8/GraphQLCustomer8Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_8/GraphQLCustomer8Tests.swift @@ -45,13 +45,14 @@ final class GraphQLCustomer8Tests: AWSAPIPluginGen2GraphQLBaseTest { let request = GraphQLRequest>( document: document, responseType: PaginatedList.self, - decodePath: operationName) + decodePath: operationName + ) let queriedCustomers = try await Amplify.API.query( request: request).get() // Code Snippet Ends - XCTAssertTrue(queriedCustomers.items.count != 0 || queriedCustomers.nextToken != nil) + XCTAssertTrue(!queriedCustomers.items.isEmpty || queriedCustomers.nextToken != nil) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_9/Customer9+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_9/Customer9+Schema.swift index 57489c5117..fd72f78934 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_9/Customer9+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_9/Customer9+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Customer9 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Customer9 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case phoneNumber @@ -12,25 +19,25 @@ extension Customer9 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let customer9 = Customer9.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Customer9s" model.syncPluralName = "Customer9s" - + model.attributes( .index(fields: ["accountRepresentativeId", "name"], name: "customer9sByAccountRepresentativeIdAndName"), .primaryKey(fields: [customer9.id]) ) - + model.fields( .field(customer9.id, is: .required, ofType: .string), .field(customer9.name, is: .optional, ofType: .string), @@ -40,32 +47,32 @@ extension Customer9 { .field(customer9.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Customer9: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Customer9 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Customer9 { + var id: FieldPath { + string("id") } - public var name: FieldPath { - string("name") + var name: FieldPath { + string("name") } - public var phoneNumber: FieldPath { - string("phoneNumber") + var phoneNumber: FieldPath { + string("phoneNumber") } - public var accountRepresentativeId: FieldPath { - string("accountRepresentativeId") + var accountRepresentativeId: FieldPath { + string("accountRepresentativeId") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_9/Customer9.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_9/Customer9.swift index 8154a90db0..099c39ed44 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_9/Customer9.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_9/Customer9.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Customer9: Model { public var accountRepresentativeId: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String? = nil, - phoneNumber: String? = nil, - accountRepresentativeId: String) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String? = nil, + phoneNumber: String? = nil, + accountRepresentativeId: String + ) { + self.init( + id: id, name: name, phoneNumber: phoneNumber, accountRepresentativeId: accountRepresentativeId, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - phoneNumber: String? = nil, - accountRepresentativeId: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + phoneNumber: String? = nil, + accountRepresentativeId: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.phoneNumber = phoneNumber @@ -34,4 +47,4 @@ public struct Customer9: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_9/GraphQLCustomer9Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_9/GraphQLCustomer9Tests.swift index ee4420f122..d5f5d89e48 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_9/GraphQLCustomer9Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/Gen2_9/GraphQLCustomer9Tests.swift @@ -45,13 +45,14 @@ final class GraphQLCustomer9Tests: AWSAPIPluginGen2GraphQLBaseTest { var request = GraphQLRequest>( document: document, responseType: PaginatedList.self, - decodePath: operationName) + decodePath: operationName + ) let queriedCustomers = try await Amplify.API.query( request: request).get() // Code Snippet Ends - XCTAssertTrue(queriedCustomers.items.count != 0 || queriedCustomers.nextToken != nil) + XCTAssertTrue(!queriedCustomers.items.isEmpty || queriedCustomers.nextToken != nil) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Comment4V2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Comment4V2+Schema.swift index e02097061d..82f2280138 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Comment4V2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Comment4V2+Schema.swift @@ -1,35 +1,42 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment4V2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment4V2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment4V2 = Comment4V2.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Comment4V2s" model.syncPluralName = "Comment4V2s" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [comment4V2.id]) ) - + model.fields( .field(comment4V2.id, is: .required, ofType: .string), .field(comment4V2.content, is: .required, ofType: .string), @@ -38,29 +45,29 @@ extension Comment4V2 { .field(comment4V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment4V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Comment4V2 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Comment4V2 { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var post: ModelPath { - Post4V2.Path(name: "post", parent: self) + var post: ModelPath { + Post4V2.Path(name: "post", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Comment4V2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Comment4V2.swift index 1c6a50f04f..5b71a919c9 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Comment4V2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Comment4V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,29 +12,35 @@ import Foundation public struct Comment4V2: Model { public let id: String public var content: String - internal var _post: LazyReference + var _post: LazyReference public var post: Post4V2? { - get async throws { + get async throws { try await _post.get() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct Comment4V2: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post4V2? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try values.decode(String.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try values.decode(String.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -53,4 +66,4 @@ public struct Comment4V2: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/GraphQLLazyLoadPostComment4V2Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/GraphQLLazyLoadPostComment4V2Tests.swift index 6f7750cdb3..9537323d2c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/GraphQLLazyLoadPostComment4V2Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/GraphQLLazyLoadPostComment4V2Tests.swift @@ -5,13 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest { @@ -22,7 +21,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest try await mutate(.create(post)) try await mutate(.create(comment)) } - + // Without `includes` and latest codegenerated types with the model path, the post should be lazy loaded func testCommentWithLazyLoadPost() async throws { await setup(withModels: PostComment4V2Models()) @@ -30,13 +29,13 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest let comment = Comment(content: "content", post: post) let createdPost = try await mutate(.create(post)) let createdComment = try await mutate(.create(comment)) - + // The comment's post should not be loaded, since no `includes` is passed in. // And the codegenerated swift models have the new modelPath properties. assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: createdPost.id)])) let loadedPost = try await createdComment.post! XCTAssertEqual(loadedPost.id, createdPost.id) - + // The loaded post should have comments that are also not loaded let comments = loadedPost.comments! assertList(comments, state: .isNotLoaded(associatedIdentifiers: [createdPost.id], associatedFields: ["post"])) @@ -46,7 +45,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest // the loaded comment's post should not be loaded assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: createdPost.id)])) } - + // With `includes` on `comment.post`, the comment's post should be eager loaded. func testCommentWithEagerLoadPost() async throws { await setup(withModels: PostComment4V2Models()) @@ -67,7 +66,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest // further nested models should not be loaded assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) } - + // With `includes` on `comment.post.comments`, func testCommentWithEagerLoadPostAndPostComments() async throws { await setup(withModels: PostComment4V2Models()) @@ -116,7 +115,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest // further nested models should not be loaded assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) } - + /* - Given: Api plugin is cleared @@ -170,7 +169,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest XCTAssertEqual(request.document, expectedDocument) try await mutate(request) } - + // Without `includes` and latest codegenerated types with the model path, the post's comments should be lazy loaded func testPostWithLazyLoadComments() async throws { await setup(withModels: PostComment4V2Models()) @@ -185,7 +184,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest assertList(comments, state: .isLoaded(count: 1)) assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) } - + // With `includes` on `post.comments` should eager load the post's comments func testPostWithEagerLoadComments() async throws { await setup(withModels: PostComment4V2Models()) @@ -198,7 +197,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest assertList(comments, state: .isLoaded(count: 1)) assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) } - + // With `includes` on `post.comments.post` should eager load the post's comments' post func testPostWithEagerLoadCommentsAndPost() async throws { await setup(withModels: PostComment4V2Models()) @@ -211,25 +210,29 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest assertList(comments, state: .isLoaded(count: 1)) assertLazyReference(comments.first!._post, state: .loaded(model: createdPost)) } - + func testListPostsListComments() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") let comment = Comment(content: "content", post: post) try await mutate(.create(post)) try await mutate(.create(comment)) - + let queriedPosts = try await listQuery(.list(Post.self, where: Post.keys.id == post.id)) assertList(queriedPosts, state: .isLoaded(count: 1)) - assertList(queriedPosts.first!.comments!, - state: .isNotLoaded(associatedIdentifiers: [post.id], associatedFields: ["post"])) - + assertList( + queriedPosts.first!.comments!, + state: .isNotLoaded(associatedIdentifiers: [post.id], associatedFields: ["post"]) + ) + let queriedComments = try await listQuery(.list(Comment.self, where: Comment.keys.id == comment.id)) assertList(queriedComments, state: .isLoaded(count: 1)) - assertLazyReference(queriedComments.first!._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) + assertLazyReference( + queriedComments.first!._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.id)]) + ) } - + func testCreateWithoutPost() async throws { await setup(withModels: PostComment4V2Models()) let comment = Comment(content: "content") @@ -245,7 +248,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest let queriedCommentWithPost = try await query(.get(Comment.self, byId: queriedCommentAfterUpdate.id, includes: { comment in [comment.post]}))! assertLazyReference(queriedCommentWithPost._post, state: .loaded(model: createdPost)) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") @@ -254,7 +257,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest try await mutate(.create(comment)) var queriedComment = try await query(.get(Comment.self, byId: comment.id))! assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) - + let newPost = Post(title: "title") let createdNewPost = try await mutate(.create(newPost)) queriedComment.setPost(newPost) @@ -264,7 +267,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest let queriedCommentWithPost = try await query(.get(Comment.self, byId: queriedCommentAfterUpdate.id, includes: { comment in [comment.post]}))! assertLazyReference(queriedCommentWithPost._post, state: .loaded(model: createdNewPost)) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") @@ -273,20 +276,20 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest try await mutate(.create(comment)) var queriedComment = try await query(.get(Comment.self, byId: comment.id))! assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) - + queriedComment.setPost(nil) let updateCommentRemovePost = try await mutate(.update(queriedComment)) let queriedCommentAfterUpdate = try await query(.get(Comment.self, byId: updateCommentRemovePost.id))! assertLazyReference(queriedCommentAfterUpdate._post, state: .notLoaded(identifiers: nil)) } - + func testDelete() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") let comment = Comment(content: "content", post: post) let createdPost = try await mutate(.create(post)) try await mutate(.create(comment)) - + try await mutate(.delete(createdPost)) let queriedPost = try await query(.get(Post.self, byId: post.id)) XCTAssertNil(queriedPost) @@ -296,7 +299,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest let queryDeletedComment = try await query(.get(Comment.self, byId: comment.id)) XCTAssertNil(queryDeletedComment) } - + func testSubscribeToComments() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") @@ -328,14 +331,14 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) let comment = Comment(content: "content", post: post) try await mutate(.create(comment)) await fulfillment(of: [onCreatedComment], timeout: 10) subscription.cancel() } - + // The identical `includes` parameter should be used because the selection set of the mutation // has to match the selection set of the subscription. func testSubscribeToCommentsIncludesPost() async throws { @@ -344,9 +347,11 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest try await mutate(.create(post)) let connected = expectation(description: "subscription connected") let onCreatedComment = expectation(description: "onCreatedComment received") - let subscriptionIncludes = Amplify.API.subscribe(request: .subscription(of: Comment.self, - type: .onCreate, - includes: { comment in [comment.post]})) + let subscriptionIncludes = Amplify.API.subscribe(request: .subscription( + of: Comment.self, + type: .onCreate, + includes: { comment in [comment.post]} + )) Task { do { for try await subscriptionEvent in subscriptionIncludes { @@ -371,18 +376,18 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 20) let comment = Comment(content: "content", post: post) try await mutate(.create(comment, includes: { comment in [comment.post] })) await fulfillment(of: [onCreatedComment], timeout: 20) subscriptionIncludes.cancel() } - + func testSubscribeToPosts() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") - + let connected = expectation(description: "subscription connected") let onCreatedPost = expectation(description: "onCreatedPost received") let subscription = Amplify.API.subscribe(request: .subscription(of: Post.self, type: .onCreate)) @@ -410,22 +415,24 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) try await mutate(.create(post)) await fulfillment(of: [onCreatedPost], timeout: 10) subscription.cancel() } - + func testSubscribeToPostsIncludes() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") - + let connected = expectation(description: "subscription connected") let onCreatedPost = expectation(description: "onCreatedPost received") - let subscriptionIncludes = Amplify.API.subscribe(request: .subscription(of: Post.self, - type: .onCreate, - includes: { post in [post.comments]})) + let subscriptionIncludes = Amplify.API.subscribe(request: .subscription( + of: Post.self, + type: .onCreate, + includes: { post in [post.comments]} + )) Task { do { for try await subscriptionEvent in subscriptionIncludes { @@ -450,7 +457,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: AWSAPIPluginGen2GraphQLBaseTest XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) try await mutate(.create(post, includes: { post in [post.comments]})) await fulfillment(of: [onCreatedPost], timeout: 10) @@ -463,7 +470,7 @@ extension GraphQLLazyLoadPostComment4V2Tests: DefaultLogger { } extension GraphQLLazyLoadPostComment4V2Tests { typealias Post = Post4V2 typealias Comment = Comment4V2 - + struct PostComment4V2Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Post4V2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Post4V2+Schema.swift index 0bbc928091..583f281cad 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Post4V2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Post4V2+Schema.swift @@ -1,35 +1,42 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post4V2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post4V2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post4V2 = Post4V2.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "Post4V2s" model.syncPluralName = "Post4V2s" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [post4V2.id]) ) - + model.fields( .field(post4V2.id, is: .required, ofType: .string), .field(post4V2.title, is: .required, ofType: .string), @@ -38,29 +45,29 @@ extension Post4V2 { .field(post4V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post4V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Post4V2 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Post4V2 { + var id: FieldPath { + string("id") } - public var title: FieldPath { - string("title") + var title: FieldPath { + string("title") } - public var comments: ModelPath { - Comment4V2.Path(name: "comments", isCollection: true, parent: self) + var comments: ModelPath { + Comment4V2.Path(name: "comments", isCollection: true, parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Post4V2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Post4V2.swift index 08f3e4b429..9106744759 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Post4V2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL1/Post4V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post4V2: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/CommentWithCompositeKey+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/CommentWithCompositeKey+Schema.swift index 8e4fbcf9d2..5761fe6ca3 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/CommentWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/CommentWithCompositeKey+Schema.swift @@ -1,35 +1,42 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CommentWithCompositeKey { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension CommentWithCompositeKey { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let commentWithCompositeKey = CommentWithCompositeKey.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "CommentWithCompositeKeys" model.syncPluralName = "CommentWithCompositeKeys" - + model.attributes( .index(fields: ["id", "content"], name: nil), .primaryKey(fields: [commentWithCompositeKey.id, commentWithCompositeKey.content]) ) - + model.fields( .field(commentWithCompositeKey.id, is: .required, ofType: .string), .field(commentWithCompositeKey.content, is: .required, ofType: .string), @@ -38,9 +45,9 @@ extension CommentWithCompositeKey { .field(commentWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension CommentWithCompositeKey: ModelIdentifiable { @@ -48,26 +55,28 @@ extension CommentWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CommentWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - content: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "content", value: content)]) +public extension CommentWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + content: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "content", value: content)]) } } -extension ModelPath where ModelType == CommentWithCompositeKey { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == CommentWithCompositeKey { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var post: ModelPath { - PostWithCompositeKey.Path(name: "post", parent: self) + var post: ModelPath { + PostWithCompositeKey.Path(name: "post", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/CommentWithCompositeKey.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/CommentWithCompositeKey.swift index 2ac30be7be..1a34e3ef6c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/CommentWithCompositeKey.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/CommentWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,29 +12,35 @@ import Foundation public struct CommentWithCompositeKey: Model { public let id: String public let content: String - internal var _post: LazyReference + var _post: LazyReference public var post: PostWithCompositeKey? { - get async throws { + get async throws { try await _post.get() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKey? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKey? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKey? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKey? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct CommentWithCompositeKey: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: PostWithCompositeKey? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try values.decode(String.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try values.decode(String.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -53,4 +66,4 @@ public struct CommentWithCompositeKey: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/GraphQLLazyLoadPostCommentWithCompositeKeyTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/GraphQLLazyLoadPostCommentWithCompositeKeyTests.swift index f6af16533f..630cbb67c5 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/GraphQLLazyLoadPostCommentWithCompositeKeyTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/GraphQLLazyLoadPostCommentWithCompositeKeyTests.swift @@ -5,49 +5,55 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2GraphQLBaseTest { func testSave() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) - + let post = Post(title: "title") let comment = Comment(content: "content", post: post) let savedPost = try await mutate(.create(post)) let savedComment = try await mutate(.create(comment)) } - + func testCommentWithLazyLoadPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) - + let post = Post(title: "title") let comment = Comment(content: "content", post: post) let createdPost = try await mutate(.create(post)) let createdComment = try await mutate(.create(comment)) - + // The comment's post should not be loaded, since no `includes` is passed in. // And the codegenerated swift models have the new modelPath properties. - assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: createdPost.id), - .init(name: "title", value: createdPost.title)])) + assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: createdPost.id), + .init(name: "title", value: createdPost.title) + ])) let loadedPost = try await createdComment.post! XCTAssertEqual(loadedPost.id, createdPost.id) - + // The loaded post should have comments that are also not loaded let comments = loadedPost.comments! - assertList(comments, state: .isNotLoaded(associatedIdentifiers: [post.id, post.title], - associatedFields: ["post"])) + assertList(comments, state: .isNotLoaded( + associatedIdentifiers: [post.id, post.title], + associatedFields: ["post"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) - assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: createdPost.id), - .init(name: "title", value: createdPost.title)])) + assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: createdPost.id), + .init(name: "title", value: createdPost.title) + ])) } - + // With `includes` on `comment.post`, the comment's post should be eager loaded. func testCommentWithEagerLoadPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) @@ -61,16 +67,20 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra XCTAssertEqual(loadedPost.id, post.id) // The loaded post should have comments that are not loaded let comments = loadedPost.comments! - assertList(comments, state: .isNotLoaded(associatedIdentifiers: [post.id, post.title], - associatedFields: ["post"])) + assertList(comments, state: .isNotLoaded( + associatedIdentifiers: [post.id, post.title], + associatedFields: ["post"] + )) // load the comments try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) // further nested models should not be loaded - assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: createdPost.id), - .init(name: "title", value: createdPost.title)])) + assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: createdPost.id), + .init(name: "title", value: createdPost.title) + ])) } - + // With `includes` on `comment.post.comments`, func testCommentWithEagerLoadPostAndPostComments() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) @@ -118,10 +128,12 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra let comments = loadedPost.comments! assertList(comments, state: .isLoaded(count: 1)) // further nested models should not be loaded - assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) + assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) } - + // Without `includes` and latest codegenerated types with the model path, the post's comments should be lazy loaded func testPostWithLazyLoadComments() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) @@ -134,10 +146,12 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra assertList(comments, state: .isNotLoaded(associatedIdentifiers: [post.id, post.title], associatedFields: ["post"])) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) - assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) + assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) } - + // With `includes` on `post.comments` should eager load the post's comments func testPostWithEagerLoadComments() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) @@ -148,10 +162,12 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra let queriedPost = try await query(.get(Post.self, byIdentifier: .identifier(id: post.id, title: post.title), includes: { post in [post.comments]}))! let comments = queriedPost.comments! assertList(comments, state: .isLoaded(count: 1)) - assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) + assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) } - + // With `includes` on `post.comments.post` should eager load the post's comments' post func testPostWithEagerLoadCommentsAndPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) @@ -159,35 +175,44 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra let comment = Comment(content: "content", post: post) let createdPost = try await mutate(.create(post)) _ = try await mutate(.create(comment)) - let queriedPost = try await query(.get(Post.self, - byIdentifier: .identifier(id: post.id, - title: post.title), - includes: { post in [post.comments.post]}))! + let queriedPost = try await query(.get( + Post.self, + byIdentifier: .identifier( + id: post.id, + title: post.title + ), + includes: { post in [post.comments.post]} + ))! let comments = queriedPost.comments! assertList(comments, state: .isLoaded(count: 1)) assertLazyReference(comments.first!._post, state: .loaded(model: createdPost)) } - + func testListPostsListComments() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") let comment = Comment(content: "content", post: post) try await mutate(.create(post)) try await mutate(.create(comment)) - + let queriedPosts = try await listQuery(.list(Post.self, where: Post.keys.id == post.id)) assertList(queriedPosts, state: .isLoaded(count: 1)) - assertList(queriedPosts.first!.comments!, - state: .isNotLoaded(associatedIdentifiers: [post.id, post.title], associatedFields: ["post"])) - + assertList( + queriedPosts.first!.comments!, + state: .isNotLoaded(associatedIdentifiers: [post.id, post.title], associatedFields: ["post"]) + ) + let queriedComments = try await listQuery(.list(Comment.self, where: Comment.keys.id == comment.id)) assertList(queriedComments, state: .isLoaded(count: 1)) - assertLazyReference(queriedComments.first!._post, - state: .notLoaded(identifiers: [ - .init(name: "id", value: post.id), - .init(name: "title", value: "title")])) + assertLazyReference( + queriedComments.first!._post, + state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: "title") + ]) + ) } - + func testCreateWithoutPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let comment = Comment(content: "content") @@ -198,18 +223,28 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra let createdPost = try await mutate(.create(post)) queriedComment.setPost(createdPost) let updateCommentWithPost = try await mutate(.update(queriedComment)) - let queriedCommentAfterUpdate = try await query(.get(Comment.self, - byIdentifier: .identifier(id: updateCommentWithPost.id, - content: updateCommentWithPost.content)))! - assertLazyReference(queriedCommentAfterUpdate._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) - let queriedCommentWithPost = try await query(.get(Comment.self, - byIdentifier: .identifier(id: queriedCommentAfterUpdate.id, - content: queriedCommentAfterUpdate.content), - includes: { comment in [comment.post]}))! + let queriedCommentAfterUpdate = try await query(.get( + Comment.self, + byIdentifier: .identifier( + id: updateCommentWithPost.id, + content: updateCommentWithPost.content + ) + ))! + assertLazyReference(queriedCommentAfterUpdate._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) + let queriedCommentWithPost = try await query(.get( + Comment.self, + byIdentifier: .identifier( + id: queriedCommentAfterUpdate.id, + content: queriedCommentAfterUpdate.content + ), + includes: { comment in [comment.post]} + ))! assertLazyReference(queriedCommentWithPost._post, state: .loaded(model: createdPost)) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") @@ -217,25 +252,37 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra try await mutate(.create(post)) try await mutate(.create(comment)) var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(id: comment.id, content: comment.content)))! - assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) - + assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) + let newPost = Post(title: "title") let createdNewPost = try await mutate(.create(newPost)) queriedComment.setPost(newPost) let updateCommentWithPost = try await mutate(.update(queriedComment)) - let queriedCommentAfterUpdate = try await query(.get(Comment.self, - byIdentifier: .identifier(id: updateCommentWithPost.id, - content: updateCommentWithPost.content)))! - assertLazyReference(queriedCommentAfterUpdate._post, state: .notLoaded(identifiers: [.init(name: "id", value: newPost.id), - .init(name: "title", value: newPost.title)])) - let queriedCommentWithPost = try await query(.get(Comment.self, - byIdentifier: .identifier(id: queriedCommentAfterUpdate.id, - content: queriedCommentAfterUpdate.content), - includes: { comment in [comment.post]}))! + let queriedCommentAfterUpdate = try await query(.get( + Comment.self, + byIdentifier: .identifier( + id: updateCommentWithPost.id, + content: updateCommentWithPost.content + ) + ))! + assertLazyReference(queriedCommentAfterUpdate._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: newPost.id), + .init(name: "title", value: newPost.title) + ])) + let queriedCommentWithPost = try await query(.get( + Comment.self, + byIdentifier: .identifier( + id: queriedCommentAfterUpdate.id, + content: queriedCommentAfterUpdate.content + ), + includes: { comment in [comment.post]} + ))! assertLazyReference(queriedCommentWithPost._post, state: .loaded(model: createdNewPost)) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") @@ -243,22 +290,24 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra try await mutate(.create(post)) try await mutate(.create(comment)) var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(id: comment.id, content: comment.content)))! - assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) - + assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) + queriedComment.setPost(nil) let updateCommentRemovePost = try await mutate(.update(queriedComment)) let queriedCommentAfterUpdate = try await query(.get(Comment.self, byIdentifier: .identifier(id: updateCommentRemovePost.id, content: updateCommentRemovePost.content)))! assertLazyReference(queriedCommentAfterUpdate._post, state: .notLoaded(identifiers: nil)) } - + func testDelete() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") let comment = Comment(content: "content", post: post) let createdPost = try await mutate(.create(post)) try await mutate(.create(comment)) - + try await mutate(.delete(createdPost)) let queriedPost = try await query(.get(Post.self, byIdentifier: .identifier(id: post.id, title: post.title))) XCTAssertNil(queriedPost) @@ -268,7 +317,7 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra let queryDeletedComment = try await query(.get(Comment.self, byIdentifier: .identifier(id: comment.id, content: comment.content))) XCTAssertNil(queryDeletedComment) } - + func testSubscribeToComments() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") @@ -289,8 +338,10 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra switch result { case .success(let createdComment): log.verbose("Successfully got createdComment from subscription: \(createdComment)") - assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) + assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) onCreatedComment.fulfill() case .failure(let error): XCTFail("Got failed result with \(error.errorDescription)") @@ -301,14 +352,14 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) let comment = Comment(content: "content", post: post) try await mutate(.create(comment)) await fulfillment(of: [onCreatedComment], timeout: 10) subscription.cancel() } - + // The identical `includes` parameter should be used because the selection set of the mutation // has to match the selection set of the subscription. func testSubscribeToCommentsIncludesPost() async throws { @@ -317,9 +368,11 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra try await mutate(.create(post)) let connected = expectation(description: "subscription connected") let onCreatedComment = expectation(description: "onCreatedComment received") - let subscriptionIncludes = Amplify.API.subscribe(request: .subscription(of: Comment.self, - type: .onCreate, - includes: { comment in [comment.post]})) + let subscriptionIncludes = Amplify.API.subscribe(request: .subscription( + of: Comment.self, + type: .onCreate, + includes: { comment in [comment.post]} + )) Task { do { for try await subscriptionEvent in subscriptionIncludes { @@ -344,18 +397,18 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 20) let comment = Comment(content: "content", post: post) try await mutate(.create(comment, includes: { comment in [comment.post] })) await fulfillment(of: [onCreatedComment], timeout: 20) subscriptionIncludes.cancel() } - + func testSubscribeToPosts() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") - + let connected = expectation(description: "subscription connected") let onCreatedPost = expectation(description: "onCreatedPost received") let subscription = Amplify.API.subscribe(request: .subscription(of: Post.self, type: .onCreate)) @@ -383,22 +436,24 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) try await mutate(.create(post)) await fulfillment(of: [onCreatedPost], timeout: 10) subscription.cancel() } - + func testSubscribeToPostsIncludes() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") - + let connected = expectation(description: "subscription connected") let onCreatedPost = expectation(description: "onCreatedPost received") - let subscriptionIncludes = Amplify.API.subscribe(request: .subscription(of: Post.self, - type: .onCreate, - includes: { post in [post.comments]})) + let subscriptionIncludes = Amplify.API.subscribe(request: .subscription( + of: Post.self, + type: .onCreate, + includes: { post in [post.comments]} + )) Task { do { for try await subscriptionEvent in subscriptionIncludes { @@ -423,7 +478,7 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: AWSAPIPluginGen2Gra XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) try await mutate(.create(post, includes: { post in [post.comments]})) await fulfillment(of: [onCreatedPost], timeout: 10) @@ -436,7 +491,7 @@ extension GraphQLLazyLoadPostCommentWithCompositeKeyTests: DefaultLogger { } extension GraphQLLazyLoadPostCommentWithCompositeKeyTests { typealias Post = PostWithCompositeKey typealias Comment = CommentWithCompositeKey - + struct PostCommentWithCompositeKeyModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/PostWithCompositeKey+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/PostWithCompositeKey+Schema.swift index a11b35aa0d..2db0fb4c2d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/PostWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/PostWithCompositeKey+Schema.swift @@ -1,35 +1,42 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithCompositeKey { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension PostWithCompositeKey { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let postWithCompositeKey = PostWithCompositeKey.keys - + model.authRules = [ rule(allow: .public, provider: .apiKey, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "PostWithCompositeKeys" model.syncPluralName = "PostWithCompositeKeys" - + model.attributes( .index(fields: ["id", "title"], name: nil), .primaryKey(fields: [postWithCompositeKey.id, postWithCompositeKey.title]) ) - + model.fields( .field(postWithCompositeKey.id, is: .required, ofType: .string), .field(postWithCompositeKey.title, is: .required, ofType: .string), @@ -38,9 +45,9 @@ extension PostWithCompositeKey { .field(postWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PostWithCompositeKey: ModelIdentifiable { @@ -48,26 +55,28 @@ extension PostWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - title: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "title", value: title)]) +public extension PostWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + title: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "title", value: title)]) } } -extension ModelPath where ModelType == PostWithCompositeKey { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == PostWithCompositeKey { + var id: FieldPath { + string("id") } - public var title: FieldPath { - string("title") + var title: FieldPath { + string("title") } - public var comments: ModelPath { - CommentWithCompositeKey.Path(name: "comments", isCollection: true, parent: self) + var comments: ModelPath { + CommentWithCompositeKey.Path(name: "comments", isCollection: true, parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/PostWithCompositeKey.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/PostWithCompositeKey.swift index e9de7de986..ac441cae5d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/PostWithCompositeKey.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGen2GraphQLTests/LL3/PostWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithCompositeKey: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/API.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/API.swift index 0c77d28084..ae4c776f91 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/API.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/API.swift @@ -1,26 +1,34 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // This file was automatically generated and should not be edited. #if canImport(AWSAPIPlugin) import Foundation + public protocol GraphQLInputValue { } public struct GraphQLVariable { let name: String - + public init(_ name: String) { self.name = name } } extension GraphQLVariable: GraphQLInputValue { } -extension JSONEncodable { - public func evaluate(with variables: [String: JSONEncodable]?) throws -> Any { +public extension JSONEncodable { + func evaluate(with variables: [String: JSONEncodable]?) throws -> Any { return jsonValue } } public typealias GraphQLMap = [String: JSONEncodable?] -extension Dictionary where Key == String, Value == JSONEncodable? { - public var withNilValuesRemoved: Dictionary { - var filtered = Dictionary(minimumCapacity: count) +public extension [String: JSONEncodable?] { + var withNilValuesRemoved: [String: JSONEncodable] { + var filtered = [String: JSONEncodable](minimumCapacity: count) for (key, value) in self { if value != nil { filtered[key] = value @@ -39,13 +47,13 @@ public extension GraphQLMapConvertible { } public typealias GraphQLID = String public protocol APISwiftGraphQLOperation: AnyObject { - + static var operationString: String { get } static var requestString: String { get } static var operationIdentifier: String? { get } - + var variables: GraphQLMap? { get } - + associatedtype Data: GraphQLSelectionSet } public extension APISwiftGraphQLOperation { @@ -68,12 +76,12 @@ public protocol GraphQLFragment: GraphQLSelectionSet { public typealias Snapshot = [String: Any?] public protocol GraphQLSelectionSet: Decodable { static var selections: [GraphQLSelection] { get } - + var snapshot: Snapshot { get } init(snapshot: Snapshot) } -extension GraphQLSelectionSet { - public init(from decoder: Decoder) throws { +public extension GraphQLSelectionSet { + init(from decoder: Decoder) throws { if let jsonObject = try? APISwiftJSONValue(from: decoder) { let encoder = JSONEncoder() let jsonData = try encoder.encode(jsonObject) @@ -92,10 +100,10 @@ enum APISwiftJSONValue: Codable { case object([String: APISwiftJSONValue]) case string(String) case null - + init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() - + if let value = try? container.decode([String: APISwiftJSONValue].self) { self = .object(value) } else if let value = try? container.decode([APISwiftJSONValue].self) { @@ -110,10 +118,10 @@ enum APISwiftJSONValue: Codable { self = .null } } - + func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() - + switch self { case .array(let value): try container.encode(value) @@ -136,19 +144,19 @@ public struct GraphQLField: GraphQLSelection { let name: String let alias: String? let arguments: [String: GraphQLInputValue]? - + var responseKey: String { return alias ?? name } - + let type: GraphQLOutputType - + public init(_ name: String, alias: String? = nil, arguments: [String: GraphQLInputValue]? = nil, type: GraphQLOutputType) { self.name = name self.alias = alias - + self.arguments = arguments - + self.type = type } } @@ -157,7 +165,7 @@ public indirect enum GraphQLOutputType { case object([GraphQLSelection]) case nonNull(GraphQLOutputType) case list(GraphQLOutputType) - + var namedType: GraphQLOutputType { switch self { case .nonNull(let innerType), .list(let innerType): @@ -171,25 +179,25 @@ public struct GraphQLBooleanCondition: GraphQLSelection { let variableName: String let inverted: Bool let selections: [GraphQLSelection] - + public init(variableName: String, inverted: Bool, selections: [GraphQLSelection]) { self.variableName = variableName - self.inverted = inverted; - self.selections = selections; + self.inverted = inverted + self.selections = selections } } public struct GraphQLTypeCondition: GraphQLSelection { let possibleTypes: [String] let selections: [GraphQLSelection] - + public init(possibleTypes: [String], selections: [GraphQLSelection]) { self.possibleTypes = possibleTypes - self.selections = selections; + self.selections = selections } } public struct GraphQLFragmentSpread: GraphQLSelection { let fragment: GraphQLFragment.Type - + public init(_ fragment: GraphQLFragment.Type) { self.fragment = fragment } @@ -197,10 +205,10 @@ public struct GraphQLFragmentSpread: GraphQLSelection { public struct GraphQLTypeCase: GraphQLSelection { let variants: [String: [GraphQLSelection]] let `default`: [GraphQLSelection] - + public init(variants: [String: [GraphQLSelection]], default: [GraphQLSelection]) { self.variants = variants - self.default = `default`; + self.default = `default` } } public typealias JSONObject = [String: Any] @@ -215,7 +223,7 @@ public enum JSONDecodingError: Error, LocalizedError { case nullValue case wrongType case couldNotConvert(value: Any, to: Any.Type) - + public var errorDescription: String? { switch self { case .missingValue: @@ -284,8 +292,8 @@ extension Bool: JSONDecodable, JSONEncodable { return self } } -extension RawRepresentable where RawValue: JSONDecodable { - public init(jsonValue value: Any) throws { +public extension RawRepresentable where RawValue: JSONDecodable { + init(jsonValue value: Any) throws { let rawValue = try RawValue(jsonValue: value) if let tempSelf = Self(rawValue: rawValue) { self = tempSelf @@ -294,17 +302,17 @@ extension RawRepresentable where RawValue: JSONDecodable { } } } -extension RawRepresentable where RawValue: JSONEncodable { - public var jsonValue: Any { +public extension RawRepresentable where RawValue: JSONEncodable { + var jsonValue: Any { return rawValue.jsonValue } } -extension Optional where Wrapped: JSONDecodable { - public init(jsonValue value: Any) throws { +public extension Optional where Wrapped: JSONDecodable { + init(jsonValue value: Any) throws { if value is NSNull { self = .none } else { - self = .some(try Wrapped(jsonValue: value)) + self = try .some(Wrapped(jsonValue: value)) } } } @@ -324,7 +332,7 @@ extension Dictionary: JSONEncodable { public var jsonValue: Any { return jsonObject } - + public var jsonObject: JSONObject { var jsonObject = JSONObject(minimumCapacity: count) for (key, value) in self { @@ -339,7 +347,7 @@ extension Dictionary: JSONEncodable { } extension Array: JSONEncodable { public var jsonValue: Any { - return map() { element -> (Any) in + return map { element -> (Any) in if case let element as JSONEncodable = element { return element.jsonValue } else { @@ -356,12 +364,12 @@ extension URL: JSONDecodable, JSONEncodable { self.init(string: string)! } public var jsonValue: Any { - return self.absoluteString + return absoluteString } } extension Dictionary { static func += (lhs: inout Dictionary, rhs: Dictionary) { - lhs.merge(rhs) { (_, new) in new } + lhs.merge(rhs) { _, new in new } } } #elseif canImport(AWSAppSync) @@ -370,11 +378,11 @@ import AWSAppSync public struct APISwift { public struct CreateTodoInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, name: String, description: String? = nil) { - graphQLMap = ["id": id, "name": name, "description": description] + self.graphQLMap = ["id": id, "name": name, "description": description] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -383,7 +391,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return graphQLMap["name"] as! String @@ -392,7 +400,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return graphQLMap["description"] as! String? @@ -402,14 +410,14 @@ public struct APISwift { } } } - + public struct ModelTodoConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(name: ModelStringInput? = nil, description: ModelStringInput? = nil, and: [ModelTodoConditionInput?]? = nil, or: [ModelTodoConditionInput?]? = nil, not: ModelTodoConditionInput? = nil) { - graphQLMap = ["name": name, "description": description, "and": and, "or": or, "not": not] + self.graphQLMap = ["name": name, "description": description, "and": and, "or": or, "not": not] } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -418,7 +426,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var description: ModelStringInput? { get { return graphQLMap["description"] as! ModelStringInput? @@ -427,7 +435,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "description") } } - + public var and: [ModelTodoConditionInput?]? { get { return graphQLMap["and"] as! [ModelTodoConditionInput?]? @@ -436,7 +444,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelTodoConditionInput?]? { get { return graphQLMap["or"] as! [ModelTodoConditionInput?]? @@ -445,7 +453,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelTodoConditionInput? { get { return graphQLMap["not"] as! ModelTodoConditionInput? @@ -455,14 +463,14 @@ public struct APISwift { } } } - + public struct ModelStringInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(ne: String? = nil, eq: String? = nil, le: String? = nil, lt: String? = nil, ge: String? = nil, gt: String? = nil, contains: String? = nil, notContains: String? = nil, between: [String?]? = nil, beginsWith: String? = nil, attributeExists: Bool? = nil, attributeType: ModelAttributeTypes? = nil, size: ModelSizeInput? = nil) { - graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "contains": contains, "notContains": notContains, "between": between, "beginsWith": beginsWith, "attributeExists": attributeExists, "attributeType": attributeType, "size": size] + self.graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "contains": contains, "notContains": notContains, "between": between, "beginsWith": beginsWith, "attributeExists": attributeExists, "attributeType": attributeType, "size": size] } - + public var ne: String? { get { return graphQLMap["ne"] as! String? @@ -471,7 +479,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var eq: String? { get { return graphQLMap["eq"] as! String? @@ -480,7 +488,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var le: String? { get { return graphQLMap["le"] as! String? @@ -489,7 +497,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "le") } } - + public var lt: String? { get { return graphQLMap["lt"] as! String? @@ -498,7 +506,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "lt") } } - + public var ge: String? { get { return graphQLMap["ge"] as! String? @@ -507,7 +515,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ge") } } - + public var gt: String? { get { return graphQLMap["gt"] as! String? @@ -516,7 +524,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "gt") } } - + public var contains: String? { get { return graphQLMap["contains"] as! String? @@ -525,7 +533,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "contains") } } - + public var notContains: String? { get { return graphQLMap["notContains"] as! String? @@ -534,7 +542,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "notContains") } } - + public var between: [String?]? { get { return graphQLMap["between"] as! [String?]? @@ -543,7 +551,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "between") } } - + public var beginsWith: String? { get { return graphQLMap["beginsWith"] as! String? @@ -552,7 +560,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "beginsWith") } } - + public var attributeExists: Bool? { get { return graphQLMap["attributeExists"] as! Bool? @@ -561,7 +569,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeExists") } } - + public var attributeType: ModelAttributeTypes? { get { return graphQLMap["attributeType"] as! ModelAttributeTypes? @@ -570,7 +578,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeType") } } - + public var size: ModelSizeInput? { get { return graphQLMap["size"] as! ModelSizeInput? @@ -580,7 +588,7 @@ public struct APISwift { } } } - + public enum ModelAttributeTypes: RawRepresentable, Equatable, JSONDecodable, JSONEncodable { public typealias RawValue = String case binary @@ -595,7 +603,7 @@ public struct APISwift { case null /// Auto generated constant for unknown enum values case unknown(RawValue) - + public init?(rawValue: RawValue) { switch rawValue { case "binary": self = .binary @@ -611,7 +619,7 @@ public struct APISwift { default: self = .unknown(rawValue) } } - + public var rawValue: RawValue { switch self { case .binary: return "binary" @@ -627,7 +635,7 @@ public struct APISwift { case .unknown(let value): return value } } - + public static func == (lhs: ModelAttributeTypes, rhs: ModelAttributeTypes) -> Bool { switch (lhs, rhs) { case (.binary, .binary): return true @@ -645,14 +653,14 @@ public struct APISwift { } } } - + public struct ModelSizeInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(ne: Int? = nil, eq: Int? = nil, le: Int? = nil, lt: Int? = nil, ge: Int? = nil, gt: Int? = nil, between: [Int?]? = nil) { - graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "between": between] + self.graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "between": between] } - + public var ne: Int? { get { return graphQLMap["ne"] as! Int? @@ -661,7 +669,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var eq: Int? { get { return graphQLMap["eq"] as! Int? @@ -670,7 +678,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var le: Int? { get { return graphQLMap["le"] as! Int? @@ -679,7 +687,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "le") } } - + public var lt: Int? { get { return graphQLMap["lt"] as! Int? @@ -688,7 +696,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "lt") } } - + public var ge: Int? { get { return graphQLMap["ge"] as! Int? @@ -697,7 +705,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ge") } } - + public var gt: Int? { get { return graphQLMap["gt"] as! Int? @@ -706,7 +714,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "gt") } } - + public var between: [Int?]? { get { return graphQLMap["between"] as! [Int?]? @@ -716,14 +724,14 @@ public struct APISwift { } } } - + public struct UpdateTodoInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, name: String? = nil, description: String? = nil) { - graphQLMap = ["id": id, "name": name, "description": description] + self.graphQLMap = ["id": id, "name": name, "description": description] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -732,7 +740,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return graphQLMap["name"] as! String? @@ -741,7 +749,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return graphQLMap["description"] as! String? @@ -751,14 +759,14 @@ public struct APISwift { } } } - + public struct DeleteTodoInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -768,14 +776,14 @@ public struct APISwift { } } } - + public struct ModelTodoFilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, name: ModelStringInput? = nil, description: ModelStringInput? = nil, and: [ModelTodoFilterInput?]? = nil, or: [ModelTodoFilterInput?]? = nil, not: ModelTodoFilterInput? = nil) { - graphQLMap = ["id": id, "name": name, "description": description, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "name": name, "description": description, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -784,7 +792,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -793,7 +801,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var description: ModelStringInput? { get { return graphQLMap["description"] as! ModelStringInput? @@ -802,7 +810,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "description") } } - + public var and: [ModelTodoFilterInput?]? { get { return graphQLMap["and"] as! [ModelTodoFilterInput?]? @@ -811,7 +819,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelTodoFilterInput?]? { get { return graphQLMap["or"] as! [ModelTodoFilterInput?]? @@ -820,7 +828,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelTodoFilterInput? { get { return graphQLMap["not"] as! ModelTodoFilterInput? @@ -830,14 +838,14 @@ public struct APISwift { } } } - + public struct ModelIDInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(ne: GraphQLID? = nil, eq: GraphQLID? = nil, le: GraphQLID? = nil, lt: GraphQLID? = nil, ge: GraphQLID? = nil, gt: GraphQLID? = nil, contains: GraphQLID? = nil, notContains: GraphQLID? = nil, between: [GraphQLID?]? = nil, beginsWith: GraphQLID? = nil, attributeExists: Bool? = nil, attributeType: ModelAttributeTypes? = nil, size: ModelSizeInput? = nil) { - graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "contains": contains, "notContains": notContains, "between": between, "beginsWith": beginsWith, "attributeExists": attributeExists, "attributeType": attributeType, "size": size] + self.graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "contains": contains, "notContains": notContains, "between": between, "beginsWith": beginsWith, "attributeExists": attributeExists, "attributeType": attributeType, "size": size] } - + public var ne: GraphQLID? { get { return graphQLMap["ne"] as! GraphQLID? @@ -846,7 +854,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var eq: GraphQLID? { get { return graphQLMap["eq"] as! GraphQLID? @@ -855,7 +863,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var le: GraphQLID? { get { return graphQLMap["le"] as! GraphQLID? @@ -864,7 +872,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "le") } } - + public var lt: GraphQLID? { get { return graphQLMap["lt"] as! GraphQLID? @@ -873,7 +881,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "lt") } } - + public var ge: GraphQLID? { get { return graphQLMap["ge"] as! GraphQLID? @@ -882,7 +890,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ge") } } - + public var gt: GraphQLID? { get { return graphQLMap["gt"] as! GraphQLID? @@ -891,7 +899,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "gt") } } - + public var contains: GraphQLID? { get { return graphQLMap["contains"] as! GraphQLID? @@ -900,7 +908,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "contains") } } - + public var notContains: GraphQLID? { get { return graphQLMap["notContains"] as! GraphQLID? @@ -909,7 +917,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "notContains") } } - + public var between: [GraphQLID?]? { get { return graphQLMap["between"] as! [GraphQLID?]? @@ -918,7 +926,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "between") } } - + public var beginsWith: GraphQLID? { get { return graphQLMap["beginsWith"] as! GraphQLID? @@ -927,7 +935,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "beginsWith") } } - + public var attributeExists: Bool? { get { return graphQLMap["attributeExists"] as! Bool? @@ -936,7 +944,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeExists") } } - + public var attributeType: ModelAttributeTypes? { get { return graphQLMap["attributeType"] as! ModelAttributeTypes? @@ -945,7 +953,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeType") } } - + public var size: ModelSizeInput? { get { return graphQLMap["size"] as! ModelSizeInput? @@ -955,40 +963,40 @@ public struct APISwift { } } } - + public final class CreateTodoMutation: GraphQLMutation { public static let operationString = "mutation CreateTodo($input: CreateTodoInput!, $condition: ModelTodoConditionInput) {\n createTodo(input: $input, condition: $condition) {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public var input: CreateTodoInput public var condition: ModelTodoConditionInput? - + public init(input: CreateTodoInput, condition: ModelTodoConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createTodo", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createTodo: CreateTodo? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createTodo": createTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createTodo": createTodo.flatMap(\.snapshot)]) } - + public var createTodo: CreateTodo? { get { return (snapshot["createTodo"] as? Snapshot).flatMap { CreateTodo(snapshot: $0) } @@ -997,10 +1005,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createTodo") } } - + public struct CreateTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1009,17 +1017,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1028,7 +1036,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1037,7 +1045,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1046,7 +1054,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1055,7 +1063,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1064,7 +1072,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1076,40 +1084,40 @@ public struct APISwift { } } } - + public final class UpdateTodoMutation: GraphQLMutation { public static let operationString = "mutation UpdateTodo($input: UpdateTodoInput!, $condition: ModelTodoConditionInput) {\n updateTodo(input: $input, condition: $condition) {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateTodoInput public var condition: ModelTodoConditionInput? - + public init(input: UpdateTodoInput, condition: ModelTodoConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateTodo", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateTodo: UpdateTodo? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateTodo": updateTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateTodo": updateTodo.flatMap(\.snapshot)]) } - + public var updateTodo: UpdateTodo? { get { return (snapshot["updateTodo"] as? Snapshot).flatMap { UpdateTodo(snapshot: $0) } @@ -1118,10 +1126,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateTodo") } } - + public struct UpdateTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1130,17 +1138,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1149,7 +1157,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1158,7 +1166,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1167,7 +1175,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1176,7 +1184,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1185,7 +1193,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1197,40 +1205,40 @@ public struct APISwift { } } } - + public final class DeleteTodoMutation: GraphQLMutation { public static let operationString = "mutation DeleteTodo($input: DeleteTodoInput!, $condition: ModelTodoConditionInput) {\n deleteTodo(input: $input, condition: $condition) {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteTodoInput public var condition: ModelTodoConditionInput? - + public init(input: DeleteTodoInput, condition: ModelTodoConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteTodo", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteTodo: DeleteTodo? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteTodo": deleteTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteTodo": deleteTodo.flatMap(\.snapshot)]) } - + public var deleteTodo: DeleteTodo? { get { return (snapshot["deleteTodo"] as? Snapshot).flatMap { DeleteTodo(snapshot: $0) } @@ -1239,10 +1247,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteTodo") } } - + public struct DeleteTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1251,17 +1259,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1270,7 +1278,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1279,7 +1287,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1288,7 +1296,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1297,7 +1305,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1306,7 +1314,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1318,38 +1326,38 @@ public struct APISwift { } } } - + public final class GetTodoQuery: GraphQLQuery { public static let operationString = "query GetTodo($id: ID!) {\n getTodo(id: $id) {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getTodo", arguments: ["id": GraphQLVariable("id")], type: .object(GetTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getTodo: GetTodo? = nil) { - self.init(snapshot: ["__typename": "Query", "getTodo": getTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getTodo": getTodo.flatMap(\.snapshot)]) } - + public var getTodo: GetTodo? { get { return (snapshot["getTodo"] as? Snapshot).flatMap { GetTodo(snapshot: $0) } @@ -1358,10 +1366,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getTodo") } } - + public struct GetTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1370,17 +1378,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1389,7 +1397,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1398,7 +1406,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1407,7 +1415,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1416,7 +1424,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1425,7 +1433,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1437,42 +1445,42 @@ public struct APISwift { } } } - + public final class ListTodosQuery: GraphQLQuery { public static let operationString = "query ListTodos($filter: ModelTodoFilterInput, $limit: Int, $nextToken: String) {\n listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelTodoFilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelTodoFilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listTodos", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listTodos: ListTodo? = nil) { - self.init(snapshot: ["__typename": "Query", "listTodos": listTodos.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listTodos": listTodos.flatMap(\.snapshot)]) } - + public var listTodos: ListTodo? { get { return (snapshot["listTodos"] as? Snapshot).flatMap { ListTodo(snapshot: $0) } @@ -1481,26 +1489,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listTodos") } } - + public struct ListTodo: GraphQLSelectionSet { public static let possibleTypes = ["ModelTodoConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelTodoConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelTodoConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1509,16 +1517,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -1527,10 +1535,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1539,17 +1547,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1558,7 +1566,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1567,7 +1575,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1576,7 +1584,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1585,7 +1593,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1594,7 +1602,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1607,31 +1615,31 @@ public struct APISwift { } } } - + public final class OnCreateTodoSubscription: GraphQLSubscription { public static let operationString = "subscription OnCreateTodo {\n onCreateTodo {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateTodo", type: .object(OnCreateTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateTodo: OnCreateTodo? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateTodo": onCreateTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateTodo": onCreateTodo.flatMap(\.snapshot)]) } - + public var onCreateTodo: OnCreateTodo? { get { return (snapshot["onCreateTodo"] as? Snapshot).flatMap { OnCreateTodo(snapshot: $0) } @@ -1640,10 +1648,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateTodo") } } - + public struct OnCreateTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1652,17 +1660,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1671,7 +1679,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1680,7 +1688,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1689,7 +1697,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1698,7 +1706,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1707,7 +1715,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1719,31 +1727,31 @@ public struct APISwift { } } } - + public final class OnUpdateTodoSubscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateTodo {\n onUpdateTodo {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateTodo", type: .object(OnUpdateTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateTodo: OnUpdateTodo? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateTodo": onUpdateTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateTodo": onUpdateTodo.flatMap(\.snapshot)]) } - + public var onUpdateTodo: OnUpdateTodo? { get { return (snapshot["onUpdateTodo"] as? Snapshot).flatMap { OnUpdateTodo(snapshot: $0) } @@ -1752,10 +1760,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateTodo") } } - + public struct OnUpdateTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1764,17 +1772,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1783,7 +1791,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1792,7 +1800,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1801,7 +1809,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1810,7 +1818,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1819,7 +1827,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1831,31 +1839,31 @@ public struct APISwift { } } } - + public final class OnDeleteTodoSubscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteTodo {\n onDeleteTodo {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteTodo", type: .object(OnDeleteTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteTodo: OnDeleteTodo? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteTodo": onDeleteTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteTodo": onDeleteTodo.flatMap(\.snapshot)]) } - + public var onDeleteTodo: OnDeleteTodo? { get { return (snapshot["onDeleteTodo"] as? Snapshot).flatMap { OnDeleteTodo(snapshot: $0) } @@ -1864,10 +1872,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteTodo") } } - + public struct OnDeleteTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1876,17 +1884,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1895,7 +1903,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1904,7 +1912,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1913,7 +1921,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1922,7 +1930,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1931,7 +1939,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/GraphQLWithIAMIntegrationAPISwiftTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/GraphQLWithIAMIntegrationAPISwiftTests.swift index c3e8e8e48b..99ac025ef3 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/GraphQLWithIAMIntegrationAPISwiftTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/GraphQLWithIAMIntegrationAPISwiftTests.swift @@ -5,28 +5,32 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSAPIPlugin import AWSCognitoAuthPlugin +import XCTest @testable import Amplify @testable import APIHostApp extension GraphQLWithIAMIntegrationTests { - + func createTodoAPISwift() async throws { let expectedId = UUID().uuidString let expectedName = "testCreateTodoMutationName" let expectedDescription = "testCreateTodoMutationDescription" - let input = APISwift.CreateTodoInput(id: expectedId, - name: expectedName, - description: expectedDescription) + let input = APISwift.CreateTodoInput( + id: expectedId, + name: expectedName, + description: expectedDescription + ) let mutation = APISwift.CreateTodoMutation(input: input) - let request = GraphQLRequest(document: APISwift.CreateTodoMutation.operationString, - variables: mutation.variables?.jsonObject, - responseType: APISwift.CreateTodoMutation.Data.self) - - + let request = GraphQLRequest( + document: APISwift.CreateTodoMutation.operationString, + variables: mutation.variables?.jsonObject, + responseType: APISwift.CreateTodoMutation.Data.self + ) + + let event = try await Amplify.API.mutate(request: request) switch event { case .success(let data): @@ -44,7 +48,7 @@ extension GraphQLWithIAMIntegrationTests { XCTFail("Unexpected .failed event: \(error)") } } - + func testCreateTodoAPISwift() async throws { try await createAuthenticatedUser() try await createTodoAPISwift() diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/GraphQLWithIAMIntegrationTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/GraphQLWithIAMIntegrationTests.swift index a100bc9b29..8924a70acc 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/GraphQLWithIAMIntegrationTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/GraphQLWithIAMIntegrationTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSAPIPlugin import AWSCognitoAuthPlugin +import XCTest @testable import Amplify @testable import APIHostApp @@ -31,7 +31,7 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { } catch { XCTFail("Error during setup: \(error)") } - + } override func tearDown() async throws { @@ -40,7 +40,7 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { } await Amplify.reset() } - + func testSignUserOut() async throws { if try await isSignedIn() { print("User is signed in") @@ -48,7 +48,7 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { await signOut() } - + /// Test create mutation with a custom GraphQL Document /// /// - Given: A custom GraphQL document containing CreateTodo mutation request, and user is signed in. @@ -61,7 +61,7 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { try await createAuthenticatedUser() try await createTodoTest() } - + /// An unauthenticated user should not fail /// /// - Given: A CreateTodo mutation request, and user is not signed in. @@ -76,18 +76,22 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { } try await createTodoTest() } - + func createTodoTest() async throws { let expectedId = UUID().uuidString let expectedName = "testCreateTodoMutationName" let expectedDescription = "testCreateTodoMutationDescription" - let request = GraphQLRequest(document: CreateTodoMutation.document, - variables: CreateTodoMutation.variables(id: expectedId, - name: expectedName, - description: expectedDescription), - responseType: CreateTodoMutation.Data.self) - - + let request = GraphQLRequest( + document: CreateTodoMutation.document, + variables: CreateTodoMutation.variables( + id: expectedId, + name: expectedName, + description: expectedDescription + ), + responseType: CreateTodoMutation.Data.self + ) + + let event = try await Amplify.API.mutate(request: request) switch event { case .success(let data): @@ -120,7 +124,7 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { } try await onCreateTodoTest() } - + /// A subscription to onCreate todo should receive an event for each create Todo mutation API called /// /// - Given: An onCreate Todo subscription established @@ -133,7 +137,7 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { try await createAuthenticatedUser() try await onCreateTodoTest() } - + func onCreateTodoTest() async throws { let connectedInvoked = expectation(description: "Connection established") let progressInvoked = expectation(description: "progress invoked") @@ -167,7 +171,7 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { } } } - + await fulfillment(of: [connectedInvoked], timeout: TestCommonConstants.networkTimeout) _ = try await createTodo(id: uuid, name: name) _ = try await createTodo(id: uuid2, name: name) @@ -177,7 +181,7 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { } // MARK: - Helpers - + func createTodo(id: String, name: String) async throws -> Todo { let todo = Todo(id: id, name: name) let event = try await Amplify.API.mutate(request: .create(todo)) @@ -190,7 +194,7 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { } // MARK: - Auth Helpers - + func createAuthenticatedUser() async throws { if try await isSignedIn() { await signOut() @@ -198,12 +202,12 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { try await signUp() try await signIn() } - + func isSignedIn() async throws -> Bool { let authSession = try await Amplify.Auth.fetchAuthSession() return authSession.isSignedIn } - + func signUp() async throws { let signUpResult = try await Amplify.Auth.signUp(username: username, password: password) guard signUpResult.isSignUpComplete else { @@ -211,7 +215,7 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { return } } - + func signIn() async throws { let signInResult = try await Amplify.Auth.signIn(username: username, password: password) guard signInResult.isSignedIn else { @@ -219,7 +223,7 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { return } } - + func signOut() async { _ = await Amplify.Auth.signOut() } @@ -231,9 +235,11 @@ class GraphQLWithIAMIntegrationTests: XCTestCase { public var name: String public var description: String? - init(id: String = UUID().uuidString, - name: String, - description: String? = nil) { + init( + id: String = UUID().uuidString, + name: String, + description: String? = nil + ) { self.id = id self.name = name self.description = description diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/Todo.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/Todo.swift index 2a88d92570..0c6e1cb0de 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/Todo.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLIAMTests/Todo.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct Todo: Decodable { let typename: String @@ -48,15 +48,15 @@ class CreateTodoMutation { static func variables(id: String? = nil, name: String?, description: String? = nil) -> [String: Any] { var input: [String: Any] = [:] - if let id = id { + if let id { input.updateValue(id, forKey: "id") } - if let name = name { + if let name { input.updateValue(name, forKey: "name") } - if let description = description { + if let description { input.updateValue(description, forKey: "description") } @@ -92,10 +92,10 @@ class UpdateTodoMutation { static func variables(id: String, name: String? = nil, description: String? = nil) -> [String: Any] { var input: [String: Any] = [:] input.updateValue(id, forKey: "id") - if let name = name { + if let name { input.updateValue(name, forKey: "name") } - if let description = description { + if let description { input.updateValue(description, forKey: "description") } return ["input": input] @@ -119,7 +119,7 @@ class DeleteTodoMutation { static func variables(id: String?) -> [String: Any] { var input: [String: Any] = [:] - if let id = id { + if let id { input.updateValue(id, forKey: "id") } @@ -166,20 +166,22 @@ class ListTodosQuery { }\n} """ - static func variables(filter: [String: Any]? = nil, - limit: Int? = nil, - nextToken: String? = nil) -> [String: Any] { + static func variables( + filter: [String: Any]? = nil, + limit: Int? = nil, + nextToken: String? = nil + ) -> [String: Any] { var input: [String: Any] = [:] - if let filter = filter { + if let filter { input.updateValue(filter, forKey: "filter") } - if let limit = limit { + if let limit { input.updateValue(limit, forKey: "limit") } - if let nextToken = nextToken { + if let nextToken { input.updateValue(nextToken, forKey: "nextToken") } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLLambdaAuthTests/GraphQLWithLambdaAuthIntegrationTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLLambdaAuthTests/GraphQLWithLambdaAuthIntegrationTests.swift index 5be0f9d63a..43732b3adc 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLLambdaAuthTests/GraphQLWithLambdaAuthIntegrationTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLLambdaAuthTests/GraphQLWithLambdaAuthIntegrationTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSAPIPlugin +import XCTest @testable import Amplify #if os(watchOS) @testable import APIWatchApp @@ -15,9 +15,9 @@ import AWSAPIPlugin #endif class GraphQLWithLambdaAuthIntegrationTests: XCTestCase { - + let amplifyConfigurationFile = "testconfiguration/GraphQLWithLambdaAuthIntegrationTests-amplifyconfiguration" - + override func setUp() async throws{ do { try Amplify.add(plugin: AWSAPIPlugin(apiAuthProviderFactory: TestAPIAuthProviderFactory())) @@ -46,11 +46,15 @@ class GraphQLWithLambdaAuthIntegrationTests: XCTestCase { let expectedId = UUID().uuidString let expectedName = "testCreateTodoMutationName" let expectedDescription = "testCreateTodoMutationDescription" - let request = GraphQLRequest(document: CreateTodoMutation.document, - variables: CreateTodoMutation.variables(id: expectedId, - name: expectedName, - description: expectedDescription), - responseType: CreateTodoMutation.Data.self) + let request = GraphQLRequest( + document: CreateTodoMutation.document, + variables: CreateTodoMutation.variables( + id: expectedId, + name: expectedName, + description: expectedDescription + ), + responseType: CreateTodoMutation.Data.self + ) let graphQLResponse = try await Amplify.API.mutate(request: request) guard case let .success(data) = graphQLResponse else { XCTFail("Missing successful response") @@ -60,7 +64,7 @@ class GraphQLWithLambdaAuthIntegrationTests: XCTestCase { XCTFail("Missing Todo") return } - + XCTAssertEqual(todo.id, expectedId) XCTAssertEqual(todo.name, expectedName) XCTAssertEqual(todo.description, expectedDescription) @@ -103,12 +107,12 @@ class GraphQLWithLambdaAuthIntegrationTests: XCTestCase { /// func testOnCreateTodoSubscription() async throws { let connectedInvoked = expectation(description: "Connection established") - + let uuid = UUID().uuidString let uuid2 = UUID().uuidString let name = String("\(#function)".dropLast(2)) let subscriptions = Amplify.API.subscribe(request: .subscription(of: Todo.self, type: .onCreate)) - + let progressInvoked = expectation(description: "progress invoked") progressInvoked.expectedFulfillmentCount = 2 @@ -161,9 +165,11 @@ class GraphQLWithLambdaAuthIntegrationTests: XCTestCase { public var name: String public var description: String? - init(id: String = UUID().uuidString, - name: String, - description: String? = nil) { + init( + id: String = UUID().uuidString, + name: String, + description: String? = nil + ) { self.id = id self.name = name self.description = description diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLLambdaAuthTests/Todo.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLLambdaAuthTests/Todo.swift index ab57c527ec..72d7161d61 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLLambdaAuthTests/Todo.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLLambdaAuthTests/Todo.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct Todo: Decodable { let typename: String @@ -48,15 +48,15 @@ class CreateTodoMutation { static func variables(id: String? = nil, name: String?, description: String? = nil) -> [String: Any] { var input: [String: Any] = [:] - if let id = id { + if let id { input.updateValue(id, forKey: "id") } - if let name = name { + if let name { input.updateValue(name, forKey: "name") } - if let description = description { + if let description { input.updateValue(description, forKey: "description") } @@ -92,10 +92,10 @@ class UpdateTodoMutation { static func variables(id: String, name: String? = nil, description: String? = nil) -> [String: Any] { var input: [String: Any] = [:] input.updateValue(id, forKey: "id") - if let name = name { + if let name { input.updateValue(name, forKey: "name") } - if let description = description { + if let description { input.updateValue(description, forKey: "description") } return ["input": input] @@ -119,7 +119,7 @@ class DeleteTodoMutation { static func variables(id: String?) -> [String: Any] { var input: [String: Any] = [:] - if let id = id { + if let id { input.updateValue(id, forKey: "id") } @@ -166,20 +166,22 @@ class ListTodosQuery { }\n} """ - static func variables(filter: [String: Any]? = nil, - limit: Int? = nil, - nextToken: String? = nil) -> [String: Any] { + static func variables( + filter: [String: Any]? = nil, + limit: Int? = nil, + nextToken: String? = nil + ) -> [String: Any] { var input: [String: Any] = [:] - if let filter = filter { + if let filter { input.updateValue(filter, forKey: "filter") } - if let limit = limit { + if let limit { input.updateValue(limit, forKey: "limit") } - if let nextToken = nextToken { + if let nextToken { input.updateValue(nextToken, forKey: "nextToken") } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/API.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/API.swift index e951fb7c91..bf7bf16d35 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/API.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/API.swift @@ -1,26 +1,34 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // This file was automatically generated and should not be edited. #if canImport(AWSAPIPlugin) import Foundation + public protocol GraphQLInputValue { } public struct GraphQLVariable { let name: String - + public init(_ name: String) { self.name = name } } extension GraphQLVariable: GraphQLInputValue { } -extension JSONEncodable { - public func evaluate(with variables: [String: JSONEncodable]?) throws -> Any { +public extension JSONEncodable { + func evaluate(with variables: [String: JSONEncodable]?) throws -> Any { return jsonValue } } public typealias GraphQLMap = [String: JSONEncodable?] -extension Dictionary where Key == String, Value == JSONEncodable? { - public var withNilValuesRemoved: Dictionary { - var filtered = Dictionary(minimumCapacity: count) +public extension [String: JSONEncodable?] { + var withNilValuesRemoved: [String: JSONEncodable] { + var filtered = [String: JSONEncodable](minimumCapacity: count) for (key, value) in self { if value != nil { filtered[key] = value @@ -39,13 +47,13 @@ public extension GraphQLMapConvertible { } public typealias GraphQLID = String public protocol APISwiftGraphQLOperation: AnyObject { - + static var operationString: String { get } static var requestString: String { get } static var operationIdentifier: String? { get } - + var variables: GraphQLMap? { get } - + associatedtype Data: GraphQLSelectionSet } public extension APISwiftGraphQLOperation { @@ -68,12 +76,12 @@ public protocol GraphQLFragment: GraphQLSelectionSet { public typealias Snapshot = [String: Any?] public protocol GraphQLSelectionSet: Decodable { static var selections: [GraphQLSelection] { get } - + var snapshot: Snapshot { get } init(snapshot: Snapshot) } -extension GraphQLSelectionSet { - public init(from decoder: Decoder) throws { +public extension GraphQLSelectionSet { + init(from decoder: Decoder) throws { if let jsonObject = try? APISwiftJSONValue(from: decoder) { let encoder = JSONEncoder() let jsonData = try encoder.encode(jsonObject) @@ -92,10 +100,10 @@ enum APISwiftJSONValue: Codable { case object([String: APISwiftJSONValue]) case string(String) case null - + init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() - + if let value = try? container.decode([String: APISwiftJSONValue].self) { self = .object(value) } else if let value = try? container.decode([APISwiftJSONValue].self) { @@ -110,10 +118,10 @@ enum APISwiftJSONValue: Codable { self = .null } } - + func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() - + switch self { case .array(let value): try container.encode(value) @@ -136,19 +144,19 @@ public struct GraphQLField: GraphQLSelection { let name: String let alias: String? let arguments: [String: GraphQLInputValue]? - + var responseKey: String { return alias ?? name } - + let type: GraphQLOutputType - + public init(_ name: String, alias: String? = nil, arguments: [String: GraphQLInputValue]? = nil, type: GraphQLOutputType) { self.name = name self.alias = alias - + self.arguments = arguments - + self.type = type } } @@ -157,7 +165,7 @@ public indirect enum GraphQLOutputType { case object([GraphQLSelection]) case nonNull(GraphQLOutputType) case list(GraphQLOutputType) - + var namedType: GraphQLOutputType { switch self { case .nonNull(let innerType), .list(let innerType): @@ -171,25 +179,25 @@ public struct GraphQLBooleanCondition: GraphQLSelection { let variableName: String let inverted: Bool let selections: [GraphQLSelection] - + public init(variableName: String, inverted: Bool, selections: [GraphQLSelection]) { self.variableName = variableName - self.inverted = inverted; - self.selections = selections; + self.inverted = inverted + self.selections = selections } } public struct GraphQLTypeCondition: GraphQLSelection { let possibleTypes: [String] let selections: [GraphQLSelection] - + public init(possibleTypes: [String], selections: [GraphQLSelection]) { self.possibleTypes = possibleTypes - self.selections = selections; + self.selections = selections } } public struct GraphQLFragmentSpread: GraphQLSelection { let fragment: GraphQLFragment.Type - + public init(_ fragment: GraphQLFragment.Type) { self.fragment = fragment } @@ -197,10 +205,10 @@ public struct GraphQLFragmentSpread: GraphQLSelection { public struct GraphQLTypeCase: GraphQLSelection { let variants: [String: [GraphQLSelection]] let `default`: [GraphQLSelection] - + public init(variants: [String: [GraphQLSelection]], default: [GraphQLSelection]) { self.variants = variants - self.default = `default`; + self.default = `default` } } public typealias JSONObject = [String: Any] @@ -215,7 +223,7 @@ public enum JSONDecodingError: Error, LocalizedError { case nullValue case wrongType case couldNotConvert(value: Any, to: Any.Type) - + public var errorDescription: String? { switch self { case .missingValue: @@ -284,8 +292,8 @@ extension Bool: JSONDecodable, JSONEncodable { return self } } -extension RawRepresentable where RawValue: JSONDecodable { - public init(jsonValue value: Any) throws { +public extension RawRepresentable where RawValue: JSONDecodable { + init(jsonValue value: Any) throws { let rawValue = try RawValue(jsonValue: value) if let tempSelf = Self(rawValue: rawValue) { self = tempSelf @@ -294,17 +302,17 @@ extension RawRepresentable where RawValue: JSONDecodable { } } } -extension RawRepresentable where RawValue: JSONEncodable { - public var jsonValue: Any { +public extension RawRepresentable where RawValue: JSONEncodable { + var jsonValue: Any { return rawValue.jsonValue } } -extension Optional where Wrapped: JSONDecodable { - public init(jsonValue value: Any) throws { +public extension Optional where Wrapped: JSONDecodable { + init(jsonValue value: Any) throws { if value is NSNull { self = .none } else { - self = .some(try Wrapped(jsonValue: value)) + self = try .some(Wrapped(jsonValue: value)) } } } @@ -324,7 +332,7 @@ extension Dictionary: JSONEncodable { public var jsonValue: Any { return jsonObject } - + public var jsonObject: JSONObject { var jsonObject = JSONObject(minimumCapacity: count) for (key, value) in self { @@ -339,7 +347,7 @@ extension Dictionary: JSONEncodable { } extension Array: JSONEncodable { public var jsonValue: Any { - return map() { element -> (Any) in + return map { element -> (Any) in if case let element as JSONEncodable = element { return element.jsonValue } else { @@ -356,12 +364,12 @@ extension URL: JSONDecodable, JSONEncodable { self.init(string: string)! } public var jsonValue: Any { - return self.absoluteString + return absoluteString } } extension Dictionary { static func += (lhs: inout Dictionary, rhs: Dictionary) { - lhs.merge(rhs) { (_, new) in new } + lhs.merge(rhs) { _, new in new } } } #elseif canImport(AWSAppSync) @@ -371,11 +379,11 @@ import AWSAppSync public struct APISwift { public struct CreateTodoInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID? = nil, name: String, description: String? = nil) { - graphQLMap = ["id": id, "name": name, "description": description] + self.graphQLMap = ["id": id, "name": name, "description": description] } - + public var id: GraphQLID? { get { return graphQLMap["id"] as! GraphQLID? @@ -384,7 +392,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return graphQLMap["name"] as! String @@ -393,7 +401,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return graphQLMap["description"] as! String? @@ -403,14 +411,14 @@ public struct APISwift { } } } - + public struct ModelTodoConditionInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(name: ModelStringInput? = nil, description: ModelStringInput? = nil, and: [ModelTodoConditionInput?]? = nil, or: [ModelTodoConditionInput?]? = nil, not: ModelTodoConditionInput? = nil) { - graphQLMap = ["name": name, "description": description, "and": and, "or": or, "not": not] + self.graphQLMap = ["name": name, "description": description, "and": and, "or": or, "not": not] } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -419,7 +427,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var description: ModelStringInput? { get { return graphQLMap["description"] as! ModelStringInput? @@ -428,7 +436,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "description") } } - + public var and: [ModelTodoConditionInput?]? { get { return graphQLMap["and"] as! [ModelTodoConditionInput?]? @@ -437,7 +445,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelTodoConditionInput?]? { get { return graphQLMap["or"] as! [ModelTodoConditionInput?]? @@ -446,7 +454,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelTodoConditionInput? { get { return graphQLMap["not"] as! ModelTodoConditionInput? @@ -456,14 +464,14 @@ public struct APISwift { } } } - + public struct ModelStringInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(ne: String? = nil, eq: String? = nil, le: String? = nil, lt: String? = nil, ge: String? = nil, gt: String? = nil, contains: String? = nil, notContains: String? = nil, between: [String?]? = nil, beginsWith: String? = nil, attributeExists: Bool? = nil, attributeType: ModelAttributeTypes? = nil, size: ModelSizeInput? = nil) { - graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "contains": contains, "notContains": notContains, "between": between, "beginsWith": beginsWith, "attributeExists": attributeExists, "attributeType": attributeType, "size": size] + self.graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "contains": contains, "notContains": notContains, "between": between, "beginsWith": beginsWith, "attributeExists": attributeExists, "attributeType": attributeType, "size": size] } - + public var ne: String? { get { return graphQLMap["ne"] as! String? @@ -472,7 +480,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var eq: String? { get { return graphQLMap["eq"] as! String? @@ -481,7 +489,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var le: String? { get { return graphQLMap["le"] as! String? @@ -490,7 +498,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "le") } } - + public var lt: String? { get { return graphQLMap["lt"] as! String? @@ -499,7 +507,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "lt") } } - + public var ge: String? { get { return graphQLMap["ge"] as! String? @@ -508,7 +516,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ge") } } - + public var gt: String? { get { return graphQLMap["gt"] as! String? @@ -517,7 +525,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "gt") } } - + public var contains: String? { get { return graphQLMap["contains"] as! String? @@ -526,7 +534,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "contains") } } - + public var notContains: String? { get { return graphQLMap["notContains"] as! String? @@ -535,7 +543,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "notContains") } } - + public var between: [String?]? { get { return graphQLMap["between"] as! [String?]? @@ -544,7 +552,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "between") } } - + public var beginsWith: String? { get { return graphQLMap["beginsWith"] as! String? @@ -553,7 +561,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "beginsWith") } } - + public var attributeExists: Bool? { get { return graphQLMap["attributeExists"] as! Bool? @@ -562,7 +570,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeExists") } } - + public var attributeType: ModelAttributeTypes? { get { return graphQLMap["attributeType"] as! ModelAttributeTypes? @@ -571,7 +579,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeType") } } - + public var size: ModelSizeInput? { get { return graphQLMap["size"] as! ModelSizeInput? @@ -581,7 +589,7 @@ public struct APISwift { } } } - + public enum ModelAttributeTypes: RawRepresentable, Equatable, JSONDecodable, JSONEncodable { public typealias RawValue = String case binary @@ -596,7 +604,7 @@ public struct APISwift { case null /// Auto generated constant for unknown enum values case unknown(RawValue) - + public init?(rawValue: RawValue) { switch rawValue { case "binary": self = .binary @@ -612,7 +620,7 @@ public struct APISwift { default: self = .unknown(rawValue) } } - + public var rawValue: RawValue { switch self { case .binary: return "binary" @@ -628,7 +636,7 @@ public struct APISwift { case .unknown(let value): return value } } - + public static func == (lhs: ModelAttributeTypes, rhs: ModelAttributeTypes) -> Bool { switch (lhs, rhs) { case (.binary, .binary): return true @@ -646,14 +654,14 @@ public struct APISwift { } } } - + public struct ModelSizeInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(ne: Int? = nil, eq: Int? = nil, le: Int? = nil, lt: Int? = nil, ge: Int? = nil, gt: Int? = nil, between: [Int?]? = nil) { - graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "between": between] + self.graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "between": between] } - + public var ne: Int? { get { return graphQLMap["ne"] as! Int? @@ -662,7 +670,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var eq: Int? { get { return graphQLMap["eq"] as! Int? @@ -671,7 +679,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var le: Int? { get { return graphQLMap["le"] as! Int? @@ -680,7 +688,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "le") } } - + public var lt: Int? { get { return graphQLMap["lt"] as! Int? @@ -689,7 +697,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "lt") } } - + public var ge: Int? { get { return graphQLMap["ge"] as! Int? @@ -698,7 +706,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ge") } } - + public var gt: Int? { get { return graphQLMap["gt"] as! Int? @@ -707,7 +715,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "gt") } } - + public var between: [Int?]? { get { return graphQLMap["between"] as! [Int?]? @@ -717,14 +725,14 @@ public struct APISwift { } } } - + public struct UpdateTodoInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID, name: String? = nil, description: String? = nil) { - graphQLMap = ["id": id, "name": name, "description": description] + self.graphQLMap = ["id": id, "name": name, "description": description] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -733,7 +741,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: String? { get { return graphQLMap["name"] as! String? @@ -742,7 +750,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return graphQLMap["description"] as! String? @@ -752,14 +760,14 @@ public struct APISwift { } } } - + public struct DeleteTodoInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: GraphQLID) { - graphQLMap = ["id": id] + self.graphQLMap = ["id": id] } - + public var id: GraphQLID { get { return graphQLMap["id"] as! GraphQLID @@ -769,14 +777,14 @@ public struct APISwift { } } } - + public struct ModelTodoFilterInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(id: ModelIDInput? = nil, name: ModelStringInput? = nil, description: ModelStringInput? = nil, and: [ModelTodoFilterInput?]? = nil, or: [ModelTodoFilterInput?]? = nil, not: ModelTodoFilterInput? = nil) { - graphQLMap = ["id": id, "name": name, "description": description, "and": and, "or": or, "not": not] + self.graphQLMap = ["id": id, "name": name, "description": description, "and": and, "or": or, "not": not] } - + public var id: ModelIDInput? { get { return graphQLMap["id"] as! ModelIDInput? @@ -785,7 +793,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "id") } } - + public var name: ModelStringInput? { get { return graphQLMap["name"] as! ModelStringInput? @@ -794,7 +802,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "name") } } - + public var description: ModelStringInput? { get { return graphQLMap["description"] as! ModelStringInput? @@ -803,7 +811,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "description") } } - + public var and: [ModelTodoFilterInput?]? { get { return graphQLMap["and"] as! [ModelTodoFilterInput?]? @@ -812,7 +820,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "and") } } - + public var or: [ModelTodoFilterInput?]? { get { return graphQLMap["or"] as! [ModelTodoFilterInput?]? @@ -821,7 +829,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "or") } } - + public var not: ModelTodoFilterInput? { get { return graphQLMap["not"] as! ModelTodoFilterInput? @@ -831,14 +839,14 @@ public struct APISwift { } } } - + public struct ModelIDInput: GraphQLMapConvertible { public var graphQLMap: GraphQLMap - + public init(ne: GraphQLID? = nil, eq: GraphQLID? = nil, le: GraphQLID? = nil, lt: GraphQLID? = nil, ge: GraphQLID? = nil, gt: GraphQLID? = nil, contains: GraphQLID? = nil, notContains: GraphQLID? = nil, between: [GraphQLID?]? = nil, beginsWith: GraphQLID? = nil, attributeExists: Bool? = nil, attributeType: ModelAttributeTypes? = nil, size: ModelSizeInput? = nil) { - graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "contains": contains, "notContains": notContains, "between": between, "beginsWith": beginsWith, "attributeExists": attributeExists, "attributeType": attributeType, "size": size] + self.graphQLMap = ["ne": ne, "eq": eq, "le": le, "lt": lt, "ge": ge, "gt": gt, "contains": contains, "notContains": notContains, "between": between, "beginsWith": beginsWith, "attributeExists": attributeExists, "attributeType": attributeType, "size": size] } - + public var ne: GraphQLID? { get { return graphQLMap["ne"] as! GraphQLID? @@ -847,7 +855,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ne") } } - + public var eq: GraphQLID? { get { return graphQLMap["eq"] as! GraphQLID? @@ -856,7 +864,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "eq") } } - + public var le: GraphQLID? { get { return graphQLMap["le"] as! GraphQLID? @@ -865,7 +873,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "le") } } - + public var lt: GraphQLID? { get { return graphQLMap["lt"] as! GraphQLID? @@ -874,7 +882,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "lt") } } - + public var ge: GraphQLID? { get { return graphQLMap["ge"] as! GraphQLID? @@ -883,7 +891,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "ge") } } - + public var gt: GraphQLID? { get { return graphQLMap["gt"] as! GraphQLID? @@ -892,7 +900,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "gt") } } - + public var contains: GraphQLID? { get { return graphQLMap["contains"] as! GraphQLID? @@ -901,7 +909,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "contains") } } - + public var notContains: GraphQLID? { get { return graphQLMap["notContains"] as! GraphQLID? @@ -910,7 +918,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "notContains") } } - + public var between: [GraphQLID?]? { get { return graphQLMap["between"] as! [GraphQLID?]? @@ -919,7 +927,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "between") } } - + public var beginsWith: GraphQLID? { get { return graphQLMap["beginsWith"] as! GraphQLID? @@ -928,7 +936,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "beginsWith") } } - + public var attributeExists: Bool? { get { return graphQLMap["attributeExists"] as! Bool? @@ -937,7 +945,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeExists") } } - + public var attributeType: ModelAttributeTypes? { get { return graphQLMap["attributeType"] as! ModelAttributeTypes? @@ -946,7 +954,7 @@ public struct APISwift { graphQLMap.updateValue(newValue, forKey: "attributeType") } } - + public var size: ModelSizeInput? { get { return graphQLMap["size"] as! ModelSizeInput? @@ -956,40 +964,40 @@ public struct APISwift { } } } - + public final class CreateTodoMutation: GraphQLMutation { public static let operationString = "mutation CreateTodo($input: CreateTodoInput!, $condition: ModelTodoConditionInput) {\n createTodo(input: $input, condition: $condition) {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public var input: CreateTodoInput public var condition: ModelTodoConditionInput? - + public init(input: CreateTodoInput, condition: ModelTodoConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("createTodo", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(CreateTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(createTodo: CreateTodo? = nil) { - self.init(snapshot: ["__typename": "Mutation", "createTodo": createTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "createTodo": createTodo.flatMap(\.snapshot)]) } - + public var createTodo: CreateTodo? { get { return (snapshot["createTodo"] as? Snapshot).flatMap { CreateTodo(snapshot: $0) } @@ -998,10 +1006,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "createTodo") } } - + public struct CreateTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1010,17 +1018,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1029,7 +1037,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1038,7 +1046,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1047,7 +1055,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1056,7 +1064,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1065,7 +1073,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1077,40 +1085,40 @@ public struct APISwift { } } } - + public final class UpdateTodoMutation: GraphQLMutation { public static let operationString = "mutation UpdateTodo($input: UpdateTodoInput!, $condition: ModelTodoConditionInput) {\n updateTodo(input: $input, condition: $condition) {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public var input: UpdateTodoInput public var condition: ModelTodoConditionInput? - + public init(input: UpdateTodoInput, condition: ModelTodoConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("updateTodo", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(UpdateTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(updateTodo: UpdateTodo? = nil) { - self.init(snapshot: ["__typename": "Mutation", "updateTodo": updateTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "updateTodo": updateTodo.flatMap(\.snapshot)]) } - + public var updateTodo: UpdateTodo? { get { return (snapshot["updateTodo"] as? Snapshot).flatMap { UpdateTodo(snapshot: $0) } @@ -1119,10 +1127,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "updateTodo") } } - + public struct UpdateTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1131,17 +1139,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1150,7 +1158,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1159,7 +1167,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1168,7 +1176,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1177,7 +1185,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1186,7 +1194,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1198,40 +1206,40 @@ public struct APISwift { } } } - + public final class DeleteTodoMutation: GraphQLMutation { public static let operationString = "mutation DeleteTodo($input: DeleteTodoInput!, $condition: ModelTodoConditionInput) {\n deleteTodo(input: $input, condition: $condition) {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public var input: DeleteTodoInput public var condition: ModelTodoConditionInput? - + public init(input: DeleteTodoInput, condition: ModelTodoConditionInput? = nil) { self.input = input self.condition = condition } - + public var variables: GraphQLMap? { return ["input": input, "condition": condition] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Mutation"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("deleteTodo", arguments: ["input": GraphQLVariable("input"), "condition": GraphQLVariable("condition")], type: .object(DeleteTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(deleteTodo: DeleteTodo? = nil) { - self.init(snapshot: ["__typename": "Mutation", "deleteTodo": deleteTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Mutation", "deleteTodo": deleteTodo.flatMap(\.snapshot)]) } - + public var deleteTodo: DeleteTodo? { get { return (snapshot["deleteTodo"] as? Snapshot).flatMap { DeleteTodo(snapshot: $0) } @@ -1240,10 +1248,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "deleteTodo") } } - + public struct DeleteTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1252,17 +1260,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1271,7 +1279,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1280,7 +1288,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1289,7 +1297,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1298,7 +1306,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1307,7 +1315,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1319,38 +1327,38 @@ public struct APISwift { } } } - + public final class GetTodoQuery: GraphQLQuery { public static let operationString = "query GetTodo($id: ID!) {\n getTodo(id: $id) {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public var id: GraphQLID - + public init(id: GraphQLID) { self.id = id } - + public var variables: GraphQLMap? { return ["id": id] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("getTodo", arguments: ["id": GraphQLVariable("id")], type: .object(GetTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(getTodo: GetTodo? = nil) { - self.init(snapshot: ["__typename": "Query", "getTodo": getTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "getTodo": getTodo.flatMap(\.snapshot)]) } - + public var getTodo: GetTodo? { get { return (snapshot["getTodo"] as? Snapshot).flatMap { GetTodo(snapshot: $0) } @@ -1359,10 +1367,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "getTodo") } } - + public struct GetTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1371,17 +1379,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1390,7 +1398,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1399,7 +1407,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1408,7 +1416,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1417,7 +1425,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1426,7 +1434,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1438,42 +1446,42 @@ public struct APISwift { } } } - + public final class ListTodosQuery: GraphQLQuery { public static let operationString = "query ListTodos($filter: ModelTodoFilterInput, $limit: Int, $nextToken: String) {\n listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {\n __typename\n items {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n nextToken\n }\n}" - + public var filter: ModelTodoFilterInput? public var limit: Int? public var nextToken: String? - + public init(filter: ModelTodoFilterInput? = nil, limit: Int? = nil, nextToken: String? = nil) { self.filter = filter self.limit = limit self.nextToken = nextToken } - + public var variables: GraphQLMap? { return ["filter": filter, "limit": limit, "nextToken": nextToken] } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("listTodos", arguments: ["filter": GraphQLVariable("filter"), "limit": GraphQLVariable("limit"), "nextToken": GraphQLVariable("nextToken")], type: .object(ListTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(listTodos: ListTodo? = nil) { - self.init(snapshot: ["__typename": "Query", "listTodos": listTodos.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Query", "listTodos": listTodos.flatMap(\.snapshot)]) } - + public var listTodos: ListTodo? { get { return (snapshot["listTodos"] as? Snapshot).flatMap { ListTodo(snapshot: $0) } @@ -1482,26 +1490,26 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "listTodos") } } - + public struct ListTodo: GraphQLSelectionSet { public static let possibleTypes = ["ModelTodoConnection"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("items", type: .nonNull(.list(.object(Item.selections)))), GraphQLField("nextToken", type: .scalar(String.self)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(items: [Item?], nextToken: String? = nil) { - self.init(snapshot: ["__typename": "ModelTodoConnection", "items": items.map { $0.flatMap { $0.snapshot } }, "nextToken": nextToken]) + self.init(snapshot: ["__typename": "ModelTodoConnection", "items": items.map { $0.flatMap(\.snapshot) }, "nextToken": nextToken]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1510,16 +1518,16 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var items: [Item?] { get { return (snapshot["items"] as! [Snapshot?]).map { $0.flatMap { Item(snapshot: $0) } } } set { - snapshot.updateValue(newValue.map { $0.flatMap { $0.snapshot } }, forKey: "items") + snapshot.updateValue(newValue.map { $0.flatMap(\.snapshot) }, forKey: "items") } } - + public var nextToken: String? { get { return snapshot["nextToken"] as? String @@ -1528,10 +1536,10 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "nextToken") } } - + public struct Item: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1540,17 +1548,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1559,7 +1567,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1568,7 +1576,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1577,7 +1585,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1586,7 +1594,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1595,7 +1603,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1608,31 +1616,31 @@ public struct APISwift { } } } - + public final class OnCreateTodoSubscription: GraphQLSubscription { public static let operationString = "subscription OnCreateTodo {\n onCreateTodo {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onCreateTodo", type: .object(OnCreateTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onCreateTodo: OnCreateTodo? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onCreateTodo": onCreateTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onCreateTodo": onCreateTodo.flatMap(\.snapshot)]) } - + public var onCreateTodo: OnCreateTodo? { get { return (snapshot["onCreateTodo"] as? Snapshot).flatMap { OnCreateTodo(snapshot: $0) } @@ -1641,10 +1649,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onCreateTodo") } } - + public struct OnCreateTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1653,17 +1661,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1672,7 +1680,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1681,7 +1689,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1690,7 +1698,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1699,7 +1707,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1708,7 +1716,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1720,31 +1728,31 @@ public struct APISwift { } } } - + public final class OnUpdateTodoSubscription: GraphQLSubscription { public static let operationString = "subscription OnUpdateTodo {\n onUpdateTodo {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onUpdateTodo", type: .object(OnUpdateTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onUpdateTodo: OnUpdateTodo? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onUpdateTodo": onUpdateTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onUpdateTodo": onUpdateTodo.flatMap(\.snapshot)]) } - + public var onUpdateTodo: OnUpdateTodo? { get { return (snapshot["onUpdateTodo"] as? Snapshot).flatMap { OnUpdateTodo(snapshot: $0) } @@ -1753,10 +1761,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onUpdateTodo") } } - + public struct OnUpdateTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1765,17 +1773,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1784,7 +1792,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1793,7 +1801,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1802,7 +1810,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1811,7 +1819,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1820,7 +1828,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String @@ -1832,31 +1840,31 @@ public struct APISwift { } } } - + public final class OnDeleteTodoSubscription: GraphQLSubscription { public static let operationString = "subscription OnDeleteTodo {\n onDeleteTodo {\n __typename\n id\n name\n description\n createdAt\n updatedAt\n }\n}" - + public init() { } - + public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Subscription"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("onDeleteTodo", type: .object(OnDeleteTodo.selections)), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(onDeleteTodo: OnDeleteTodo? = nil) { - self.init(snapshot: ["__typename": "Subscription", "onDeleteTodo": onDeleteTodo.flatMap { $0.snapshot }]) + self.init(snapshot: ["__typename": "Subscription", "onDeleteTodo": onDeleteTodo.flatMap(\.snapshot)]) } - + public var onDeleteTodo: OnDeleteTodo? { get { return (snapshot["onDeleteTodo"] as? Snapshot).flatMap { OnDeleteTodo(snapshot: $0) } @@ -1865,10 +1873,10 @@ public struct APISwift { snapshot.updateValue(newValue?.snapshot, forKey: "onDeleteTodo") } } - + public struct OnDeleteTodo: GraphQLSelectionSet { public static let possibleTypes = ["Todo"] - + public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), @@ -1877,17 +1885,17 @@ public struct APISwift { GraphQLField("createdAt", type: .nonNull(.scalar(String.self))), GraphQLField("updatedAt", type: .nonNull(.scalar(String.self))), ] - + public var snapshot: Snapshot - + public init(snapshot: Snapshot) { self.snapshot = snapshot } - + public init(id: GraphQLID, name: String, description: String? = nil, createdAt: String, updatedAt: String) { self.init(snapshot: ["__typename": "Todo", "id": id, "name": name, "description": description, "createdAt": createdAt, "updatedAt": updatedAt]) } - + public var __typename: String { get { return snapshot["__typename"]! as! String @@ -1896,7 +1904,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "__typename") } } - + public var id: GraphQLID { get { return snapshot["id"]! as! GraphQLID @@ -1905,7 +1913,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "id") } } - + public var name: String { get { return snapshot["name"]! as! String @@ -1914,7 +1922,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "name") } } - + public var description: String? { get { return snapshot["description"] as? String @@ -1923,7 +1931,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "description") } } - + public var createdAt: String { get { return snapshot["createdAt"]! as! String @@ -1932,7 +1940,7 @@ public struct APISwift { snapshot.updateValue(newValue, forKey: "createdAt") } } - + public var updatedAt: String { get { return snapshot["updatedAt"]! as! String diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/Base/AsyncExpectation.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/Base/AsyncExpectation.swift index 9b3bd39a7a..6403ffdab0 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/Base/AsyncExpectation.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/Base/AsyncExpectation.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation import XCTest -import Amplify public actor AsyncExpectation { enum State { @@ -28,10 +28,12 @@ public actor AsyncExpectation { state == .fulfilled } - public init(description: String, - isInverted: Bool = false, - expectedFulfillmentCount: Int = 1) { - expectationDescription = description + public init( + description: String, + isInverted: Bool = false, + expectedFulfillmentCount: Int = 1 + ) { + self.expectationDescription = description self.isInverted = isInverted self.expectedFulfillmentCount = expectedFulfillmentCount } @@ -59,7 +61,7 @@ public actor AsyncExpectation { } } - internal nonisolated func wait() async throws { + nonisolated func wait() async throws { try await withTaskCancellationHandler(handler: { Task { await cancel() @@ -69,8 +71,10 @@ public actor AsyncExpectation { }) } - internal func timeOut(file: StaticString = #filePath, - line: UInt = #line) async { + func timeOut( + file: StaticString = #filePath, + line: UInt = #line + ) async { if isInverted { state = .timedOut } else if state != .fulfilled { @@ -103,7 +107,7 @@ public actor AsyncExpectation { } -extension XCTestCase { +public extension XCTestCase { /// Creates a new async expectation with an associated description. /// @@ -118,12 +122,16 @@ extension XCTestCase { /// - description: A string to display in the test log for this expectation, to help diagnose failures. /// - isInverted: Indicates that the expectation is not intended to happen. /// - expectedFulfillmentCount: The number of times fulfill() must be called before the expectation is completely fulfilled. (default = 1) - public func expectation(description: String, - isInverted: Bool = false, - expectedFulfillmentCount: Int = 1) -> AsyncExpectation { - expectation(description: description, - isInverted: isInverted, - expectedFulfillmentCount: expectedFulfillmentCount) + func expectation( + description: String, + isInverted: Bool = false, + expectedFulfillmentCount: Int = 1 + ) -> AsyncExpectation { + expectation( + description: description, + isInverted: isInverted, + expectedFulfillmentCount: expectedFulfillmentCount + ) } /// Waits for the test to fulfill a set of expectations within a specified time. @@ -131,33 +139,43 @@ extension XCTestCase { /// - expectations: An array of async expectations that must be fulfilled. /// - timeout: The number of seconds within which all expectations must be fulfilled. @MainActor - public func waitForExpectations(_ expectations: [AsyncExpectation], - timeout: Double = 1.0, - file: StaticString = #filePath, - line: UInt = #line) async { - await AsyncTesting.waitForExpectations(expectations, - timeout: timeout, - file: file, - line: line) + func waitForExpectations( + _ expectations: [AsyncExpectation], + timeout: Double = 1.0, + file: StaticString = #filePath, + line: UInt = #line + ) async { + await AsyncTesting.waitForExpectations( + expectations, + timeout: timeout, + file: file, + line: line + ) } } public enum AsyncTesting { - public static func expectation(description: String, - isInverted: Bool = false, - expectedFulfillmentCount: Int = 1) -> AsyncExpectation { - expectation(description: description, - isInverted: isInverted, - expectedFulfillmentCount: expectedFulfillmentCount) + public static func expectation( + description: String, + isInverted: Bool = false, + expectedFulfillmentCount: Int = 1 + ) -> AsyncExpectation { + expectation( + description: description, + isInverted: isInverted, + expectedFulfillmentCount: expectedFulfillmentCount + ) } @MainActor - public static func waitForExpectations(_ expectations: [AsyncExpectation], - timeout: Double = 1.0, - file: StaticString = #filePath, - line: UInt = #line) async { + public static func waitForExpectations( + _ expectations: [AsyncExpectation], + timeout: Double = 1.0, + file: StaticString = #filePath, + line: UInt = #line + ) async { guard !expectations.isEmpty else { return } // check if all expectations are already satisfied and skip sleeping diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/GraphQLWithUserPoolIntegrationAPISwiftTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/GraphQLWithUserPoolIntegrationAPISwiftTests.swift index 8ab5a60fcd..4d416a3045 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/GraphQLWithUserPoolIntegrationAPISwiftTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/GraphQLWithUserPoolIntegrationAPISwiftTests.swift @@ -5,29 +5,33 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Foundation import AWSAPIPlugin import AWSCognitoAuthPlugin +import Foundation +import XCTest @testable import Amplify @testable import APIHostApp extension GraphQLWithUserPoolIntegrationTests { - + func createTodoAPISwift() async throws { let expectedId = UUID().uuidString let expectedName = "testCreateTodoMutationName" let expectedDescription = "testCreateTodoMutationDescription" - let input = APISwift.CreateTodoInput(id: expectedId, - name: expectedName, - description: expectedDescription) + let input = APISwift.CreateTodoInput( + id: expectedId, + name: expectedName, + description: expectedDescription + ) let mutation = APISwift.CreateTodoMutation(input: input) - let request = GraphQLRequest(document: APISwift.CreateTodoMutation.operationString, - variables: mutation.variables?.jsonObject, - responseType: APISwift.CreateTodoMutation.Data.self) - - + let request = GraphQLRequest( + document: APISwift.CreateTodoMutation.operationString, + variables: mutation.variables?.jsonObject, + responseType: APISwift.CreateTodoMutation.Data.self + ) + + let event = try await Amplify.API.mutate(request: request) switch event { case .success(let data): @@ -45,7 +49,7 @@ extension GraphQLWithUserPoolIntegrationTests { XCTFail("Unexpected .failed event: \(error)") } } - + func testCreateTodoMutationWithUserPoolWithSignedInUserAPISwift() async throws { try await createAuthenticatedUser() try await createTodoAPISwift() diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/GraphQLWithUserPoolIntegrationTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/GraphQLWithUserPoolIntegrationTests.swift index b69d85b123..21788f0206 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/GraphQLWithUserPoolIntegrationTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/GraphQLWithUserPoolIntegrationTests.swift @@ -5,20 +5,21 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Foundation import AWSAPIPlugin import AWSCognitoAuthPlugin +import Foundation +import XCTest @testable import Amplify @testable import APIHostApp + // swiftlint:disable type_body_length class GraphQLWithUserPoolIntegrationTests: XCTestCase { let amplifyConfigurationFile = "testconfiguration/GraphQLWithUserPoolIntegrationTests-amplifyconfiguration" let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - + override func setUp() { do { try Amplify.add(plugin: AWSAPIPlugin()) @@ -35,7 +36,7 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { await signOut() await Amplify.reset() } - + /// Given: A CreateTodo mutation request, and user signed in, graphql has userpools as auth mode. /// When: Call mutate API /// Then: The operation completes successfully with no errors and todo in response @@ -44,11 +45,15 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { let expectedId = UUID().uuidString let expectedName = "testCreateTodoMutationName" let expectedDescription = "testCreateTodoMutationDescription" - let request = GraphQLRequest(document: CreateTodoMutation.document, - variables: CreateTodoMutation.variables(id: expectedId, - name: expectedName, - description: expectedDescription), - responseType: CreateTodoMutation.Data.self) + let request = GraphQLRequest( + document: CreateTodoMutation.document, + variables: CreateTodoMutation.variables( + id: expectedId, + name: expectedName, + description: expectedDescription + ), + responseType: CreateTodoMutation.Data.self + ) let graphQLResponse = try await Amplify.API.mutate(request: request) guard case let .success(data) = graphQLResponse else { XCTFail("Missing successful response") @@ -72,11 +77,15 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { let expectedId = UUID().uuidString let expectedName = "testCreateTodoMutationName" let expectedDescription = "testCreateTodoMutationDescription" - let request = GraphQLRequest(document: CreateTodoMutation.document, - variables: CreateTodoMutation.variables(id: expectedId, - name: expectedName, - description: expectedDescription), - responseType: CreateTodoMutation.Data.self) + let request = GraphQLRequest( + document: CreateTodoMutation.document, + variables: CreateTodoMutation.variables( + id: expectedId, + name: expectedName, + description: expectedDescription + ), + responseType: CreateTodoMutation.Data.self + ) do { let graphQLResponse = try await Amplify.API.mutate(request: request) XCTFail("Unexpected .completed event: \(graphQLResponse)") @@ -93,24 +102,28 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { let expectedId = UUID().uuidString let expectedName = "testCreateTodoMutationName" let expectedDescription = "testCreateTodoMutationDescription" - let request = GraphQLRequest(document: CreateTodoMutation.document, - variables: CreateTodoMutation.variables(id: expectedId, - name: expectedName, - description: expectedDescription), - responseType: Todo?.self, - decodePath: CreateTodoMutation.decodePath) + let request = GraphQLRequest( + document: CreateTodoMutation.document, + variables: CreateTodoMutation.variables( + id: expectedId, + name: expectedName, + description: expectedDescription + ), + responseType: Todo?.self, + decodePath: CreateTodoMutation.decodePath + ) let graphQLResponse = try await Amplify.API.mutate(request: request) guard case let .success(data) = graphQLResponse else { XCTFail("Missing successful response") return } - + guard let todo = data else { XCTFail("Missing Todo") return } - + XCTAssertEqual(todo.id, expectedId) XCTAssertEqual(todo.name, expectedName) XCTAssertEqual(todo.description, expectedDescription) @@ -125,12 +138,16 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { let uuid = UUID().uuidString // create a Todo mutation with a missing/invalid "name" variable value - let request = GraphQLRequest(document: CreateTodoMutation.document, - variables: CreateTodoMutation.variables(id: uuid, - name: nil, - description: nil), - responseType: Todo?.self, - decodePath: CreateTodoMutation.decodePath) + let request = GraphQLRequest( + document: CreateTodoMutation.document, + variables: CreateTodoMutation.variables( + id: uuid, + name: nil, + description: nil + ), + responseType: Todo?.self, + decodePath: CreateTodoMutation.decodePath + ) let graphQLResponse = try await Amplify.API.mutate(request: request) guard case let .failure(graphQLResponseError) = graphQLResponse else { XCTFail("Unexpected response success \(graphQLResponse)") @@ -140,8 +157,10 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { XCTFail("Missing errors") return } - XCTAssertEqual("Variable 'input' has coerced Null value for NonNull type 'String!'", - firstError.message) + XCTAssertEqual( + "Variable 'input' has coerced Null value for NonNull type 'String!'", + firstError.message + ) } /// Given: A CreateTodo mutation request with incorrect repsonse type (ListTodo instead of Todo) @@ -152,17 +171,21 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { let expectedId = UUID().uuidString let expectedName = "testCreateTodoMutationName" let expectedDescription = "testCreateTodoMutationDescription" - let request = GraphQLRequest(document: CreateTodoMutation.document, - variables: CreateTodoMutation.variables(id: expectedId, - name: expectedName, - description: expectedDescription), - responseType: MalformedCreateTodoData.self) + let request = GraphQLRequest( + document: CreateTodoMutation.document, + variables: CreateTodoMutation.variables( + id: expectedId, + name: expectedName, + description: expectedDescription + ), + responseType: MalformedCreateTodoData.self + ) let graphQLResponse = try await Amplify.API.mutate(request: request) guard case let .failure(graphQLResponseError) = graphQLResponse else { XCTFail("Unexpected event: \(graphQLResponse)") return } - + guard case .transformationError = graphQLResponseError else { XCTFail("Should be transformation error") return @@ -183,9 +206,11 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { return } - let request = GraphQLRequest(document: GetTodoQuery.document, - variables: GetTodoQuery.variables(id: todo.id), - responseType: GetTodoQuery.Data.self) + let request = GraphQLRequest( + document: GetTodoQuery.document, + variables: GetTodoQuery.variables(id: todo.id), + responseType: GetTodoQuery.Data.self + ) let graphQLResponse = try await Amplify.API.query(request: request) guard case let .success(data) = graphQLResponse else { XCTFail("Missing successful response") @@ -195,7 +220,7 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { XCTFail("Missing Todo") return } - + XCTAssertEqual(todo.id, todo.id) XCTAssertEqual(todo.name, name) XCTAssertEqual(todo.description, description) @@ -208,9 +233,11 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { func testGetTodoQueryForMissingTodo() async throws { try await createAuthenticatedUser() let uuid = UUID().uuidString - let request = GraphQLRequest(document: GetTodoQuery.document, - variables: GetTodoQuery.variables(id: uuid), - responseType: GetTodoQuery.Data.self) + let request = GraphQLRequest( + document: GetTodoQuery.document, + variables: GetTodoQuery.variables(id: uuid), + responseType: GetTodoQuery.Data.self + ) let graphQLResponse = try await Amplify.API.query(request: request) guard case let .success(data) = graphQLResponse else { XCTFail("Missing successful response") @@ -234,11 +261,15 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { } let expectedName = name + "Updated" let expectedDescription = description + "Updated" - let request = GraphQLRequest(document: UpdateTodoMutation.document, - variables: UpdateTodoMutation.variables(id: todo.id, - name: expectedName, - description: expectedDescription), - responseType: UpdateTodoMutation.Data.self) + let request = GraphQLRequest( + document: UpdateTodoMutation.document, + variables: UpdateTodoMutation.variables( + id: todo.id, + name: expectedName, + description: expectedDescription + ), + responseType: UpdateTodoMutation.Data.self + ) let graphQLResponse = try await Amplify.API.mutate(request: request) guard case let .success(data) = graphQLResponse else { XCTFail("Missing successful response") @@ -268,9 +299,11 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { return } - let request = GraphQLRequest(document: DeleteTodoMutation.document, - variables: DeleteTodoMutation.variables(id: todo.id), - responseType: DeleteTodoMutation.Data.self) + let request = GraphQLRequest( + document: DeleteTodoMutation.document, + variables: DeleteTodoMutation.variables(id: todo.id), + responseType: DeleteTodoMutation.Data.self + ) let graphQLResponse = try await Amplify.API.mutate(request: request) guard case let .success(data) = graphQLResponse else { XCTFail("Missing successful response") @@ -280,23 +313,25 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { XCTFail("Missing deleteTodo") return } - + XCTAssertEqual(deleteTodo.id, todo.id) XCTAssertEqual(deleteTodo.name, name) XCTAssertEqual(deleteTodo.description, description) XCTAssertEqual(deleteTodo.typename, String(describing: Todo.self)) - let getTodoRequest = GraphQLRequest(document: GetTodoQuery.document, - variables: GetTodoQuery.variables(id: todo.id), - responseType: GetTodoQuery.Data.self) + let getTodoRequest = GraphQLRequest( + document: GetTodoQuery.document, + variables: GetTodoQuery.variables(id: todo.id), + responseType: GetTodoQuery.Data.self + ) let graphQLResponse2 = try await Amplify.API.query(request: getTodoRequest) XCTAssertNotNil(graphQLResponse2) - + guard case let .success(data) = graphQLResponse2 else { XCTFail("Missing successful response") return } - + XCTAssertNil(data.getTodo) } @@ -314,9 +349,11 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { return } - let request = GraphQLRequest(document: ListTodosQuery.document, - variables: nil, - responseType: ListTodosQuery.Data.self) + let request = GraphQLRequest( + document: ListTodosQuery.document, + variables: nil, + responseType: ListTodosQuery.Data.self + ) let graphQLResponse = try await Amplify.API.query(request: request) switch graphQLResponse { case .success(let data): @@ -338,9 +375,11 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { let uuid = UUID().uuidString let filter = ["id": ["eq": uuid]] let variables = ListTodosQuery.variables(filter: filter, limit: 10) - let request = GraphQLRequest(document: ListTodosQuery.document, - variables: variables, - responseType: ListTodosQuery.Data.self) + let request = GraphQLRequest( + document: ListTodosQuery.document, + variables: variables, + responseType: ListTodosQuery.Data.self + ) let graphQLResponse = try await Amplify.API.query(request: request) guard case let .success(data) = graphQLResponse else { XCTFail("Missing successful response") @@ -360,9 +399,11 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { let connectedInvoked = expectation(description: "Connection established") connectedInvoked.isInverted = true let completedInvoked = expectation(description: "Completed invoked") - let request = GraphQLRequest(document: OnCreateTodoSubscription.document, - variables: nil, - responseType: OnCreateTodoSubscription.Data.self) + let request = GraphQLRequest( + document: OnCreateTodoSubscription.document, + variables: nil, + responseType: OnCreateTodoSubscription.Data.self + ) let subscriptions = Amplify.API.subscribe(request: request) Task { @@ -401,9 +442,11 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { let completedInvoked = expectation(description: "Completed invoked") let progressInvoked = expectation(description: "progress invoked") progressInvoked.expectedFulfillmentCount = 2 - let request = GraphQLRequest(document: OnCreateTodoSubscription.document, - variables: nil, - responseType: OnCreateTodoSubscription.Data.self) + let request = GraphQLRequest( + document: OnCreateTodoSubscription.document, + variables: nil, + responseType: OnCreateTodoSubscription.Data.self + ) let subscriptions = Amplify.API.subscribe(request: request) Task { for try await subscription in subscriptions { @@ -421,7 +464,7 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { progressInvoked.fulfill() } } - + completedInvoked.fulfill() } await fulfillment(of: [connectedInvoked], timeout: TestCommonConstants.networkTimeout) @@ -457,9 +500,11 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { let progressInvoked = expectation(description: "progress invoked") progressInvoked.expectedFulfillmentCount = 2 - let request = GraphQLRequest(document: OnUpdateTodoSubscription.document, - variables: nil, - responseType: OnUpdateTodoSubscription.Data.self) + let request = GraphQLRequest( + document: OnUpdateTodoSubscription.document, + variables: nil, + responseType: OnUpdateTodoSubscription.Data.self + ) let subscriptions = Amplify.API.subscribe(request: request) Task { for try await subscription in subscriptions { @@ -514,9 +559,11 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { let disconnectedInvoked = expectation(description: "Connection disconnected") let completedInvoked = expectation(description: "Completed invoked") let progressInvoked = expectation(description: "progress invoked") - let request = GraphQLRequest(document: OnDeleteTodoSubscription.document, - variables: nil, - responseType: OnDeleteTodoSubscription.Data.self) + let request = GraphQLRequest( + document: OnDeleteTodoSubscription.document, + variables: nil, + responseType: OnDeleteTodoSubscription.Data.self + ) let subscriptions = Amplify.API.subscribe(request: request) Task { for try await subscription in subscriptions { @@ -553,25 +600,27 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { } await fulfillment(of: [progressInvoked], timeout: TestCommonConstants.networkTimeout) - + subscriptions.cancel() await fulfillment(of: [disconnectedInvoked, completedInvoked], timeout: TestCommonConstants.networkTimeout) } func testCreateMultipleSubscriptions() async throws { try await createAuthenticatedUser() - let subscriptions = [await createTodoSubscription(), - await createTodoSubscription(), - await createTodoSubscription(), - await createTodoSubscription(), - await createTodoSubscription()] + let subscriptions = await [ + createTodoSubscription(), + createTodoSubscription(), + createTodoSubscription(), + createTodoSubscription(), + createTodoSubscription() + ] for subscription in subscriptions { subscription.cancel() } } - + // MARK: - Auth Helpers - + func createAuthenticatedUser() async throws { if try await isSignedIn() { await signOut() @@ -579,12 +628,12 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { try await signUp() try await signIn() } - + func isSignedIn() async throws -> Bool { let authSession = try await Amplify.Auth.fetchAuthSession() return authSession.isSignedIn } - + func signUp() async throws { let signUpResult = try await Amplify.Auth.signUp(username: username, password: password) guard signUpResult.isSignUpComplete else { @@ -594,26 +643,32 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { } func signIn() async throws { - let signInResult = try await Amplify.Auth.signIn(username: username, - password: password) + let signInResult = try await Amplify.Auth.signIn( + username: username, + password: password + ) guard signInResult.isSignedIn else { XCTFail("Sign in successful but not complete") return } } - + func signOut() async { _ = await Amplify.Auth.signOut() } // MARK: - Helpers - + func createTodo(id: String, name: String, description: String) async throws -> Todo? { - let request = GraphQLRequest(document: CreateTodoMutation.document, - variables: CreateTodoMutation.variables(id: id, - name: name, - description: description), - responseType: CreateTodoMutation.Data.self) + let request = GraphQLRequest( + document: CreateTodoMutation.document, + variables: CreateTodoMutation.variables( + id: id, + name: name, + description: description + ), + responseType: CreateTodoMutation.Data.self + ) let graphQLResponse = try await Amplify.API.mutate(request: request) switch graphQLResponse { case .success(let data): @@ -624,11 +679,15 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { } func updateTodo(id: String, name: String, description: String) async throws -> Todo? { - let request = GraphQLRequest(document: UpdateTodoMutation.document, - variables: UpdateTodoMutation.variables(id: id, - name: name, - description: description), - responseType: UpdateTodoMutation.Data.self) + let request = GraphQLRequest( + document: UpdateTodoMutation.document, + variables: UpdateTodoMutation.variables( + id: id, + name: name, + description: description + ), + responseType: UpdateTodoMutation.Data.self + ) let graphQLResponse = try await Amplify.API.mutate(request: request) switch graphQLResponse { case .success(let data): @@ -639,9 +698,11 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { } func deleteTodo(id: String) async throws -> Todo? { - let request = GraphQLRequest(document: DeleteTodoMutation.document, - variables: DeleteTodoMutation.variables(id: id), - responseType: DeleteTodoMutation.Data.self) + let request = GraphQLRequest( + document: DeleteTodoMutation.document, + variables: DeleteTodoMutation.variables(id: id), + responseType: DeleteTodoMutation.Data.self + ) let graphQLResponse = try await Amplify.API.mutate(request: request) switch graphQLResponse { case .success(let data): @@ -653,9 +714,11 @@ class GraphQLWithUserPoolIntegrationTests: XCTestCase { func createTodoSubscription() async -> AmplifyAsyncThrowingSequence> { let connectedInvoked = expectation(description: "Connection established") - let request = GraphQLRequest(document: OnCreateTodoSubscription.document, - variables: nil, - responseType: OnCreateTodoSubscription.Data.self) + let request = GraphQLRequest( + document: OnCreateTodoSubscription.document, + variables: nil, + responseType: OnCreateTodoSubscription.Data.self + ) let subscriptions = Amplify.API.subscribe(request: request) Task { for try await subscription in subscriptions { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/Todo.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/Todo.swift index ab57c527ec..72d7161d61 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/Todo.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginGraphQLUserPoolTests/Todo.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct Todo: Decodable { let typename: String @@ -48,15 +48,15 @@ class CreateTodoMutation { static func variables(id: String? = nil, name: String?, description: String? = nil) -> [String: Any] { var input: [String: Any] = [:] - if let id = id { + if let id { input.updateValue(id, forKey: "id") } - if let name = name { + if let name { input.updateValue(name, forKey: "name") } - if let description = description { + if let description { input.updateValue(description, forKey: "description") } @@ -92,10 +92,10 @@ class UpdateTodoMutation { static func variables(id: String, name: String? = nil, description: String? = nil) -> [String: Any] { var input: [String: Any] = [:] input.updateValue(id, forKey: "id") - if let name = name { + if let name { input.updateValue(name, forKey: "name") } - if let description = description { + if let description { input.updateValue(description, forKey: "description") } return ["input": input] @@ -119,7 +119,7 @@ class DeleteTodoMutation { static func variables(id: String?) -> [String: Any] { var input: [String: Any] = [:] - if let id = id { + if let id { input.updateValue(id, forKey: "id") } @@ -166,20 +166,22 @@ class ListTodosQuery { }\n} """ - static func variables(filter: [String: Any]? = nil, - limit: Int? = nil, - nextToken: String? = nil) -> [String: Any] { + static func variables( + filter: [String: Any]? = nil, + limit: Int? = nil, + nextToken: String? = nil + ) -> [String: Any] { var input: [String: Any] = [:] - if let filter = filter { + if let filter { input.updateValue(filter, forKey: "filter") } - if let limit = limit { + if let limit { input.updateValue(limit, forKey: "limit") } - if let nextToken = nextToken { + if let nextToken { input.updateValue(nextToken, forKey: "nextToken") } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginIGraphQLAuthDirectiveTests/Base/AuthSignInHelper.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginIGraphQLAuthDirectiveTests/Base/AuthSignInHelper.swift index 98e6d9556a..d091aa412a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginIGraphQLAuthDirectiveTests/Base/AuthSignInHelper.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginIGraphQLAuthDirectiveTests/Base/AuthSignInHelper.swift @@ -9,7 +9,7 @@ import Amplify public typealias CompletionType = (Bool, AuthError?) -> Void -public struct AuthSignInHelper { +public enum AuthSignInHelper { public static func signUpUser(username: String, password: String, email: String) async throws -> AuthSignUpResult { let options = AuthSignUpRequest.Options(userAttributes: [AuthUserAttribute(.email, value: email)]) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginIGraphQLAuthDirectiveTests/GraphQLAuthDirectiveIntegrationTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginIGraphQLAuthDirectiveTests/GraphQLAuthDirectiveIntegrationTests.swift index d3d73f8061..cf44c21c4d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginIGraphQLAuthDirectiveTests/GraphQLAuthDirectiveIntegrationTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginIGraphQLAuthDirectiveTests/GraphQLAuthDirectiveIntegrationTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import AWSPluginsCore import AWSAPIPlugin import AWSCognitoAuthPlugin +import AWSPluginsCore +import XCTest @testable import Amplify @testable import APIHostApp @@ -18,11 +18,11 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { let username: String let password: String } - + let amplifyConfigurationFile = "testconfiguration/GraphQLWithUserPoolIntegrationTests-amplifyconfiguration" var user1: User! var user2: User! - + override func setUp() async throws { do { user1 = User(username: "integTest\(UUID().uuidString)", password: "P123@\(UUID().uuidString)") @@ -31,13 +31,17 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { try Amplify.add(plugin: AWSCognitoAuthPlugin()) let amplifyConfig = try TestConfigHelper.retrieveAmplifyConfiguration(forResource: amplifyConfigurationFile) try Amplify.configure(amplifyConfig) - - _ = try await AuthSignInHelper.signUpUser(username: user1.username, - password: user1.password, - email: "\(user1.username)@\(UUID().uuidString).com") - _ = try await AuthSignInHelper.signUpUser(username: user2.username, - password: user2.password, - email: "\(user2.username)@\(UUID().uuidString).com") + + _ = try await AuthSignInHelper.signUpUser( + username: user1.username, + password: user1.password, + email: "\(user1.username)@\(UUID().uuidString).com" + ) + _ = try await AuthSignInHelper.signUpUser( + username: user2.username, + password: user2.password, + email: "\(user2.username)@\(UUID().uuidString).com" + ) ModelRegistry.register(modelType: SocialNote.self) } catch { XCTFail("Error during setup: \(error)") @@ -46,12 +50,12 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { await signOut() } } - + override func tearDown() async throws { await signOut() await Amplify.reset() } - + /// Models created with: /// @auth(rules: [ { allow: owner, operations: [create, update, delete] } ]) /// @@ -80,14 +84,15 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { XCTFail("Owner should be able to successfully create a note") return } - + let ownerReadNoteResult = try await queryNote(byId: ownerCreatedNote.model.id) guard case let .success(ownerReadNoteOptional) = ownerReadNoteResult, - let ownerReadNote = ownerReadNoteOptional else { + let ownerReadNote = ownerReadNoteOptional + else { XCTFail("Owner should be able to query for own note") return } - + let ownerUpdateNote = SocialNote(id: ownerReadNote.model.id, content: "owner updated content", owner: nil) let ownerUpdatedNoteResult = try await updateNote(ownerUpdateNote, version: ownerReadNote.syncMetadata.version) guard case let .success(ownerUpdatedNote) = ownerUpdatedNoteResult else { @@ -95,20 +100,22 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { return } await signOut() - + try await signIn(username: user2.username, password: user2.password) let otherReadNoteResult = try await queryNote(byId: id) guard case let .success(otherReadNoteOptional) = otherReadNoteResult, - let otherReadNote = otherReadNoteOptional else { + let otherReadNote = otherReadNoteOptional + else { XCTFail("Others should be able to read the note") return } - + let otherUpdateNote = SocialNote(id: otherReadNote.model.id, content: "other updated content", owner: nil) do { let otherUpdatedNoteResult = try await updateNote(otherUpdateNote, version: otherReadNote.syncMetadata.version) guard case let .failure(graphQLResponseErrorOnUpdate) = otherUpdatedNoteResult, - let appSyncErrorOnUpdate = getAppSyncError(graphQLResponseErrorOnUpdate) else { + let appSyncErrorOnUpdate = getAppSyncError(graphQLResponseErrorOnUpdate) + else { XCTFail("Other should not be able to update owner's note") return } @@ -116,20 +123,20 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { } catch (let error) { XCTFail("Failed with error: \(error)") } - + await signOut() try await signIn(username: user1.username, password: user1.password) do { let result = try await deleteNote(byId: id, version: ownerUpdatedNote.syncMetadata.version) XCTAssertNotNil(result) - } catch(let error) { + } catch (let error) { XCTFail("Owner should be able to delete own note: \(error)") } } catch (let error as APIError) { XCTFail("Failed with error: \(error)") } } - + /// An unauthorized user should not be able to make a mutation /// - Given: An API backend as per README.md with SocialNote schema /// - When: An unauthorized mutation request is made @@ -147,7 +154,7 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { } await fulfillment(of: [failureInvoked], timeout: TestCommonConstants.networkTimeout) } - + /// - Given: An API backend as per README.md with SocialNote schema /// - When: An authrorized syncQuery request is made /// - Then: The request should succeed @@ -162,7 +169,7 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { XCTFail("Failed with error: \(error)") } } - + /// An unauthorized user should not be able to query /// - Given: An API backend as per README.md with SocialNote schema /// - When: An unauthrorized syncQuery request is made @@ -173,14 +180,14 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { do { _ = try await Amplify.API.query(request: request) XCTFail("Should not have completed successfully") - } catch (let error as APIError){ + } catch (let error as APIError) { self.assertNotAuthenticated(error) failureInvoked.fulfill() } - + await fulfillment(of: [failureInvoked], timeout: TestCommonConstants.networkTimeout) } - + /// An authorized user should not subscribe to mutation events /// - Given: An API backend as per README.md with SocialNote schema /// - When: An authorized user sets up subscription to API @@ -189,8 +196,10 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { try await signIn(username: user1.username, password: user1.password) let connectedInvoked = expectation(description: "Connection established") let progressInvoked = expectation(description: "Progress invoked") - let request = GraphQLRequest.subscription(to: SocialNote.self, - subscriptionType: .onCreate) + let request = GraphQLRequest.subscription( + to: SocialNote.self, + subscriptionType: .onCreate + ) let subscription = Amplify.API.subscribe(request: request) Task { do { @@ -213,22 +222,22 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { XCTFail("Unexpected subscription failure: \(error)") } } - + await fulfillment(of: [connectedInvoked], timeout: TestCommonConstants.networkTimeout) - + do { _ = try await createNote(content: "owner created content") } catch (let error) { XCTFail("Owner should be able to successfully create a note: \(error)") } - + await fulfillment(of: [progressInvoked], timeout: TestCommonConstants.networkTimeout) subscription.cancel() } - - + + // MARK: - Helpers - + func signIn(username: String, password: String) async throws { do { let signInResult = try await Amplify.Auth.signIn(username: username, password: password) @@ -240,43 +249,45 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { XCTFail("Failed with signIn error: \(error)") } } - + func signOut() async { _ = await Amplify.Auth.signOut() } - + func isSignedIn() async throws -> Bool { let authSession = try await Amplify.Auth.fetchAuthSession() return authSession.isSignedIn } - + func createNote(_ id: String = UUID().uuidString, content: String) async throws -> GraphQLResponse { let note = SocialNote(id: id, content: content, owner: nil) let request = GraphQLRequest.createMutation(of: note) let mutateResult = try await Amplify.API.mutate(request: request) return mutateResult } - + func updateNote(_ note: SocialNote, version: Int) async throws -> GraphQLResponse { let request = GraphQLRequest.updateMutation(of: note, version: version) let mutateResult = try await Amplify.API.mutate(request: request) return mutateResult } - + func deleteNote(byId id: String, version: Int) async throws -> GraphQLResponse { - let request = GraphQLRequest.deleteMutation(of: SocialNote(id: id, content: ""), - modelSchema: SocialNote.schema, - version: version) + let request = GraphQLRequest.deleteMutation( + of: SocialNote(id: id, content: ""), + modelSchema: SocialNote.schema, + version: version + ) let mutateResult = try await Amplify.API.mutate(request: request) return mutateResult } - + func queryNote(byId id: String) async throws -> GraphQLResponse { let request = GraphQLRequest.query(modelName: SocialNote.modelName, byId: id) let queryResult = try await Amplify.API.query(request: request) return queryResult } - + func syncQuery() async throws -> SyncQueryResult { let syncQueryInvoked = expectation(description: "note was sync queried") var resultOptional: SyncQueryResult? @@ -295,18 +306,19 @@ class GraphQLAuthDirectiveIntegrationTests: XCTestCase { } return result } - + func getAppSyncError(_ graphQLResponseError: GraphQLResponseError) -> AppSyncErrorType? { guard case let .error(errors) = graphQLResponseError, let error = errors.first, let extensions = error.extensions, - case let .string(errorTypeValue) = extensions["errorType"] else { + case let .string(errorTypeValue) = extensions["errorType"] + else { XCTFail("Missing expected `errorType` from error.extensions") return nil } return AppSyncErrorType(errorTypeValue) } - + func assertNotAuthenticated(_ error: APIError) { guard case let .operationError(_, _, underlyingError) = error else { XCTFail("Error should be operationError") diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginIGraphQLAuthDirectiveTests/SocialNote.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginIGraphQLAuthDirectiveTests/SocialNote.swift index 11cfbce7f6..f307e6ee39 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginIGraphQLAuthDirectiveTests/SocialNote.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginIGraphQLAuthDirectiveTests/SocialNote.swift @@ -13,27 +13,29 @@ public struct SocialNote: Model { public var content: String public var owner: String? - public init(id: String = UUID().uuidString, - content: String, - owner: String? = nil) { + public init( + id: String = UUID().uuidString, + content: String, + owner: String? = nil + ) { self.id = id self.content = content self.owner = owner } } -extension SocialNote { +public extension SocialNote { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case owner } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let socialNote = SocialNote.keys model.authRules = [ diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/GraphQLLazyLoadBaseTest.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/GraphQLLazyLoadBaseTest.swift index 219d3d549f..5903c23d16 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/GraphQLLazyLoadBaseTest.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/GraphQLLazyLoadBaseTest.swift @@ -6,59 +6,62 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify @testable import APIHostApp +@testable import AWSAPIPlugin @testable import AWSPluginsCore class GraphQLLazyLoadBaseTest: XCTestCase { - + var amplifyConfig: AmplifyConfiguration! - + override func setUp() { continueAfterFailure = false } - + override func tearDown() async throws { await Amplify.reset() try await Task.sleep(seconds: 1) } - + func setupConfig() { let basePath = "testconfiguration" let baseFileName = "GraphQLLazyLoadTests" let configFile = "\(basePath)/\(baseFileName)-amplifyconfiguration" - + do { amplifyConfig = try TestConfigHelper.retrieveAmplifyConfiguration(forResource: configFile) } catch { XCTFail("Error during setup: \(error)") } } - + func apiEndpointName() throws -> String { guard let apiPlugin = amplifyConfig.api?.plugins["awsAPIPlugin"], - case .object(let value) = apiPlugin else { + case .object(let value) = apiPlugin + else { throw APIError.invalidConfiguration("API endpoint not found.", "Check the provided configuration") } return value.keys.first! } - + /// Setup API with given models /// - Parameter models: DataStore models - func setup(withModels models: AmplifyModelRegistration, - logLevel: LogLevel = .verbose) async { + func setup( + withModels models: AmplifyModelRegistration, + logLevel: LogLevel = .verbose + ) async { do { setupConfig() Amplify.Logging.logLevel = logLevel try Amplify.add(plugin: AWSAPIPlugin(modelRegistration: models)) try Amplify.configure(amplifyConfig) - + } catch { XCTFail("Error during setup: \(error)") } } - + @discardableResult func mutate(_ request: GraphQLRequest) async throws -> M { do { @@ -72,10 +75,10 @@ class GraphQLLazyLoadBaseTest: XCTestCase { } catch { XCTFail("Failed with error \(error)") } - + throw "See XCTFail message" } - + func query(_ request: GraphQLRequest) async throws -> M? { do { let graphQLResponse = try await Amplify.API.query(request: request) @@ -90,7 +93,7 @@ class GraphQLLazyLoadBaseTest: XCTestCase { } throw "See XCTFail message" } - + func listQuery(_ request: GraphQLRequest>) async throws -> List { do { let graphQLResponse = try await Amplify.API.query(request: request) @@ -105,14 +108,16 @@ class GraphQLLazyLoadBaseTest: XCTestCase { } throw "See XCTFail message" } - + enum AssertLazyModelState { case notLoaded(identifiers: [LazyReferenceIdentifier]?) case loaded(model: M?) } - - func assertLazyReference(_ lazyModel: LazyReference, - state: AssertLazyModelState) { + + func assertLazyReference( + _ lazyModel: LazyReference, + state: AssertLazyModelState + ) { switch state { case .notLoaded(let expectedIdentifiers): if case .notLoaded(let identifiers) = lazyModel.modelProvider.getState() { @@ -122,7 +127,7 @@ class GraphQLLazyLoadBaseTest: XCTestCase { } case .loaded(let expectedModel): if case .loaded(let model) = lazyModel.modelProvider.getState() { - guard let expectedModel = expectedModel, let model = model else { + guard let expectedModel, let model else { XCTAssertNil(model) return } @@ -132,13 +137,13 @@ class GraphQLLazyLoadBaseTest: XCTestCase { } } } - + enum AssertListState { case isNotLoaded(associatedIdentifiers: [String], associatedFields: [String]) case isLoaded(count: Int) } - - func assertList(_ list: List, state: AssertListState) { + + func assertList(_ list: List, state: AssertListState) { switch state { case .isNotLoaded(let expectedAssociatedIdentifiers, let expectedAssociatedFields): if case .notLoaded(let associatedIdentifiers, let associatedFields) = list.listProvider.getState() { @@ -155,35 +160,39 @@ class GraphQLLazyLoadBaseTest: XCTestCase { } } } - - func assertModelExists(_ model: M) async throws { + + func assertModelExists(_ model: some Model) async throws { let modelExists = try await query(for: model) != nil XCTAssertTrue(modelExists) } - - func assertModelDoesNotExist(_ model: M) async throws { + + func assertModelDoesNotExist(_ model: some Model) async throws { let modelExists = try await query(for: model) != nil XCTAssertFalse(modelExists) } - + func query(for model: M, includes: IncludedAssociations = { _ in [] }) async throws -> M? { let id = M.identifier(model)(schema: model.schema) - - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: model.schema, - operationType: .query) + + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: model.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) - + if let modelPath = M.rootPath as? ModelPath { let associations = includes(modelPath) documentBuilder.add(decorator: IncludeAssociationDecorator(associations)) } documentBuilder.add(decorator: ModelIdDecorator(identifierFields: id.fields)) let document = documentBuilder.build() - - let request = GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: M?.self, - decodePath: document.name) + + let request = GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: M?.self, + decodePath: document.name + ) return try await query(request) } @@ -207,8 +216,7 @@ class GraphQLLazyLoadBaseTest: XCTestCase { } if let data = subscriptionEvent.extractData(), - try await verifyChange(data) - { + try await verifyChange(data) { eventReceived.fulfill() } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/GraphQLLazyLoadPhoneCallTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/GraphQLLazyLoadPhoneCallTests.swift index df714fd717..67f7b27654 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/GraphQLLazyLoadPhoneCallTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/GraphQLLazyLoadPhoneCallTests.swift @@ -5,19 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadPhoneCallTests: GraphQLLazyLoadBaseTest { - + func testConfigure() async throws { await setup(withModels: PhoneCallModels()) } - + /// Saving a person should be successfully /// /// - Given: A model instance of a Person @@ -30,7 +30,7 @@ final class GraphQLLazyLoadPhoneCallTests: GraphQLLazyLoadBaseTest { let person = Person(name: "name") try await mutate(.create(person)) } - + /// Saving a PhoneCall, requires a caller and a callee, should be successful. /// /// - Given: Two saved persons @@ -46,28 +46,32 @@ final class GraphQLLazyLoadPhoneCallTests: GraphQLLazyLoadBaseTest { let savedCaller = try await mutate(.create(caller)) let callee = Person(name: "callee") let savedCallee = try await mutate(.create(callee)) - + let phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let savedPhoneCall = try await mutate(.create(phoneCall)) let queriedPhoneCall = try await query(for: savedPhoneCall)! - assertLazyReference(queriedPhoneCall._caller, - state: .notLoaded(identifiers: [.init(name: "id", value: caller.id)])) - assertLazyReference(queriedPhoneCall._callee, - state: .notLoaded(identifiers: [.init(name: "id", value: callee.id)])) + assertLazyReference( + queriedPhoneCall._caller, + state: .notLoaded(identifiers: [.init(name: "id", value: caller.id)]) + ) + assertLazyReference( + queriedPhoneCall._callee, + state: .notLoaded(identifiers: [.init(name: "id", value: callee.id)]) + ) let loadedCaller = try await queriedPhoneCall.caller let loadedCallee = try await queriedPhoneCall.callee assertLazyReference(queriedPhoneCall._caller, state: .loaded(model: savedCaller)) assertLazyReference(queriedPhoneCall._callee, state: .loaded(model: savedCallee)) - + let queriedCaller = try await query(for: caller)! try await queriedCaller.callerOf?.fetch() XCTAssertEqual(queriedCaller.callerOf!.count, 1) - + let queriedCallee = try await query(for: callee)! try await queriedCallee.calleeOf?.fetch() XCTAssertEqual(queriedCallee.calleeOf!.count, 1) } - + /// Saving a Transcript with a PhoneCall and a PhoneCall with a Transcript, should be successful /// /// - Given: A Transcript with a PhoneCall. A PhoneCall with a Transcript @@ -87,39 +91,45 @@ final class GraphQLLazyLoadPhoneCallTests: GraphQLLazyLoadBaseTest { let savedCallee = try await mutate(.create(callee)) var phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let transcript = Transcript(text: "text", phoneCall: phoneCall) - + // This is a DX painpoint, the transcript can be set on either the connected model reference or the FK phoneCall.setTranscript(transcript) phoneCall.phoneCallTranscriptId = transcript.id - + let savedPhoneCall = try await mutate(.create(phoneCall)) XCTAssertEqual(savedPhoneCall.phoneCallTranscriptId, transcript.id) let savedTranscript = try await mutate(.create(transcript)) - assertLazyReference(savedTranscript._phoneCall, - state: .notLoaded(identifiers: [.init(name: "id", value: savedPhoneCall.id)])) - + assertLazyReference( + savedTranscript._phoneCall, + state: .notLoaded(identifiers: [.init(name: "id", value: savedPhoneCall.id)]) + ) + let queriedTranscript = try await query(for: savedTranscript)! - assertLazyReference(queriedTranscript._phoneCall, - state: .notLoaded(identifiers: [.init(name: "id", value: savedPhoneCall.id)])) + assertLazyReference( + queriedTranscript._phoneCall, + state: .notLoaded(identifiers: [.init(name: "id", value: savedPhoneCall.id)]) + ) let loadedPhoneCall = try await queriedTranscript.phoneCall! - assertLazyReference(queriedTranscript._phoneCall, - state: .loaded(model: savedPhoneCall)) + assertLazyReference( + queriedTranscript._phoneCall, + state: .loaded(model: savedPhoneCall) + ) let loadedCaller = try await loadedPhoneCall.caller let loadedCallee = try await loadedPhoneCall.callee - + try await loadedCaller.callerOf?.fetch() XCTAssertEqual(loadedCaller.callerOf!.count, 1) - + try await loadedCaller.calleeOf?.fetch() XCTAssertEqual(loadedCaller.calleeOf!.count, 0) - + try await loadedCallee.callerOf?.fetch() XCTAssertEqual(loadedCallee.callerOf!.count, 0) - + try await loadedCallee.calleeOf?.fetch() XCTAssertEqual(loadedCallee.calleeOf!.count, 1) } - + func testUpdatePhoneCallToTranscript() async throws { await setup(withModels: PhoneCallModels()) let caller = Person(name: "caller") @@ -131,22 +141,22 @@ final class GraphQLLazyLoadPhoneCallTests: GraphQLLazyLoadBaseTest { XCTAssertNil(savedPhoneCall.phoneCallTranscriptId) let transcript = Transcript(text: "text", phoneCall: phoneCall) let savedTranscript = try await mutate(.create(transcript)) - + var queriedPhoneCall = try await query(for: savedPhoneCall)! queriedPhoneCall.setTranscript(transcript) let updatedPhoneCall = try await mutate(.update(queriedPhoneCall)) XCTAssertEqual(updatedPhoneCall.phoneCallTranscriptId, transcript.id) } - + func testDeletePerson() async throws { await setup(withModels: PhoneCallModels()) let person = Person(name: "name") let savedPerson = try await mutate(.create(person)) - + try await mutate(.delete(savedPerson)) try await assertModelDoesNotExist(savedPerson) } - + /// Deleting a PhoneCall is successful /// /// - Given: PhoneCall, belongs to two Persons @@ -163,13 +173,13 @@ final class GraphQLLazyLoadPhoneCallTests: GraphQLLazyLoadBaseTest { let savedCallee = try await mutate(.create(callee)) let phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let savedPhoneCall = try await mutate(.create(phoneCall)) - + try await mutate(.delete(savedPhoneCall)) try await assertModelDoesNotExist(savedPhoneCall) try await assertModelExists(caller) try await assertModelExists(callee) } - + /// Delete a PhoneCall before deleting the Caller and Callee /// /// - Given: PhoneCall which belongs to two different Persons (caller and callee) @@ -186,7 +196,7 @@ final class GraphQLLazyLoadPhoneCallTests: GraphQLLazyLoadBaseTest { let savedCallee = try await mutate(.create(callee)) let phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let savedPhoneCall = try await mutate(.create(phoneCall)) - + try await mutate(.delete(savedPhoneCall)) try await mutate(.delete(savedCaller)) try await mutate(.delete(savedCallee)) @@ -194,7 +204,7 @@ final class GraphQLLazyLoadPhoneCallTests: GraphQLLazyLoadBaseTest { try await assertModelDoesNotExist(savedCaller) try await assertModelDoesNotExist(savedCallee) } - + /// Delete PhoneCall before Deleting Transcript. /// /// - Given: Transcript belongs to a PhoneCall @@ -212,10 +222,10 @@ final class GraphQLLazyLoadPhoneCallTests: GraphQLLazyLoadBaseTest { var phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let transcript = Transcript(text: "text", phoneCall: phoneCall) phoneCall.phoneCallTranscriptId = transcript.id - + let savedPhoneCall = try await mutate(.create(phoneCall)) let savedTranscript = try await mutate(.create(transcript)) - + try await mutate(.delete(savedPhoneCall)) try await mutate(.delete(savedTranscript)) try await assertModelDoesNotExist(savedTranscript) @@ -226,7 +236,7 @@ final class GraphQLLazyLoadPhoneCallTests: GraphQLLazyLoadBaseTest { extension GraphQLLazyLoadPhoneCallTests: DefaultLogger { } extension GraphQLLazyLoadPhoneCallTests { - + struct PhoneCallModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Person+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Person+Schema.swift index 28bef917e2..52d8a37214 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Person+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Person+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Person { +public extension Person { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case callerOf @@ -12,19 +19,19 @@ extension Person { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let person = Person.keys - + model.pluralName = "People" - + model.attributes( .primaryKey(fields: [person.id]) ) - + model.fields( .field(person.id, is: .required, ofType: .string), .field(person.name, is: .required, ofType: .string), @@ -36,32 +43,32 @@ extension Person { .field(person.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Person: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Person { - public var id: FieldPath { +public extension ModelPath where ModelType == Person { + var id: FieldPath { string("id") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var callerOf: ModelPath { + var callerOf: ModelPath { PhoneCall.Path(name: "callerOf", isCollection: true, parent: self) } - public var calleeOf: ModelPath { + var calleeOf: ModelPath { PhoneCall.Path(name: "calleeOf", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Person.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Person.swift index f3d6c1328a..7b577b70b5 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Person.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Person.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Person: Model { public var calleeOf: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - callerOf: List = [], - calleeOf: List = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + callerOf: List = [], + calleeOf: List = [] + ) { + self.init( + id: id, name: name, callerOf: callerOf, calleeOf: calleeOf, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - callerOf: List = [], - calleeOf: List = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + callerOf: List = [], + calleeOf: List = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.callerOf = callerOf diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/PhoneCall+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/PhoneCall+Schema.swift index 557468c4c4..6f2522afe1 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/PhoneCall+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/PhoneCall+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PhoneCall { +public extension PhoneCall { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case caller case callee @@ -13,21 +20,21 @@ extension PhoneCall { case updatedAt case phoneCallTranscriptId } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let phoneCall = PhoneCall.keys - + model.pluralName = "PhoneCalls" - + model.attributes( .index(fields: ["callerId"], name: "byCaller"), .index(fields: ["calleeId"], name: "byCallee"), .primaryKey(fields: [phoneCall.id]) ) - + model.fields( .field(phoneCall.id, is: .required, ofType: .string), .belongsTo(phoneCall.caller, is: .required, ofType: Person.self, targetNames: ["callerId"]), @@ -38,35 +45,35 @@ extension PhoneCall { .field(phoneCall.phoneCallTranscriptId, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PhoneCall: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == PhoneCall { - public var id: FieldPath { +public extension ModelPath where ModelType == PhoneCall { + var id: FieldPath { string("id") } - public var caller: ModelPath { + var caller: ModelPath { Person.Path(name: "caller", parent: self) } - public var callee: ModelPath { + var callee: ModelPath { Person.Path(name: "callee", parent: self) } - public var transcript: ModelPath { + var transcript: ModelPath { Transcript.Path(name: "transcript", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } - public var phoneCallTranscriptId: FieldPath { + var phoneCallTranscriptId: FieldPath { string("phoneCallTranscriptId") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/PhoneCall.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/PhoneCall.swift index 54ebec566c..723b4cb393 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/PhoneCall.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/PhoneCall.swift @@ -1,22 +1,29 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation public struct PhoneCall: Model { public let id: String - internal var _caller: LazyReference + var _caller: LazyReference public var caller: Person { get async throws { try await _caller.require() } } - internal var _callee: LazyReference + var _callee: LazyReference public var callee: Person { get async throws { try await _callee.require() } } - internal var _transcript: LazyReference + var _transcript: LazyReference public var transcript: Transcript? { get async throws { try await _transcript.get() @@ -25,27 +32,33 @@ public struct PhoneCall: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? public var phoneCallTranscriptId: String? - - public init(id: String = UUID().uuidString, - caller: Person, - callee: Person, - transcript: Transcript? = nil, - phoneCallTranscriptId: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + caller: Person, + callee: Person, + transcript: Transcript? = nil, + phoneCallTranscriptId: String? = nil + ) { + self.init( + id: id, caller: caller, callee: callee, transcript: transcript, createdAt: nil, updatedAt: nil, - phoneCallTranscriptId: phoneCallTranscriptId) + phoneCallTranscriptId: phoneCallTranscriptId + ) } - internal init(id: String = UUID().uuidString, - caller: Person, - callee: Person, - transcript: Transcript? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - phoneCallTranscriptId: String? = nil) { + init( + id: String = UUID().uuidString, + caller: Person, + callee: Person, + transcript: Transcript? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + phoneCallTranscriptId: String? = nil + ) { self.id = id self._caller = LazyReference(caller) self._callee = LazyReference(callee) @@ -55,23 +68,23 @@ public struct PhoneCall: Model { self.phoneCallTranscriptId = phoneCallTranscriptId } public mutating func setCaller(_ caller: Person) { - self._caller = LazyReference(caller) + _caller = LazyReference(caller) } public mutating func setCallee(_ callee: Person) { - self._callee = LazyReference(callee) + _callee = LazyReference(callee) } public mutating func setTranscript(_ transcript: Transcript? = nil) { - self._transcript = LazyReference(transcript) + _transcript = LazyReference(transcript) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - _caller = try values.decodeIfPresent(LazyReference.self, forKey: .caller) ?? LazyReference(identifiers: nil) - _callee = try values.decodeIfPresent(LazyReference.self, forKey: .callee) ?? LazyReference(identifiers: nil) - _transcript = try values.decodeIfPresent(LazyReference.self, forKey: .transcript) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - phoneCallTranscriptId = try? values.decode(String?.self, forKey: .phoneCallTranscriptId) + self.id = try values.decode(String.self, forKey: .id) + self._caller = try values.decodeIfPresent(LazyReference.self, forKey: .caller) ?? LazyReference(identifiers: nil) + self._callee = try values.decodeIfPresent(LazyReference.self, forKey: .callee) ?? LazyReference(identifiers: nil) + self._transcript = try values.decodeIfPresent(LazyReference.self, forKey: .transcript) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.phoneCallTranscriptId = try? values.decode(String?.self, forKey: .phoneCallTranscriptId) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Transcript+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Transcript+Schema.swift index 7bffc18bdb..7c600943a4 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Transcript+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Transcript+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Transcript { +public extension Transcript { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case text case language @@ -12,19 +19,19 @@ extension Transcript { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let transcript = Transcript.keys - + model.pluralName = "Transcripts" - + model.attributes( .primaryKey(fields: [transcript.id]) ) - + model.fields( .field(transcript.id, is: .required, ofType: .string), .field(transcript.text, is: .required, ofType: .string), @@ -34,32 +41,32 @@ extension Transcript { .field(transcript.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Transcript: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Transcript { - public var id: FieldPath { +public extension ModelPath where ModelType == Transcript { + var id: FieldPath { string("id") } - public var text: FieldPath { + var text: FieldPath { string("text") } - public var language: FieldPath { + var language: FieldPath { string("language") } - public var phoneCall: ModelPath { + var phoneCall: ModelPath { PhoneCall.Path(name: "phoneCall", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Transcript.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Transcript.swift index 039f461e5b..4144fd8b5b 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Transcript.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/L13/Transcript.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -6,7 +13,7 @@ public struct Transcript: Model { public let id: String public var text: String public var language: String? - internal var _phoneCall: LazyReference + var _phoneCall: LazyReference public var phoneCall: PhoneCall? { get async throws { try await _phoneCall.get() @@ -14,24 +21,30 @@ public struct Transcript: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - text: String, - language: String? = nil, - phoneCall: PhoneCall? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + text: String, + language: String? = nil, + phoneCall: PhoneCall? = nil + ) { + self.init( + id: id, text: text, language: language, phoneCall: phoneCall, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - text: String, - language: String? = nil, - phoneCall: PhoneCall? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + text: String, + language: String? = nil, + phoneCall: PhoneCall? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.text = text self.language = language @@ -40,16 +53,16 @@ public struct Transcript: Model { self.updatedAt = updatedAt } public mutating func setPhoneCall(_ phoneCall: PhoneCall? = nil) { - self._phoneCall = LazyReference(phoneCall) + _phoneCall = LazyReference(phoneCall) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - text = try values.decode(String.self, forKey: .text) - language = try? values.decode(String?.self, forKey: .language) - _phoneCall = try values.decodeIfPresent(LazyReference.self, forKey: .phoneCall) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.text = try values.decode(String.self, forKey: .text) + self.language = try? values.decode(String?.self, forKey: .language) + self._phoneCall = try values.decodeIfPresent(LazyReference.self, forKey: .phoneCall) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Comment4V2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Comment4V2+Schema.swift index 225bbfd4fd..448c925ca0 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Comment4V2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Comment4V2+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment4V2 { +public extension Comment4V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let comment4V2 = Comment4V2.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Comment4V2s" - + model.attributes( .index(fields: ["postID", "content"], name: "byPost4"), .primaryKey(fields: [comment4V2.id]) ) - + model.fields( .field(comment4V2.id, is: .required, ofType: .string), .field(comment4V2.content, is: .required, ofType: .string), @@ -37,29 +44,29 @@ extension Comment4V2 { .field(comment4V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment4V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Comment4V2 { - public var id: FieldPath { +public extension ModelPath where ModelType == Comment4V2 { + var id: FieldPath { string("id") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var post: ModelPath { + var post: ModelPath { Post4V2.Path(name: "post", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Comment4V2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Comment4V2.swift index fe39f08abe..ee184a16d7 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Comment4V2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Comment4V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Comment4V2: Model { public let id: String public var content: String - internal var _post: LazyReference + var _post: LazyReference public var post: Post4V2? { get async throws { try await _post.get() @@ -13,21 +20,27 @@ public struct Comment4V2: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil) { - self.init(id: id, - content: content, - post: post, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil + ) { + self.init( + id: id, + content: content, + post: post, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct Comment4V2: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post4V2? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try values.decode(String.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try values.decode(String.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/GraphQLLazyLoadPostComment4V2Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/GraphQLLazyLoadPostComment4V2Tests.swift index 1b2e2a9838..dea5ae358b 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/GraphQLLazyLoadPostComment4V2Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/GraphQLLazyLoadPostComment4V2Tests.swift @@ -5,13 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { @@ -22,7 +21,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { try await mutate(.create(post)) try await mutate(.create(comment)) } - + // Without `includes` and latest codegenerated types with the model path, the post should be lazy loaded func testCommentWithLazyLoadPost() async throws { await setup(withModels: PostComment4V2Models()) @@ -30,13 +29,13 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { let comment = Comment(content: "content", post: post) let createdPost = try await mutate(.create(post)) let createdComment = try await mutate(.create(comment)) - + // The comment's post should not be loaded, since no `includes` is passed in. // And the codegenerated swift models have the new modelPath properties. assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: createdPost.id)])) let loadedPost = try await createdComment.post! XCTAssertEqual(loadedPost.id, createdPost.id) - + // The loaded post should have comments that are also not loaded let comments = loadedPost.comments! assertList(comments, state: .isNotLoaded(associatedIdentifiers: [createdPost.id], associatedFields: ["post"])) @@ -46,7 +45,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { // the loaded comment's post should not be loaded assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: createdPost.id)])) } - + // With `includes` on `comment.post`, the comment's post should be eager loaded. func testCommentWithEagerLoadPost() async throws { await setup(withModels: PostComment4V2Models()) @@ -67,7 +66,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { // further nested models should not be loaded assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) } - + // With `includes` on `comment.post.comments`, func testCommentWithEagerLoadPostAndPostComments() async throws { await setup(withModels: PostComment4V2Models()) @@ -116,7 +115,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { // further nested models should not be loaded assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) } - + /* - Given: Api plugin is cleared @@ -170,7 +169,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { XCTAssertEqual(request.document, expectedDocument) try await mutate(request) } - + // Without `includes` and latest codegenerated types with the model path, the post's comments should be lazy loaded func testPostWithLazyLoadComments() async throws { await setup(withModels: PostComment4V2Models()) @@ -185,7 +184,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { assertList(comments, state: .isLoaded(count: 1)) assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) } - + // With `includes` on `post.comments` should eager load the post's comments func testPostWithEagerLoadComments() async throws { await setup(withModels: PostComment4V2Models()) @@ -198,7 +197,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { assertList(comments, state: .isLoaded(count: 1)) assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) } - + // With `includes` on `post.comments.post` should eager load the post's comments' post func testPostWithEagerLoadCommentsAndPost() async throws { await setup(withModels: PostComment4V2Models()) @@ -211,25 +210,29 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { assertList(comments, state: .isLoaded(count: 1)) assertLazyReference(comments.first!._post, state: .loaded(model: createdPost)) } - + func testListPostsListComments() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") let comment = Comment(content: "content", post: post) try await mutate(.create(post)) try await mutate(.create(comment)) - + let queriedPosts = try await listQuery(.list(Post.self, where: Post.keys.id == post.id)) assertList(queriedPosts, state: .isLoaded(count: 1)) - assertList(queriedPosts.first!.comments!, - state: .isNotLoaded(associatedIdentifiers: [post.id], associatedFields: ["post"])) - + assertList( + queriedPosts.first!.comments!, + state: .isNotLoaded(associatedIdentifiers: [post.id], associatedFields: ["post"]) + ) + let queriedComments = try await listQuery(.list(Comment.self, where: Comment.keys.id == comment.id)) assertList(queriedComments, state: .isLoaded(count: 1)) - assertLazyReference(queriedComments.first!._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) + assertLazyReference( + queriedComments.first!._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.id)]) + ) } - + func testCreateWithoutPost() async throws { await setup(withModels: PostComment4V2Models()) let comment = Comment(content: "content") @@ -245,7 +248,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { let queriedCommentWithPost = try await query(.get(Comment.self, byId: queriedCommentAfterUpdate.id, includes: { comment in [comment.post]}))! assertLazyReference(queriedCommentWithPost._post, state: .loaded(model: createdPost)) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") @@ -254,7 +257,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { try await mutate(.create(comment)) var queriedComment = try await query(.get(Comment.self, byId: comment.id))! assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) - + let newPost = Post(title: "title") let createdNewPost = try await mutate(.create(newPost)) queriedComment.setPost(newPost) @@ -264,7 +267,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { let queriedCommentWithPost = try await query(.get(Comment.self, byId: queriedCommentAfterUpdate.id, includes: { comment in [comment.post]}))! assertLazyReference(queriedCommentWithPost._post, state: .loaded(model: createdNewPost)) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") @@ -273,20 +276,20 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { try await mutate(.create(comment)) var queriedComment = try await query(.get(Comment.self, byId: comment.id))! assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) - + queriedComment.setPost(nil) let updateCommentRemovePost = try await mutate(.update(queriedComment)) let queriedCommentAfterUpdate = try await query(.get(Comment.self, byId: updateCommentRemovePost.id))! assertLazyReference(queriedCommentAfterUpdate._post, state: .notLoaded(identifiers: nil)) } - + func testDelete() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") let comment = Comment(content: "content", post: post) let createdPost = try await mutate(.create(post)) try await mutate(.create(comment)) - + try await mutate(.delete(createdPost)) let queriedPost = try await query(.get(Post.self, byId: post.id)) XCTAssertNil(queriedPost) @@ -296,7 +299,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { let queryDeletedComment = try await query(.get(Comment.self, byId: comment.id)) XCTAssertNil(queryDeletedComment) } - + func testSubscribeToComments() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") @@ -328,14 +331,14 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) let comment = Comment(content: "content", post: post) try await mutate(.create(comment)) await fulfillment(of: [onCreatedComment], timeout: 10) subscription.cancel() } - + // The identical `includes` parameter should be used because the selection set of the mutation // has to match the selection set of the subscription. func testSubscribeToCommentsIncludesPost() async throws { @@ -344,9 +347,11 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { try await mutate(.create(post)) let connected = expectation(description: "subscription connected") let onCreatedComment = expectation(description: "onCreatedComment received") - let subscriptionIncludes = Amplify.API.subscribe(request: .subscription(of: Comment.self, - type: .onCreate, - includes: { comment in [comment.post]})) + let subscriptionIncludes = Amplify.API.subscribe(request: .subscription( + of: Comment.self, + type: .onCreate, + includes: { comment in [comment.post]} + )) Task { do { for try await subscriptionEvent in subscriptionIncludes { @@ -371,18 +376,18 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 20) let comment = Comment(content: "content", post: post) try await mutate(.create(comment, includes: { comment in [comment.post] })) await fulfillment(of: [onCreatedComment], timeout: 20) subscriptionIncludes.cancel() } - + func testSubscribeToPosts() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") - + let connected = expectation(description: "subscription connected") let onCreatedPost = expectation(description: "onCreatedPost received") let subscription = Amplify.API.subscribe(request: .subscription(of: Post.self, type: .onCreate)) @@ -410,22 +415,24 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) try await mutate(.create(post)) await fulfillment(of: [onCreatedPost], timeout: 10) subscription.cancel() } - + func testSubscribeToPostsIncludes() async throws { await setup(withModels: PostComment4V2Models()) let post = Post(title: "title") - + let connected = expectation(description: "subscription connected") let onCreatedPost = expectation(description: "onCreatedPost received") - let subscriptionIncludes = Amplify.API.subscribe(request: .subscription(of: Post.self, - type: .onCreate, - includes: { post in [post.comments]})) + let subscriptionIncludes = Amplify.API.subscribe(request: .subscription( + of: Post.self, + type: .onCreate, + includes: { post in [post.comments]} + )) Task { do { for try await subscriptionEvent in subscriptionIncludes { @@ -450,7 +457,7 @@ final class GraphQLLazyLoadPostComment4V2Tests: GraphQLLazyLoadBaseTest { XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) try await mutate(.create(post, includes: { post in [post.comments]})) await fulfillment(of: [onCreatedPost], timeout: 10) @@ -463,7 +470,7 @@ extension GraphQLLazyLoadPostComment4V2Tests: DefaultLogger { } extension GraphQLLazyLoadBaseTest { typealias Post = Post4V2 typealias Comment = Comment4V2 - + struct PostComment4V2Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Post4V2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Post4V2+Schema.swift index 2b1435bfa7..cd402d73fb 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Post4V2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Post4V2+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post4V2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post4V2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post4V2 = Post4V2.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Post4V2s" - + model.attributes( .primaryKey(fields: [post4V2.id]) ) - + model.fields( .field(post4V2.id, is: .required, ofType: .string), .field(post4V2.title, is: .required, ofType: .string), @@ -36,10 +43,10 @@ extension Post4V2 { .field(post4V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post4V2: ModelIdentifiable { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Post4V2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Post4V2.swift index 08f3e4b429..9106744759 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Post4V2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL1/Post4V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post4V2: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Comment7+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Comment7+Schema.swift index 2850d94c8d..1cb4ae68a7 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Comment7+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Comment7+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment7 { +public extension Comment7 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case commentId case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let comment7 = Comment7.keys - + model.pluralName = "Comment7s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .index(fields: ["postId", "postTitle"], name: "byPost"), .primaryKey(fields: [comment7.commentId, comment7.content]) ) - + model.fields( .field(comment7.commentId, is: .required, ofType: .string), .field(comment7.content, is: .required, ofType: .string), @@ -34,9 +41,9 @@ extension Comment7 { .field(comment7.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment7: ModelIdentifiable { @@ -44,26 +51,28 @@ extension Comment7: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment7.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment7.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == Comment7 { - public var commentId: FieldPath { +public extension ModelPath where ModelType == Comment7 { + var commentId: FieldPath { string("commentId") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var post: ModelPath { + var post: ModelPath { Post7.Path(name: "post", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Comment7.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Comment7.swift index e2f2ea2620..3e8e4efddd 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Comment7.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Comment7.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Comment7: Model { public let commentId: String public let content: String - internal var _post: LazyReference + var _post: LazyReference public var post: Post7? { get async throws { try await _post.get() @@ -13,21 +20,27 @@ public struct Comment7: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(commentId: String, - content: String, - post: Post7? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + post: Post7? = nil + ) { + self.init( + commentId: commentId, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(commentId: String, - content: String, - post: Post7? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + commentId: String, + content: String, + post: Post7? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.commentId = commentId self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct Comment7: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post7? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - commentId = try values.decode(String.self, forKey: .commentId) - content = try values.decode(String.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.commentId = try values.decode(String.self, forKey: .commentId) + self.content = try values.decode(String.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/GraphQLLazyLoadPostComment7Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/GraphQLLazyLoadPostComment7Tests.swift index 28d7434a23..ba23c15b2b 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/GraphQLLazyLoadPostComment7Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/GraphQLLazyLoadPostComment7Tests.swift @@ -5,24 +5,24 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadPostComment7Tests: GraphQLLazyLoadBaseTest { func testSave() async throws { await setup(withModels: PostComment7Models()) - + let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) try await mutate(.create(post)) try await mutate(.create(comment)) } - + // Without `includes` and latest codegenerated types with the model path, the post should be lazy loaded func testCommentWithLazyLoadPost() async throws { await setup(withModels: PostComment7Models()) @@ -30,15 +30,17 @@ final class GraphQLLazyLoadPostComment7Tests: GraphQLLazyLoadBaseTest { let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) let createdPost = try await mutate(.create(post)) let createdComment = try await mutate(.create(comment)) - + // The comment's post should not be loaded, since no `includes` is passed in. // And the codegenerated swift models have the new modelPath properties. - assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [.init(name: "postId", value: createdPost.postId), - .init(name: "title", value: post.title)])) + assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [ + .init(name: "postId", value: createdPost.postId), + .init(name: "title", value: post.title) + ])) let loadedPost = try await createdComment.post! XCTAssertEqual(loadedPost.postId, createdPost.postId) XCTAssertEqual(loadedPost.title, createdPost.title) - + let comments = loadedPost.comments! // The loaded post should have comments that are also not loaded assertList(comments, state: .isNotLoaded(associatedIdentifiers: [createdPost.postId, createdPost.title], associatedFields: ["post"])) @@ -46,10 +48,12 @@ final class GraphQLLazyLoadPostComment7Tests: GraphQLLazyLoadBaseTest { try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) // the loaded comment's post should not be loaded - assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "postId", value: createdPost.postId), - .init(name: "title", value: createdPost.title)])) + assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [ + .init(name: "postId", value: createdPost.postId), + .init(name: "title", value: createdPost.title) + ])) } - + // With `includes` on `comment.post`, the comment's post should be eager loaded. func testCommentWithEagerLoadPost() async throws { await setup(withModels: PostComment7Models()) @@ -68,10 +72,12 @@ final class GraphQLLazyLoadPostComment7Tests: GraphQLLazyLoadBaseTest { try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) // further nested models should not be loaded - assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "postId", value: createdPost.postId), - .init(name: "title", value: createdPost.title)])) + assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [ + .init(name: "postId", value: createdPost.postId), + .init(name: "title", value: createdPost.title) + ])) } - + func testQueryThenLazyLoad() async throws { await setup(withModels: PostComment7Models()) let post = Post(postId: UUID().uuidString, title: "title") @@ -80,87 +86,114 @@ final class GraphQLLazyLoadPostComment7Tests: GraphQLLazyLoadBaseTest { let savedComment = try await mutate(.create(comment, includes: { comment in [comment.post]})) try await assertComment(savedComment, hasEagerLoaded: savedPost) try await assertPost(savedPost, canLazyLoad: savedComment) - let queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(commentId: comment.commentId, - content: comment.content)))! + let queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier( + commentId: comment.commentId, + content: comment.content + )))! try await assertComment(queriedComment, canLazyLoad: savedPost) let queriedPost = try await query(.get(Post.self, byIdentifier: .identifier(postId: post.postId, title: post.title)))! try await assertPost(queriedPost, canLazyLoad: savedComment) } - + func testListPostsListComments() async throws { await setup(withModels: PostComment7Models()) let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) try await mutate(.create(post)) try await mutate(.create(comment)) - + let queriedPosts = try await listQuery(.list(Post.self, where: Post.keys.postId == post.postId)) assertList(queriedPosts, state: .isLoaded(count: 1)) - assertList(queriedPosts.first!.comments!, - state: .isNotLoaded(associatedIdentifiers: [post.postId, post.title], associatedFields: ["post"])) - + assertList( + queriedPosts.first!.comments!, + state: .isNotLoaded(associatedIdentifiers: [post.postId, post.title], associatedFields: ["post"]) + ) + let queriedComments = try await listQuery(.list(Comment.self, where: Comment.keys.commentId == comment.commentId)) assertList(queriedComments, state: .isLoaded(count: 1)) - assertLazyReference(queriedComments.first!._post, - state: .notLoaded(identifiers: [ - .init(name: "postId", value: post.postId), - .init(name: "title", value: "title")])) + assertLazyReference( + queriedComments.first!._post, + state: .notLoaded(identifiers: [ + .init(name: "postId", value: post.postId), + .init(name: "title", value: "title") + ]) + ) } - - func assertComment(_ comment: Comment, - hasEagerLoaded post: Post) async throws { - assertLazyReference(comment._post, - state: .loaded(model: post)) - + + func assertComment( + _ comment: Comment, + hasEagerLoaded post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) + guard let loadedPost = try await comment.post else { XCTFail("Failed to retrieve the post from the comment") return } XCTAssertEqual(loadedPost.postId, post.postId) - + try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertComment(_ comment: Comment, - canLazyLoad post: Post) async throws { - assertLazyReference(comment._post, state: .notLoaded(identifiers: [.init(name: "postId", value: post.postId), - .init(name: "title", value: post.title)])) + + func assertComment( + _ comment: Comment, + canLazyLoad post: Post + ) async throws { + assertLazyReference(comment._post, state: .notLoaded(identifiers: [ + .init(name: "postId", value: post.postId), + .init(name: "title", value: post.title) + ])) guard let loadedPost = try await comment.post else { XCTFail("Failed to load the post from the comment") return } XCTAssertEqual(loadedPost.postId, post.postId) - assertLazyReference(comment._post, - state: .loaded(model: post)) + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertPost(_ post: Post, - canLazyLoad comment: Comment) async throws { + + func assertPost( + _ post: Post, + canLazyLoad comment: Comment + ) async throws { guard let comments = post.comments else { XCTFail("Missing comments on post") return } - assertList(comments, state: .isNotLoaded(associatedIdentifiers: [post.postId, post.title], - associatedFields: ["post"])) + assertList(comments, state: .isNotLoaded( + associatedIdentifiers: [post.postId, post.title], + associatedFields: ["post"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) guard let comment = comments.first else { XCTFail("Missing lazy loaded comment from post") return } - assertLazyReference(comment._post, state: .notLoaded(identifiers: [.init(name: "postId", value: post.postId), - .init(name: "title", value: post.title)])) + assertLazyReference(comment._post, state: .notLoaded(identifiers: [ + .init(name: "postId", value: post.postId), + .init(name: "title", value: post.title) + ])) } - + func testSaveWithoutPost() async throws { await setup(withModels: PostComment7Models()) let comment = Comment(commentId: UUID().uuidString, content: "content") let savedComment = try await mutate(.create(comment)) - var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(commentId: comment.commentId, - content: comment.content)))! - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: nil)) + var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier( + commentId: comment.commentId, + content: comment.content + )))! + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: nil) + ) let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await mutate(.create(post)) queriedComment.setPost(savedPost) @@ -168,34 +201,42 @@ final class GraphQLLazyLoadPostComment7Tests: GraphQLLazyLoadBaseTest { let queriedComment2 = try await query(for: saveCommentWithPost)! try await assertComment(queriedComment2, canLazyLoad: post) } - + func testUpdateFromQueriedComment() async throws { await setup(withModels: PostComment7Models()) let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) let savedPost = try await mutate(.create(post)) let savedComment = try await mutate(.create(comment)) - var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(commentId: comment.commentId, - content: comment.content)))! - assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [.init(name: "postId", value: post.postId), - .init(name: "title", value: post.title)])) + var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier( + commentId: comment.commentId, + content: comment.content + )))! + assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [ + .init(name: "postId", value: post.postId), + .init(name: "title", value: post.title) + ])) let savedQueriedComment = try await mutate(.update(queriedComment)) let queriedComment2 = try await query(for: savedQueriedComment)! try await assertComment(queriedComment2, canLazyLoad: savedPost) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostComment7Models()) - + let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) _ = try await mutate(.create(post)) let savedComment = try await mutate(.create(comment)) - var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(commentId: comment.commentId, - content: comment.content)))! - assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [.init(name: "postId", value: post.postId), - .init(name: "title", value: post.title)])) - + var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier( + commentId: comment.commentId, + content: comment.content + )))! + assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [ + .init(name: "postId", value: post.postId), + .init(name: "title", value: post.title) + ])) + let newPost = Post(postId: UUID().uuidString, title: "title") _ = try await mutate(.create(newPost)) queriedComment.setPost(newPost) @@ -203,28 +244,34 @@ final class GraphQLLazyLoadPostComment7Tests: GraphQLLazyLoadBaseTest { let queriedComment2 = try await query(for: saveCommentWithNewPost)! try await assertComment(queriedComment2, canLazyLoad: newPost) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostComment7Models()) - + let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) _ = try await mutate(.create(post)) let savedComment = try await mutate(.create(comment)) - var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(commentId: comment.commentId, - content: comment.content)))! - assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [.init(name: "postId", value: post.postId), - .init(name: "title", value: post.title)])) + var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier( + commentId: comment.commentId, + content: comment.content + )))! + assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [ + .init(name: "postId", value: post.postId), + .init(name: "title", value: post.title) + ])) queriedComment.setPost(nil) let saveCommentRemovePost = try await mutate(.update(queriedComment)) let queriedCommentNoPost = try await query(for: saveCommentRemovePost)! - assertLazyReference(queriedCommentNoPost._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedCommentNoPost._post, + state: .notLoaded(identifiers: nil) + ) } - + func testDelete() async throws { await setup(withModels: PostComment7Models()) - + let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) let savedPost = try await mutate(.create(post)) @@ -242,7 +289,7 @@ extension GraphQLLazyLoadPostComment7Tests: DefaultLogger { } extension GraphQLLazyLoadPostComment7Tests { typealias Post = Post7 typealias Comment = Comment7 - + struct PostComment7Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Post7+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Post7+Schema.swift index 9b511cde28..4ebf8b81ef 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Post7+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Post7+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post7 { +public extension Post7 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let post7 = Post7.keys - + model.pluralName = "Post7s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post7.postId, post7.title]) ) - + model.fields( .field(post7.postId, is: .required, ofType: .string), .field(post7.title, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension Post7 { .field(post7.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post7: ModelIdentifiable { @@ -43,26 +50,28 @@ extension Post7: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post7.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post7.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } } -extension ModelPath where ModelType == Post7 { - public var postId: FieldPath { +public extension ModelPath where ModelType == Post7 { + var postId: FieldPath { string("postId") } - public var title: FieldPath { + var title: FieldPath { string("title") } - public var comments: ModelPath { + var comments: ModelPath { Comment7.Path(name: "comments", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Post7.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Post7.swift index aecf363022..c07fbc8320 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Post7.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL10/Post7.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,21 +15,27 @@ public struct Post7: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Comment8+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Comment8+Schema.swift index 7c5a3571b2..415c2046a0 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Comment8+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Comment8+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment8 { +public extension Comment8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case commentId case content case postId @@ -12,21 +19,21 @@ extension Comment8 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let comment8 = Comment8.keys - + model.pluralName = "Comment8s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .index(fields: ["postId", "postTitle"], name: "byPost"), .primaryKey(fields: [comment8.commentId, comment8.content]) ) - + model.fields( .field(comment8.commentId, is: .required, ofType: .string), .field(comment8.content, is: .required, ofType: .string), @@ -36,9 +43,9 @@ extension Comment8 { .field(comment8.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment8: ModelIdentifiable { @@ -46,29 +53,31 @@ extension Comment8: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment8.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment8.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == Comment8 { - public var commentId: FieldPath { +public extension ModelPath where ModelType == Comment8 { + var commentId: FieldPath { string("commentId") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var postId: FieldPath { + var postId: FieldPath { string("postId") } - public var postTitle: FieldPath { + var postTitle: FieldPath { string("postTitle") } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Comment8.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Comment8.swift index 22fcd26a4b..0fc5456492 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Comment8.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Comment8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Comment8: Model { public var postTitle: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(commentId: String, - content: String, - postId: String? = nil, - postTitle: String? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + postId: String? = nil, + postTitle: String? = nil + ) { + self.init( + commentId: commentId, content: content, postId: postId, postTitle: postTitle, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(commentId: String, - content: String, - postId: String? = nil, - postTitle: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + commentId: String, + content: String, + postId: String? = nil, + postTitle: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.commentId = commentId self.content = content self.postId = postId @@ -34,4 +47,4 @@ public struct Comment8: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/GraphQLLazyLoadPostComment8Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/GraphQLLazyLoadPostComment8Tests.swift index ff51b5e9c3..904b902ef8 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/GraphQLLazyLoadPostComment8Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/GraphQLLazyLoadPostComment8Tests.swift @@ -5,35 +5,39 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadPostComment8Tests: GraphQLLazyLoadBaseTest { func testSave() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let savedPost = try await mutate(.create(post)) let savedComment = try await mutate(.create(comment)) } - + func testQueryThenLazyLoad() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let savedPost = try await mutate(.create(post)) let savedComment = try await mutate(.create(comment)) assertComment(savedComment, contains: savedPost) @@ -43,25 +47,29 @@ final class GraphQLLazyLoadPostComment8Tests: GraphQLLazyLoadBaseTest { let queriedPost = try await query(.get(Post.self, byIdentifier: .identifier(postId: post.postId, title: post.title)))! try await assertPost(queriedPost, canLazyLoad: savedComment) } - + func assertComment(_ comment: Comment, contains post: Post) { XCTAssertEqual(comment.postId, post.postId) XCTAssertEqual(comment.postTitle, post.title) } - + func assertCommentDoesNotContainPost(_ comment: Comment) { XCTAssertNil(comment.postId) XCTAssertNil(comment.postTitle) } - - func assertPost(_ post: Post, - canLazyLoad comment: Comment) async throws { + + func assertPost( + _ post: Post, + canLazyLoad comment: Comment + ) async throws { guard let comments = post.comments else { XCTFail("Missing comments on post") return } - assertList(comments, state: .isNotLoaded(associatedIdentifiers: [post.postId, post.title], - associatedFields: ["postId", "postTitle"])) + assertList(comments, state: .isNotLoaded( + associatedIdentifiers: [post.postId, post.title], + associatedFields: ["postId", "postTitle"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) guard let comment = comments.first else { @@ -70,29 +78,33 @@ final class GraphQLLazyLoadPostComment8Tests: GraphQLLazyLoadBaseTest { } assertComment(comment, contains: post) } - + func testListPostsListComments() async throws { await setup(withModels: PostComment8Models()) let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) try await mutate(.create(post)) try await mutate(.create(comment)) - - + + let queriedPosts = try await listQuery(.list(Post.self, where: Post.keys.postId == post.postId)) assertList(queriedPosts, state: .isLoaded(count: 1)) - assertList(queriedPosts.first!.comments!, - state: .isNotLoaded(associatedIdentifiers: [post.postId, post.title], associatedFields: ["postId", "postTitle"])) - + assertList( + queriedPosts.first!.comments!, + state: .isNotLoaded(associatedIdentifiers: [post.postId, post.title], associatedFields: ["postId", "postTitle"]) + ) + let queriedComments = try await listQuery(.list(Comment.self, where: Comment.keys.commentId == comment.commentId)) assertList(queriedComments, state: .isLoaded(count: 1)) XCTAssertEqual(queriedComments.first!.postId, post.postId) XCTAssertEqual(queriedComments.first!.postTitle, post.title) } - + func testSaveWithoutPost() async throws { await setup(withModels: PostComment8Models()) let comment = Comment(commentId: UUID().uuidString, content: "content") @@ -107,14 +119,16 @@ final class GraphQLLazyLoadPostComment8Tests: GraphQLLazyLoadBaseTest { let queriedComment2 = try await query(for: saveCommentWithPost)! assertComment(queriedComment2, contains: post) } - + func testUpdateFromQueriedComment() async throws { await setup(withModels: PostComment8Models()) let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let savedPost = try await mutate(.create(post)) let savedComment = try await mutate(.create(comment)) let queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(commentId: comment.commentId, content: comment.content)))! @@ -123,15 +137,17 @@ final class GraphQLLazyLoadPostComment8Tests: GraphQLLazyLoadBaseTest { let queriedComment2 = try await query(for: savedQueriedComment)! assertComment(queriedComment2, contains: savedPost) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) _ = try await mutate(.create(post)) let savedComment = try await mutate(.create(comment)) var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(commentId: comment.commentId, content: comment.content)))! @@ -144,39 +160,43 @@ final class GraphQLLazyLoadPostComment8Tests: GraphQLLazyLoadBaseTest { let queriedComment2 = try await query(for: saveCommentWithNewPost)! assertComment(queriedComment2, contains: newPost) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) _ = try await mutate(.create(post)) let savedComment = try await mutate(.create(comment)) var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(commentId: comment.commentId, content: comment.content)))! assertComment(queriedComment, contains: post) - + queriedComment.postId = nil queriedComment.postTitle = nil - + let saveCommentRemovePost = try await mutate(.update(queriedComment)) let queriedCommentNoPost = try await query(for: saveCommentRemovePost)! assertCommentDoesNotContainPost(queriedCommentNoPost) } - + func testDelete() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let savedPost = try await mutate(.create(post)) let savedComment = try await mutate(.create(comment)) - + try await mutate(.delete(savedPost)) try await assertModelDoesNotExist(savedPost) try await assertModelExists(savedComment) @@ -190,7 +210,7 @@ extension GraphQLLazyLoadPostComment8Tests: DefaultLogger { } extension GraphQLLazyLoadPostComment8Tests { typealias Post = Post8 typealias Comment = Comment8 - + struct PostComment8Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Post8+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Post8+Schema.swift index cfe0976e51..e4fb344e00 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Post8+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Post8+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post8 { +public extension Post8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let post8 = Post8.keys - + model.pluralName = "Post8s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post8.postId, post8.title]) ) - + model.fields( .field(post8.postId, is: .required, ofType: .string), .field(post8.title, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension Post8 { .field(post8.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post8: ModelIdentifiable { @@ -43,26 +50,28 @@ extension Post8: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post8.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post8.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } } -extension ModelPath where ModelType == Post8 { - public var postId: FieldPath { +public extension ModelPath where ModelType == Post8 { + var postId: FieldPath { string("postId") } - public var title: FieldPath { + var title: FieldPath { string("title") } - public var comments: ModelPath { + var comments: ModelPath { Comment8.Path(name: "comments", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Post8.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Post8.swift index 440cd2b9d7..eb60ae8287 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Post8.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL11/Post8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post8: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo+Schema.swift index 1f4e006ad2..e7abeb3b2a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ChildSansBelongsTo { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ChildSansBelongsTo { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case childId case content case compositePKParentChildrenSansBelongsToCustomId @@ -12,21 +19,21 @@ extension ChildSansBelongsTo { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let childSansBelongsTo = ChildSansBelongsTo.keys - + model.pluralName = "ChildSansBelongsTos" - + model.attributes( .index(fields: ["childId", "content"], name: nil), .index(fields: ["compositePKParentChildrenSansBelongsToCustomId", "compositePKParentChildrenSansBelongsToContent"], name: "byParent"), .primaryKey(fields: [childSansBelongsTo.childId, childSansBelongsTo.content]) ) - + model.fields( .field(childSansBelongsTo.childId, is: .required, ofType: .string), .field(childSansBelongsTo.content, is: .required, ofType: .string), @@ -36,9 +43,9 @@ extension ChildSansBelongsTo { .field(childSansBelongsTo.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ChildSansBelongsTo: ModelIdentifiable { @@ -46,29 +53,31 @@ extension ChildSansBelongsTo: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ChildSansBelongsTo.IdentifierProtocol { - public static func identifier(childId: String, - content: String) -> Self { - .make(fields:[(name: "childId", value: childId), (name: "content", value: content)]) +public extension ChildSansBelongsTo.IdentifierProtocol { + static func identifier( + childId: String, + content: String + ) -> Self { + .make(fields: [(name: "childId", value: childId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == ChildSansBelongsTo { - public var childId: FieldPath { - string("childId") +public extension ModelPath where ModelType == ChildSansBelongsTo { + var childId: FieldPath { + string("childId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var compositePKParentChildrenSansBelongsToCustomId: FieldPath { - string("compositePKParentChildrenSansBelongsToCustomId") + var compositePKParentChildrenSansBelongsToCustomId: FieldPath { + string("compositePKParentChildrenSansBelongsToCustomId") } - public var compositePKParentChildrenSansBelongsToContent: FieldPath { - string("compositePKParentChildrenSansBelongsToContent") + var compositePKParentChildrenSansBelongsToContent: FieldPath { + string("compositePKParentChildrenSansBelongsToContent") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo.swift index b419195e95..b52ce8c5a9 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct ChildSansBelongsTo: Model { public var compositePKParentChildrenSansBelongsToContent: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(childId: String, - content: String, - compositePKParentChildrenSansBelongsToCustomId: String, - compositePKParentChildrenSansBelongsToContent: String? = nil) { - self.init(childId: childId, + + public init( + childId: String, + content: String, + compositePKParentChildrenSansBelongsToCustomId: String, + compositePKParentChildrenSansBelongsToContent: String? = nil + ) { + self.init( + childId: childId, content: content, compositePKParentChildrenSansBelongsToCustomId: compositePKParentChildrenSansBelongsToCustomId, compositePKParentChildrenSansBelongsToContent: compositePKParentChildrenSansBelongsToContent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(childId: String, - content: String, - compositePKParentChildrenSansBelongsToCustomId: String, - compositePKParentChildrenSansBelongsToContent: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + childId: String, + content: String, + compositePKParentChildrenSansBelongsToCustomId: String, + compositePKParentChildrenSansBelongsToContent: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.childId = childId self.content = content self.compositePKParentChildrenSansBelongsToCustomId = compositePKParentChildrenSansBelongsToCustomId diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKChild+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKChild+Schema.swift index ff29705bcc..fb7c116016 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKChild+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKChild+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CompositePKChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension CompositePKChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case childId case content case parent case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let compositePKChild = CompositePKChild.keys - + model.pluralName = "CompositePKChildren" - + model.attributes( .index(fields: ["childId", "content"], name: nil), .index(fields: ["parentId", "parentTitle"], name: "byParent"), .primaryKey(fields: [compositePKChild.childId, compositePKChild.content]) ) - + model.fields( .field(compositePKChild.childId, is: .required, ofType: .string), .field(compositePKChild.content, is: .required, ofType: .string), @@ -34,9 +41,9 @@ extension CompositePKChild { .field(compositePKChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension CompositePKChild: ModelIdentifiable { @@ -44,26 +51,28 @@ extension CompositePKChild: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CompositePKChild.IdentifierProtocol { - public static func identifier(childId: String, - content: String) -> Self { - .make(fields:[(name: "childId", value: childId), (name: "content", value: content)]) +public extension CompositePKChild.IdentifierProtocol { + static func identifier( + childId: String, + content: String + ) -> Self { + .make(fields: [(name: "childId", value: childId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == CompositePKChild { - public var childId: FieldPath { - string("childId") +public extension ModelPath where ModelType == CompositePKChild { + var childId: FieldPath { + string("childId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var parent: ModelPath { - CompositePKParent.Path(name: "parent", parent: self) + var parent: ModelPath { + CompositePKParent.Path(name: "parent", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKChild.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKChild.swift index 9bb28b4dee..7e0222bdc0 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKChild.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct CompositePKChild: Model { public let childId: String public let content: String - internal var _parent: LazyReference + var _parent: LazyReference public var parent: CompositePKParent? { get async throws { try await _parent.get() @@ -13,21 +20,27 @@ public struct CompositePKChild: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(childId: String, - content: String, - parent: CompositePKParent? = nil) { - self.init(childId: childId, + + public init( + childId: String, + content: String, + parent: CompositePKParent? = nil + ) { + self.init( + childId: childId, content: content, parent: parent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(childId: String, - content: String, - parent: CompositePKParent? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + childId: String, + content: String, + parent: CompositePKParent? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.childId = childId self.content = content self._parent = LazyReference(parent) @@ -35,15 +48,15 @@ public struct CompositePKChild: Model { self.updatedAt = updatedAt } public mutating func setParent(_ parent: CompositePKParent? = nil) { - self._parent = LazyReference(parent) + _parent = LazyReference(parent) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - childId = try values.decode(String.self, forKey: .childId) - content = try values.decode(String.self, forKey: .content) - _parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.childId = try values.decode(String.self, forKey: .childId) + self.content = try values.decode(String.self, forKey: .content) + self._parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKParent+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKParent+Schema.swift index e047f0dc3e..0b8341d9c1 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKParent+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKParent+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CompositePKParent { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension CompositePKParent { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case customId case content case children @@ -14,20 +21,20 @@ extension CompositePKParent { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let compositePKParent = CompositePKParent.keys - + model.pluralName = "CompositePKParents" - + model.attributes( .index(fields: ["customId", "content"], name: nil), .primaryKey(fields: [compositePKParent.customId, compositePKParent.content]) ) - + model.fields( .field(compositePKParent.customId, is: .required, ofType: .string), .field(compositePKParent.content, is: .required, ofType: .string), @@ -39,9 +46,9 @@ extension CompositePKParent { .field(compositePKParent.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension CompositePKParent: ModelIdentifiable { @@ -49,35 +56,37 @@ extension CompositePKParent: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CompositePKParent.IdentifierProtocol { - public static func identifier(customId: String, - content: String) -> Self { - .make(fields:[(name: "customId", value: customId), (name: "content", value: content)]) +public extension CompositePKParent.IdentifierProtocol { + static func identifier( + customId: String, + content: String + ) -> Self { + .make(fields: [(name: "customId", value: customId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == CompositePKParent { - public var customId: FieldPath { - string("customId") +public extension ModelPath where ModelType == CompositePKParent { + var customId: FieldPath { + string("customId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var children: ModelPath { - CompositePKChild.Path(name: "children", isCollection: true, parent: self) + var children: ModelPath { + CompositePKChild.Path(name: "children", isCollection: true, parent: self) } - public var implicitChildren: ModelPath { - ImplicitChild.Path(name: "implicitChildren", isCollection: true, parent: self) + var implicitChildren: ModelPath { + ImplicitChild.Path(name: "implicitChildren", isCollection: true, parent: self) } - public var strangeChildren: ModelPath { - StrangeExplicitChild.Path(name: "strangeChildren", isCollection: true, parent: self) + var strangeChildren: ModelPath { + StrangeExplicitChild.Path(name: "strangeChildren", isCollection: true, parent: self) } - public var childrenSansBelongsTo: ModelPath { - ChildSansBelongsTo.Path(name: "childrenSansBelongsTo", isCollection: true, parent: self) + var childrenSansBelongsTo: ModelPath { + ChildSansBelongsTo.Path(name: "childrenSansBelongsTo", isCollection: true, parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKParent.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKParent.swift index d2bef97b61..12a4f511fc 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKParent.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/CompositePKParent.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -11,30 +18,36 @@ public struct CompositePKParent: Model { public var childrenSansBelongsTo: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(customId: String, - content: String, - children: List? = [], - implicitChildren: List? = [], - strangeChildren: List? = [], - childrenSansBelongsTo: List? = []) { - self.init(customId: customId, + + public init( + customId: String, + content: String, + children: List? = [], + implicitChildren: List? = [], + strangeChildren: List? = [], + childrenSansBelongsTo: List? = [] + ) { + self.init( + customId: customId, content: content, children: children, implicitChildren: implicitChildren, strangeChildren: strangeChildren, childrenSansBelongsTo: childrenSansBelongsTo, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(customId: String, - content: String, - children: List? = [], - implicitChildren: List? = [], - strangeChildren: List? = [], - childrenSansBelongsTo: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + customId: String, + content: String, + children: List? = [], + implicitChildren: List? = [], + strangeChildren: List? = [], + childrenSansBelongsTo: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.customId = customId self.content = content self.children = children diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKChildSansTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKChildSansTests.swift index a98c432fa5..e49d3b3c57 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKChildSansTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKChildSansTests.swift @@ -5,34 +5,35 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension GraphQLLazyLoadCompositePKTests { - + // MARK: - CompositePKParent / ChildSansBelongsTo - + func initChildSansBelongsTo(with parent: CompositePKParent) -> ChildSansBelongsTo { ChildSansBelongsTo( childId: UUID().uuidString, content: "content", compositePKParentChildrenSansBelongsToCustomId: parent.customId, - compositePKParentChildrenSansBelongsToContent: parent.content) + compositePKParentChildrenSansBelongsToContent: parent.content + ) } - + func testSaveChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initChildSansBelongsTo(with: savedParent) try await mutate(.create(child)) } - + func testUpdateChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -41,7 +42,7 @@ extension GraphQLLazyLoadCompositePKTests { var savedChild = try await mutate(.create(child)) XCTAssertEqual(savedChild.compositePKParentChildrenSansBelongsToCustomId, savedParent.customId) XCTAssertEqual(savedChild.compositePKParentChildrenSansBelongsToContent, savedParent.content) - + // update the child to a new parent let newParent = initParent() let savedNewParent = try await mutate(.create(newParent)) @@ -51,56 +52,70 @@ extension GraphQLLazyLoadCompositePKTests { XCTAssertEqual(updatedChild.compositePKParentChildrenSansBelongsToCustomId, savedNewParent.customId) XCTAssertEqual(updatedChild.compositePKParentChildrenSansBelongsToContent, savedNewParent.content) } - + func testDeleteChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initChildSansBelongsTo(with: parent) let savedChild = try await mutate(.create(child)) - + try await mutate(.delete(savedChild)) try await assertModelDoesNotExist(savedChild) - + try await mutate(.delete(savedParent)) try await assertModelDoesNotExist(savedParent) } - + func testGetChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initChildSansBelongsTo(with: parent) let savedChild = try await mutate(.create(child)) - + // query parent and load the children - let queriedParent = try await query(.get(CompositePKParent.self, - byIdentifier: .identifier(customId: savedParent.customId, - content: savedParent.content)))! - - assertList(queriedParent.childrenSansBelongsTo!, state: .isNotLoaded(associatedIdentifiers: [queriedParent.customId, - queriedParent.content], - associatedFields: ["compositePKParentChildrenSansBelongsToCustomId", "compositePKParentChildrenSansBelongsToContent"])) + let queriedParent = try await query(.get( + CompositePKParent.self, + byIdentifier: .identifier( + customId: savedParent.customId, + content: savedParent.content + ) + ))! + + assertList(queriedParent.childrenSansBelongsTo!, state: .isNotLoaded( + associatedIdentifiers: [ + queriedParent.customId, + queriedParent.content + ], + associatedFields: ["compositePKParentChildrenSansBelongsToCustomId", "compositePKParentChildrenSansBelongsToContent"] + )) try await queriedParent.childrenSansBelongsTo?.fetch() assertList(queriedParent.childrenSansBelongsTo!, state: .isLoaded(count: 1)) - + // query children and verify the parent - ChildSansBelongsTo - let queriedChildSansBelongsTo = try await query(.get(ChildSansBelongsTo.self, - byIdentifier: .identifier(childId: savedChild.childId, - content: savedChild.content)))! + let queriedChildSansBelongsTo = try await query(.get( + ChildSansBelongsTo.self, + byIdentifier: .identifier( + childId: savedChild.childId, + content: savedChild.content + ) + ))! XCTAssertEqual(queriedChildSansBelongsTo.compositePKParentChildrenSansBelongsToCustomId, savedParent.customId) XCTAssertEqual(queriedChildSansBelongsTo.compositePKParentChildrenSansBelongsToContent, savedParent.content) } - + func testListChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initChildSansBelongsTo(with: savedParent) try await mutate(.create(child)) - - var queriedChild = try await listQuery(.list(ChildSansBelongsTo.self, - where: ChildSansBelongsTo.keys.childId == child.childId && ChildSansBelongsTo.keys.content == child.content)) + + var queriedChild = try await listQuery(.list( + ChildSansBelongsTo.self, + where: ChildSansBelongsTo.keys.childId == child.childId && ChildSansBelongsTo.keys.content == child.content + )) while queriedChild.hasNextPage() { queriedChild = try await queriedChild.getNextPage() } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKChildTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKChildTests.swift index d9bc6411d1..05f3b38903 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKChildTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKChildTests.swift @@ -5,30 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension GraphQLLazyLoadCompositePKTests { // MARK: - CompositePKParent / CompositePKChild - + func initChild(with parent: CompositePKParent? = nil) -> CompositePKChild { CompositePKChild(childId: UUID().uuidString, content: "content", parent: parent) } - + func testSaveCompositePKChild() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initChild(with: savedParent) try await mutate(.create(child)) } - + func testUpdateCompositePKChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -37,7 +37,7 @@ extension GraphQLLazyLoadCompositePKTests { var savedChild = try await mutate(.create(child)) let loadedParent = try await savedChild.parent XCTAssertEqual(loadedParent?.identifier, savedParent.identifier) - + // update the child to a new parent let newParent = initParent() let savedNewParent = try await mutate(.create(newParent)) @@ -46,37 +46,37 @@ extension GraphQLLazyLoadCompositePKTests { let loadedNewParent = try await updatedChild.parent XCTAssertEqual(loadedNewParent?.identifier, savedNewParent.identifier) } - + func testUpdateFromNoParentCompositePKChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await mutate(.create(parent)) - + let childWithoutParent = initChild() var savedChild = try await mutate(.create(childWithoutParent)) let nilParent = try await savedChild.parent XCTAssertNil(nilParent) - + // update the child to a parent savedChild.setParent(savedParent) let savedChildWithParent = try await mutate(.update(savedChild)) let loadedParent = try await savedChildWithParent.parent XCTAssertEqual(loadedParent?.identifier, savedParent.identifier) } - + func testDeleteCompositePKChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initChild(with: parent) let savedChild = try await mutate(.create(child)) - + try await mutate(.delete(savedParent)) try await assertModelDoesNotExist(savedParent) try await mutate(.delete(savedChild)) try await assertModelDoesNotExist(savedChild) } - + func testGetCompositePKChild() async throws { await setup(withModels: CompositePKModels()) @@ -86,25 +86,43 @@ extension GraphQLLazyLoadCompositePKTests { let savedCompositePKChild = try await mutate(.create(child)) // query parent and load the children - let queriedParent = try await query(.get(CompositePKParent.self, - byIdentifier: .identifier(customId: savedParent.customId, - content: savedParent.content)))! - assertList(queriedParent.children!, state: .isNotLoaded(associatedIdentifiers: [queriedParent.customId, - queriedParent.content], - associatedFields: ["parent"])) + let queriedParent = try await query(.get( + CompositePKParent.self, + byIdentifier: .identifier( + customId: savedParent.customId, + content: savedParent.content + ) + ))! + assertList(queriedParent.children!, state: .isNotLoaded( + associatedIdentifiers: [ + queriedParent.customId, + queriedParent.content + ], + associatedFields: ["parent"] + )) try await queriedParent.children?.fetch() assertList(queriedParent.children!, state: .isLoaded(count: 1)) // query child and load the parent - CompositePKChild - let queriedCompositePKChild = try await query(.get(CompositePKChild.self, - byIdentifier: .identifier(childId: savedCompositePKChild.childId, - content: savedCompositePKChild.content)))! - assertLazyReference(queriedCompositePKChild._parent, - state: .notLoaded(identifiers: [.init(name: "customId", value: savedParent.customId), - .init(name: "content", value: savedParent.content)])) + let queriedCompositePKChild = try await query(.get( + CompositePKChild.self, + byIdentifier: .identifier( + childId: savedCompositePKChild.childId, + content: savedCompositePKChild.content + ) + ))! + assertLazyReference( + queriedCompositePKChild._parent, + state: .notLoaded(identifiers: [ + .init(name: "customId", value: savedParent.customId), + .init(name: "content", value: savedParent.content) + ]) + ) let loadedParent = try await queriedCompositePKChild.parent - assertLazyReference(queriedCompositePKChild._parent, - state: .loaded(model: loadedParent)) + assertLazyReference( + queriedCompositePKChild._parent, + state: .loaded(model: loadedParent) + ) } func testListCompositePKChild() async throws { @@ -114,8 +132,10 @@ extension GraphQLLazyLoadCompositePKTests { let child = initChild(with: savedParent) try await mutate(.create(child)) - var queriedChild = try await listQuery(.list(CompositePKChild.self, - where: CompositePKChild.keys.childId == child.childId)) + var queriedChild = try await listQuery(.list( + CompositePKChild.self, + where: CompositePKChild.keys.childId == child.childId + )) while queriedChild.hasNextPage() { queriedChild = try await queriedChild.getNextPage() } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKImplicitTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKImplicitTests.swift index 694b7904f7..960e67c2c5 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKImplicitTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKImplicitTests.swift @@ -5,30 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension GraphQLLazyLoadCompositePKTests { - + // MARK: - CompositePKParent / ImplicitChild - + func initImplicitChild(with parent: CompositePKParent) -> ImplicitChild { ImplicitChild(childId: UUID().uuidString, content: "content", parent: parent) } - + func testSaveImplicitChild() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initImplicitChild(with: savedParent) try await mutate(.create(child)) } - + func testUpdateImplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -37,7 +37,7 @@ extension GraphQLLazyLoadCompositePKTests { var savedChild = try await mutate(.create(child)) let loadedParent = try await savedChild.parent XCTAssertEqual(loadedParent.identifier, savedParent.identifier) - + // update the child to a new parent let newParent = initParent() let savedNewParent = try await mutate(.create(newParent)) @@ -45,63 +45,83 @@ extension GraphQLLazyLoadCompositePKTests { let updatedChild = try await mutate(.update(savedChild)) let loadedNewParent = try await updatedChild.parent XCTAssertEqual(loadedNewParent.identifier, savedNewParent.identifier) - + } - + func testDeleteImplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initImplicitChild(with: parent) let savedChild = try await mutate(.create(child)) - + try await mutate(.delete(savedChild)) try await assertModelDoesNotExist(savedChild) try await mutate(.delete(savedParent)) try await assertModelDoesNotExist(savedParent) } - + func testGetImplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initImplicitChild(with: parent) let savedChild = try await mutate(.create(child)) - + // query parent and load the children - let queriedParent = try await query(.get(CompositePKParent.self, - byIdentifier: .identifier(customId: savedParent.customId, - content: savedParent.content)))! - - assertList(queriedParent.implicitChildren!, state: .isNotLoaded(associatedIdentifiers: [queriedParent.customId, - queriedParent.content], - associatedFields: ["parent"])) + let queriedParent = try await query(.get( + CompositePKParent.self, + byIdentifier: .identifier( + customId: savedParent.customId, + content: savedParent.content + ) + ))! + + assertList(queriedParent.implicitChildren!, state: .isNotLoaded( + associatedIdentifiers: [ + queriedParent.customId, + queriedParent.content + ], + associatedFields: ["parent"] + )) try await queriedParent.implicitChildren?.fetch() assertList(queriedParent.implicitChildren!, state: .isLoaded(count: 1)) - + // query child and load the parent - ImplicitChild - let queriedImplicitChild = try await query(.get(ImplicitChild.self, - byIdentifier: .identifier(childId: savedChild.childId, - content: savedChild.content)))! - assertLazyReference(queriedImplicitChild._parent, - state: .notLoaded(identifiers: [.init(name: "customId", value: savedParent.customId), - .init(name: "content", value: savedParent.content)])) + let queriedImplicitChild = try await query(.get( + ImplicitChild.self, + byIdentifier: .identifier( + childId: savedChild.childId, + content: savedChild.content + ) + ))! + assertLazyReference( + queriedImplicitChild._parent, + state: .notLoaded(identifiers: [ + .init(name: "customId", value: savedParent.customId), + .init(name: "content", value: savedParent.content) + ]) + ) let loadedParent = try await queriedImplicitChild.parent - assertLazyReference(queriedImplicitChild._parent, - state: .loaded(model: loadedParent)) + assertLazyReference( + queriedImplicitChild._parent, + state: .loaded(model: loadedParent) + ) } - + func testListImplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initImplicitChild(with: savedParent) try await mutate(.create(child)) - + var queriedChild = try await listQuery( - .list(ImplicitChild.self, - where: ImplicitChild.keys.childId == child.childId && ImplicitChild.keys.content == child.content)) + .list( + ImplicitChild.self, + where: ImplicitChild.keys.childId == child.childId && ImplicitChild.keys.content == child.content + )) while queriedChild.hasNextPage() { queriedChild = try await queriedChild.getNextPage() } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKStrangeExplicitTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKStrangeExplicitTests.swift index 1b74ee70c6..435e2b49b6 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKStrangeExplicitTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKStrangeExplicitTests.swift @@ -5,30 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension GraphQLLazyLoadCompositePKTests { - + // MARK: - CompositePKParent / StrangeExplicitChild - + func initStrangeExplicitChild(with parent: CompositePKParent) -> StrangeExplicitChild { StrangeExplicitChild(strangeId: UUID().uuidString, content: "content", parent: parent) } - + func testSaveStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initStrangeExplicitChild(with: savedParent) try await mutate(.create(child)) } - + func testUpdateStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -37,7 +37,7 @@ extension GraphQLLazyLoadCompositePKTests { var savedChild = try await mutate(.create(child)) let loadedParent = try await savedChild.parent XCTAssertEqual(loadedParent.identifier, savedParent.identifier) - + // update the child to a new parent let newParent = initParent() let savedNewParent = try await mutate(.create(newParent)) @@ -45,62 +45,82 @@ extension GraphQLLazyLoadCompositePKTests { let updatedChild = try await mutate(.update(savedChild)) let loadedNewParent = try await updatedChild.parent XCTAssertEqual(loadedNewParent.identifier, savedNewParent.identifier) - + } - + func testDeleteStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initStrangeExplicitChild(with: parent) let savedChild = try await mutate(.create(child)) - + try await mutate(.delete(savedChild)) try await assertModelDoesNotExist(savedChild) try await mutate(.delete(savedParent)) try await assertModelDoesNotExist(savedParent) } - + func testGetStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initStrangeExplicitChild(with: parent) let savedChild = try await mutate(.create(child)) - + // query parent and load the children - let queriedParent = try await query(.get(CompositePKParent.self, - byIdentifier: .identifier(customId: savedParent.customId, - content: savedParent.content)))! - - assertList(queriedParent.strangeChildren!, state: .isNotLoaded(associatedIdentifiers: [queriedParent.customId, - queriedParent.content], - associatedFields: ["parent"])) + let queriedParent = try await query(.get( + CompositePKParent.self, + byIdentifier: .identifier( + customId: savedParent.customId, + content: savedParent.content + ) + ))! + + assertList(queriedParent.strangeChildren!, state: .isNotLoaded( + associatedIdentifiers: [ + queriedParent.customId, + queriedParent.content + ], + associatedFields: ["parent"] + )) try await queriedParent.strangeChildren?.fetch() assertList(queriedParent.strangeChildren!, state: .isLoaded(count: 1)) - + // query children and load the parent - StrangeExplicitChild - let queriedStrangeImplicitChild = try await query(.get(StrangeExplicitChild.self, - byIdentifier: .identifier(strangeId: savedChild.strangeId, - content: savedChild.content)))! - assertLazyReference(queriedStrangeImplicitChild._parent, - state: .notLoaded(identifiers: [.init(name: "customId", value: savedParent.customId), - .init(name: "content", value: savedParent.content)])) + let queriedStrangeImplicitChild = try await query(.get( + StrangeExplicitChild.self, + byIdentifier: .identifier( + strangeId: savedChild.strangeId, + content: savedChild.content + ) + ))! + assertLazyReference( + queriedStrangeImplicitChild._parent, + state: .notLoaded(identifiers: [ + .init(name: "customId", value: savedParent.customId), + .init(name: "content", value: savedParent.content) + ]) + ) let loadedParent3 = try await queriedStrangeImplicitChild.parent - assertLazyReference(queriedStrangeImplicitChild._parent, - state: .loaded(model: loadedParent3)) + assertLazyReference( + queriedStrangeImplicitChild._parent, + state: .loaded(model: loadedParent3) + ) } - + func testListStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await mutate(.create(parent)) let child = initStrangeExplicitChild(with: savedParent) try await mutate(.create(child)) - + var queriedChild = try await listQuery( - .list(StrangeExplicitChild.self, - where: StrangeExplicitChild.keys.strangeId == child.strangeId && StrangeExplicitChild.keys.content == child.content)) + .list( + StrangeExplicitChild.self, + where: StrangeExplicitChild.keys.strangeId == child.strangeId && StrangeExplicitChild.keys.content == child.content + )) while queriedChild.hasNextPage() { queriedChild = try await queriedChild.getNextPage() } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKTests.swift index 9f7e8bbf74..0717bab822 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/GraphQLLazyLoadCompositePKTests.swift @@ -5,25 +5,25 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadCompositePKTests: GraphQLLazyLoadBaseTest { func testConfigure() async throws { await setup(withModels: CompositePKModels()) } - + func testIncludesAllChildren() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await mutate(.create(parent)) - + let child = initChild(with: savedParent) try await mutate(.create(child)) let implicitChild = initImplicitChild(with: savedParent) @@ -32,13 +32,17 @@ final class GraphQLLazyLoadCompositePKTests: GraphQLLazyLoadBaseTest { try await mutate(.create(explicitChild)) let sansChild = initChildSansBelongsTo(with: savedParent) try await mutate(.create(sansChild)) - - let request = GraphQLRequest.get(CompositePKParent.self, - byIdentifier: .identifier(customId: savedParent.customId, - content: savedParent.content), - includes: { parent in + + let request = GraphQLRequest.get( + CompositePKParent.self, + byIdentifier: .identifier( + customId: savedParent.customId, + content: savedParent.content + ), + includes: { parent in [parent.children, parent.implicitChildren, parent.strangeChildren, parent.childrenSansBelongsTo] - }) + } + ) let expectedDocument = """ query GetCompositePKParent($content: String!, $customId: ID!) { getCompositePKParent(content: $content, customId: $customId) { @@ -112,7 +116,7 @@ final class GraphQLLazyLoadCompositePKTests: GraphQLLazyLoadBaseTest { extension GraphQLLazyLoadCompositePKTests: DefaultLogger { } extension GraphQLLazyLoadCompositePKTests { - + struct CompositePKModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -123,9 +127,11 @@ extension GraphQLLazyLoadCompositePKTests { ModelRegistry.register(modelType: ChildSansBelongsTo.self) } } - + func initParent() -> CompositePKParent { - CompositePKParent(customId: UUID().uuidString, - content: "content") + CompositePKParent( + customId: UUID().uuidString, + content: "content" + ) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ImplicitChild+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ImplicitChild+Schema.swift index a515819f26..cbbbd263a8 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ImplicitChild+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ImplicitChild+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ImplicitChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ImplicitChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case childId case content case parent case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let implicitChild = ImplicitChild.keys - + model.pluralName = "ImplicitChildren" - + model.attributes( .index(fields: ["childId", "content"], name: nil), .primaryKey(fields: [implicitChild.childId, implicitChild.content]) ) - + model.fields( .field(implicitChild.childId, is: .required, ofType: .string), .field(implicitChild.content, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension ImplicitChild { .field(implicitChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ImplicitChild: ModelIdentifiable { @@ -43,26 +50,28 @@ extension ImplicitChild: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ImplicitChild.IdentifierProtocol { - public static func identifier(childId: String, - content: String) -> Self { - .make(fields:[(name: "childId", value: childId), (name: "content", value: content)]) +public extension ImplicitChild.IdentifierProtocol { + static func identifier( + childId: String, + content: String + ) -> Self { + .make(fields: [(name: "childId", value: childId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == ImplicitChild { - public var childId: FieldPath { - string("childId") +public extension ModelPath where ModelType == ImplicitChild { + var childId: FieldPath { + string("childId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var parent: ModelPath { - CompositePKParent.Path(name: "parent", parent: self) + var parent: ModelPath { + CompositePKParent.Path(name: "parent", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ImplicitChild.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ImplicitChild.swift index 78ec7c0f2d..b8f2e21ccb 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ImplicitChild.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/ImplicitChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct ImplicitChild: Model { public let childId: String public let content: String - internal var _parent: LazyReference + var _parent: LazyReference public var parent: CompositePKParent { get async throws { try await _parent.require() @@ -13,21 +20,27 @@ public struct ImplicitChild: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(childId: String, - content: String, - parent: CompositePKParent) { - self.init(childId: childId, + + public init( + childId: String, + content: String, + parent: CompositePKParent + ) { + self.init( + childId: childId, content: content, parent: parent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(childId: String, - content: String, - parent: CompositePKParent, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + childId: String, + content: String, + parent: CompositePKParent, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.childId = childId self.content = content self._parent = LazyReference(parent) @@ -35,15 +48,15 @@ public struct ImplicitChild: Model { self.updatedAt = updatedAt } public mutating func setParent(_ parent: CompositePKParent) { - self._parent = LazyReference(parent) + _parent = LazyReference(parent) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - childId = try values.decode(String.self, forKey: .childId) - content = try values.decode(String.self, forKey: .content) - _parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.childId = try values.decode(String.self, forKey: .childId) + self.content = try values.decode(String.self, forKey: .content) + self._parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild+Schema.swift index d4d8af24ee..172e7a9b4c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension StrangeExplicitChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension StrangeExplicitChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case strangeId case content case parent case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let strangeExplicitChild = StrangeExplicitChild.keys - + model.pluralName = "StrangeExplicitChildren" - + model.attributes( .index(fields: ["strangeId", "content"], name: nil), .index(fields: ["strangeParentId", "strangeParentTitle"], name: "byCompositePKParentX"), .primaryKey(fields: [strangeExplicitChild.strangeId, strangeExplicitChild.content]) ) - + model.fields( .field(strangeExplicitChild.strangeId, is: .required, ofType: .string), .field(strangeExplicitChild.content, is: .required, ofType: .string), @@ -34,9 +41,9 @@ extension StrangeExplicitChild { .field(strangeExplicitChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension StrangeExplicitChild: ModelIdentifiable { @@ -44,26 +51,28 @@ extension StrangeExplicitChild: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension StrangeExplicitChild.IdentifierProtocol { - public static func identifier(strangeId: String, - content: String) -> Self { - .make(fields:[(name: "strangeId", value: strangeId), (name: "content", value: content)]) +public extension StrangeExplicitChild.IdentifierProtocol { + static func identifier( + strangeId: String, + content: String + ) -> Self { + .make(fields: [(name: "strangeId", value: strangeId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == StrangeExplicitChild { - public var strangeId: FieldPath { - string("strangeId") +public extension ModelPath where ModelType == StrangeExplicitChild { + var strangeId: FieldPath { + string("strangeId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var parent: ModelPath { - CompositePKParent.Path(name: "parent", parent: self) + var parent: ModelPath { + CompositePKParent.Path(name: "parent", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild.swift index 45fb1b967d..e2519d542e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct StrangeExplicitChild: Model { public let strangeId: String public let content: String - internal var _parent: LazyReference + var _parent: LazyReference public var parent: CompositePKParent { get async throws { try await _parent.require() @@ -13,21 +20,27 @@ public struct StrangeExplicitChild: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(strangeId: String, - content: String, - parent: CompositePKParent) { - self.init(strangeId: strangeId, + + public init( + strangeId: String, + content: String, + parent: CompositePKParent + ) { + self.init( + strangeId: strangeId, content: content, parent: parent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(strangeId: String, - content: String, - parent: CompositePKParent, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + strangeId: String, + content: String, + parent: CompositePKParent, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.strangeId = strangeId self.content = content self._parent = LazyReference(parent) @@ -35,15 +48,15 @@ public struct StrangeExplicitChild: Model { self.updatedAt = updatedAt } public mutating func setParent(_ parent: CompositePKParent) { - self._parent = LazyReference(parent) + _parent = LazyReference(parent) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - strangeId = try values.decode(String.self, forKey: .strangeId) - content = try values.decode(String.self, forKey: .content) - _parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.strangeId = try values.decode(String.self, forKey: .strangeId) + self.content = try values.decode(String.self, forKey: .content) + self._parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild+Schema.swift index 9fe9d05f4c..44da59840b 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension DefaultPKChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension DefaultPKChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case parent case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let defaultPKChild = DefaultPKChild.keys - + model.pluralName = "DefaultPKChildren" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [defaultPKChild.id]) ) - + model.fields( .field(defaultPKChild.id, is: .required, ofType: .string), .field(defaultPKChild.content, is: .optional, ofType: .string), @@ -33,29 +40,29 @@ extension DefaultPKChild { .field(defaultPKChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension DefaultPKChild: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == DefaultPKChild { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == DefaultPKChild { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var parent: ModelPath { - DefaultPKParent.Path(name: "parent", parent: self) + var parent: ModelPath { + DefaultPKParent.Path(name: "parent", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild.swift index dabbd4888e..e1ef75fd6d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct DefaultPKChild: Model { public let id: String public var content: String? - internal var _parent: LazyReference + var _parent: LazyReference public var parent: DefaultPKParent? { get async throws { try await _parent.get() @@ -13,21 +20,27 @@ public struct DefaultPKChild: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - parent: DefaultPKParent? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + parent: DefaultPKParent? = nil + ) { + self.init( + id: id, content: content, parent: parent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - parent: DefaultPKParent? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + parent: DefaultPKParent? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._parent = LazyReference(parent) @@ -35,15 +48,15 @@ public struct DefaultPKChild: Model { self.updatedAt = updatedAt } public mutating func setParent(_ parent: DefaultPKParent? = nil) { - self._parent = LazyReference(parent) + _parent = LazyReference(parent) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try? values.decode(String?.self, forKey: .content) - _parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try? values.decode(String?.self, forKey: .content) + self._parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent+Schema.swift index d493d3a95f..39c2889c26 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension DefaultPKParent { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension DefaultPKParent { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case children case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let defaultPKParent = DefaultPKParent.keys - + model.pluralName = "DefaultPKParents" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [defaultPKParent.id]) ) - + model.fields( .field(defaultPKParent.id, is: .required, ofType: .string), .field(defaultPKParent.content, is: .optional, ofType: .string), @@ -33,29 +40,29 @@ extension DefaultPKParent { .field(defaultPKParent.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension DefaultPKParent: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == DefaultPKParent { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == DefaultPKParent { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var children: ModelPath { - DefaultPKChild.Path(name: "children", isCollection: true, parent: self) + var children: ModelPath { + DefaultPKChild.Path(name: "children", isCollection: true, parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent.swift index 830d085e35..d2bedd8d1e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,21 +15,27 @@ public struct DefaultPKParent: Model { public var children: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - children: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + children: List? = [] + ) { + self.init( + id: id, content: content, children: children, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - children: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + children: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.children = children diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/GraphQLLazyLoadDefaultPKTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/GraphQLLazyLoadDefaultPKTests.swift index a530aacb2e..96de0c34b5 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/GraphQLLazyLoadDefaultPKTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/DefaultPK/GraphQLLazyLoadDefaultPKTests.swift @@ -5,100 +5,118 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadDefaultPKTests: GraphQLLazyLoadBaseTest { func testConfigure() async throws { await setup(withModels: DefaultPKModels()) } - + func testDefaultPKParentChild() async throws { await setup(withModels: DefaultPKModels()) let defaultPKParent = DefaultPKParent() let savedParent = try await mutate(.create(defaultPKParent)) let defaultPKChild = DefaultPKChild(parent: savedParent) let savedChild = try await mutate(.create(defaultPKChild)) - - assertLazyReference(savedChild._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: savedParent.id)])) + + assertLazyReference( + savedChild._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: savedParent.id)]) + ) let loadedParent = try await savedChild.parent - assertLazyReference(savedChild._parent, - state: .loaded(model: loadedParent)) + assertLazyReference( + savedChild._parent, + state: .loaded(model: loadedParent) + ) } - + func testDefaultParentChildUpdate() async throws { await setup(withModels: DefaultPKModels()) let defaultPKParent = DefaultPKParent() let savedParent = try await mutate(.create(defaultPKParent)) let defaultPKChild = DefaultPKChild(parent: savedParent) var savedChild = try await mutate(.create(defaultPKChild)) - + let newParent = DefaultPKParent() let savedNewParent = try await mutate(.create(newParent)) savedChild.setParent(savedNewParent) var updatedChild = try await mutate(.update(savedChild)) - - assertLazyReference(updatedChild._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: newParent.id)])) + + assertLazyReference( + updatedChild._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: newParent.id)]) + ) let loadedParent = try await updatedChild.parent - assertLazyReference(updatedChild._parent, - state: .loaded(model: loadedParent)) + assertLazyReference( + updatedChild._parent, + state: .loaded(model: loadedParent) + ) } - + func testDefaultParentChildDelete() async throws { await setup(withModels: DefaultPKModels()) let defaultPKParent = DefaultPKParent() let savedParent = try await mutate(.create(defaultPKParent)) let defaultPKChild = DefaultPKChild(parent: savedParent) let savedChild = try await mutate(.create(defaultPKChild)) - + try await mutate(.delete(savedParent)) try await assertModelDoesNotExist(savedParent) try await assertModelExists(savedChild) try await mutate(.delete(savedChild)) try await assertModelDoesNotExist(savedChild) } - + func testDefaultPKParentChildGet() async throws { await setup(withModels: DefaultPKModels()) let defaultPKParent = DefaultPKParent() let savedParent = try await mutate(.create(defaultPKParent)) let defaultPKChild = DefaultPKChild(parent: savedParent) let savedChild = try await mutate(.create(defaultPKChild)) - + let queriedParent = try await query(.get(DefaultPKParent.self, byId: savedParent.id))! - assertList(queriedParent.children!, state: .isNotLoaded(associatedIdentifiers: [queriedParent.id], - associatedFields: ["parent"])) + assertList(queriedParent.children!, state: .isNotLoaded( + associatedIdentifiers: [queriedParent.id], + associatedFields: ["parent"] + )) try await queriedParent.children?.fetch() assertList(queriedParent.children!, state: .isLoaded(count: 1)) - + let queriedChild = try await query(.get(DefaultPKChild.self, byId: savedChild.id))! - assertLazyReference(queriedChild._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: savedParent.id)])) + assertLazyReference( + queriedChild._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: savedParent.id)]) + ) let loadedParent = try await queriedChild.parent - assertLazyReference(queriedChild._parent, - state: .loaded(model: loadedParent)) + assertLazyReference( + queriedChild._parent, + state: .loaded(model: loadedParent) + ) } - + func testDefaultPKParentChildList() async throws { await setup(withModels: DefaultPKModels()) let defaultPKParent = DefaultPKParent() let savedParent = try await mutate(.create(defaultPKParent)) let defaultPKChild = DefaultPKChild(parent: savedParent) let savedChild = try await mutate(.create(defaultPKChild)) - - let queriedParents = try await listQuery(.list(DefaultPKParent.self, - where: DefaultPKParent.keys.id == defaultPKParent.id)) + + let queriedParents = try await listQuery(.list( + DefaultPKParent.self, + where: DefaultPKParent.keys.id == defaultPKParent.id + )) assertList(queriedParents, state: .isLoaded(count: 1)) - - let queriedChildren = try await listQuery(.list(DefaultPKChild.self, - where: DefaultPKChild.keys.id == defaultPKChild.id)) + + let queriedChildren = try await listQuery(.list( + DefaultPKChild.self, + where: DefaultPKChild.keys.id == defaultPKChild.id + )) assertList(queriedChildren, state: .isLoaded(count: 1)) } @@ -269,7 +287,7 @@ final class GraphQLLazyLoadDefaultPKTests: GraphQLLazyLoadBaseTest { extension GraphQLLazyLoadDefaultPKTests: DefaultLogger { } extension GraphQLLazyLoadDefaultPKTests { - + struct DefaultPKModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/GraphQLLazyLoadHasOneTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/GraphQLLazyLoadHasOneTests.swift index 25f8a575b1..80c8fb84ff 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/GraphQLLazyLoadHasOneTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/GraphQLLazyLoadHasOneTests.swift @@ -5,96 +5,112 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadHasOneTests: GraphQLLazyLoadBaseTest { func testConfigure() async throws { await setup(withModels: HasOneParentChildModels()) } - + func testHasOneParentChild() async throws { await setup(withModels: HasOneParentChildModels()) let hasOneChild = HasOneChild() let savedChild = try await mutate(.create(hasOneChild)) let hasOneParent = HasOneParent(child: hasOneChild) let savedParent = try await mutate(.create(hasOneParent)) - - assertLazyReference(savedParent._child, - state: .notLoaded(identifiers: [.init(name: "id", value: savedChild.id)])) + + assertLazyReference( + savedParent._child, + state: .notLoaded(identifiers: [.init(name: "id", value: savedChild.id)]) + ) let loadedChild = try await savedParent.child - assertLazyReference(savedParent._child, - state: .loaded(model: loadedChild)) + assertLazyReference( + savedParent._child, + state: .loaded(model: loadedChild) + ) } - + func testHasOneParentChildUpdate() async throws { await setup(withModels: HasOneParentChildModels()) let hasOneChild = HasOneChild() let savedChild = try await mutate(.create(hasOneChild)) let hasOneParent = HasOneParent(child: hasOneChild) var savedParent = try await mutate(.create(hasOneParent)) - + let newChild = HasOneChild() let savedNewChild = try await mutate(.create(newChild)) savedParent.setChild(newChild) var updatedParent = try await mutate(.update(savedParent)) - - assertLazyReference(updatedParent._child, - state: .notLoaded(identifiers: [.init(name: "id", value: newChild.id)])) + + assertLazyReference( + updatedParent._child, + state: .notLoaded(identifiers: [.init(name: "id", value: newChild.id)]) + ) let loadedChild = try await updatedParent.child - assertLazyReference(updatedParent._child, - state: .loaded(model: loadedChild)) + assertLazyReference( + updatedParent._child, + state: .loaded(model: loadedChild) + ) } - + func testHasOneParentChildDelete() async throws { await setup(withModels: HasOneParentChildModels()) let hasOneChild = HasOneChild() let savedChild = try await mutate(.create(hasOneChild)) let hasOneParent = HasOneParent(child: hasOneChild) var savedParent = try await mutate(.create(hasOneParent)) - + try await mutate(.delete(savedParent)) try await assertModelDoesNotExist(savedParent) try await assertModelExists(savedChild) try await mutate(.delete(savedChild)) try await assertModelDoesNotExist(savedChild) } - + func testHasOneParentChildGet() async throws { await setup(withModels: HasOneParentChildModels()) let hasOneChild = HasOneChild() let savedChild = try await mutate(.create(hasOneChild)) let hasOneParent = HasOneParent(child: hasOneChild) let savedParent = try await mutate(.create(hasOneParent)) - + let queriedParent = try await query(.get(HasOneParent.self, byId: savedParent.id))! - assertLazyReference(queriedParent._child, - state: .notLoaded(identifiers: [.init(name: "id", value: savedChild.id)])) + assertLazyReference( + queriedParent._child, + state: .notLoaded(identifiers: [.init(name: "id", value: savedChild.id)]) + ) let loadedChild = try await queriedParent.child - assertLazyReference(queriedParent._child, - state: .loaded(model: loadedChild)) - + assertLazyReference( + queriedParent._child, + state: .loaded(model: loadedChild) + ) + let queriedChild = try await query(.get(HasOneChild.self, byId: savedChild.id))! } - + func testHasOneParentChildList() async throws { await setup(withModels: HasOneParentChildModels()) let hasOneChild = HasOneChild() let savedChild = try await mutate(.create(hasOneChild)) let hasOneParent = HasOneParent(child: hasOneChild) let savedParent = try await mutate(.create(hasOneParent)) - - let queriedParents = try await listQuery(.list(HasOneParent.self, - where: HasOneParent.keys.id == hasOneParent.id)) + + let queriedParents = try await listQuery(.list( + HasOneParent.self, + where: HasOneParent.keys.id == hasOneParent.id + )) assertList(queriedParents, state: .isLoaded(count: 1)) - - let queriedChildren = try await listQuery(.list(HasOneChild.self, - where: HasOneChild.keys.id == hasOneChild.id)) + + let queriedChildren = try await listQuery(.list( + HasOneChild.self, + where: HasOneChild.keys.id == hasOneChild.id + )) assertList(queriedChildren, state: .isLoaded(count: 1)) } @@ -256,7 +272,7 @@ final class GraphQLLazyLoadHasOneTests: GraphQLLazyLoadBaseTest { extension GraphQLLazyLoadHasOneTests: DefaultLogger { } extension GraphQLLazyLoadHasOneTests { - + struct HasOneParentChildModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild+Schema.swift index 5256e3b18a..9a67ca4452 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension HasOneChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension HasOneChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let hasOneChild = HasOneChild.keys - + model.pluralName = "HasOneChildren" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [hasOneChild.id]) ) - + model.fields( .field(hasOneChild.id, is: .required, ofType: .string), .field(hasOneChild.content, is: .optional, ofType: .string), @@ -31,26 +38,26 @@ extension HasOneChild { .field(hasOneChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension HasOneChild: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == HasOneChild { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == HasOneChild { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild.swift index 20714ad8e0..1e37821e08 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,18 +14,24 @@ public struct HasOneChild: Model { public var content: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent+Schema.swift index c832500224..f4b24e8e1e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension HasOneParent { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension HasOneParent { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case child case createdAt case updatedAt case hasOneParentChildId } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let hasOneParent = HasOneParent.keys - + model.pluralName = "HasOneParents" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [hasOneParent.id]) ) - + model.fields( .field(hasOneParent.id, is: .required, ofType: .string), .hasOne(hasOneParent.child, is: .optional, ofType: HasOneChild.self, associatedWith: HasOneChild.keys.id, targetNames: ["hasOneParentChildId"]), @@ -33,29 +40,29 @@ extension HasOneParent { .field(hasOneParent.hasOneParentChildId, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension HasOneParent: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == HasOneParent { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == HasOneParent { + var id: FieldPath { + string("id") } - public var child: ModelPath { - HasOneChild.Path(name: "child", parent: self) + var child: ModelPath { + HasOneChild.Path(name: "child", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } - public var hasOneParentChildId: FieldPath { - string("hasOneParentChildId") + var hasOneParentChildId: FieldPath { + string("hasOneParentChildId") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent.swift index 887aedc67d..81931f3e97 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation public struct HasOneParent: Model { public let id: String - internal var _child: LazyReference + var _child: LazyReference public var child: HasOneChild? { get async throws { try await _child.get() @@ -13,21 +20,27 @@ public struct HasOneParent: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? public var hasOneParentChildId: String? - - public init(id: String = UUID().uuidString, - child: HasOneChild? = nil, - hasOneParentChildId: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + child: HasOneChild? = nil, + hasOneParentChildId: String? = nil + ) { + self.init( + id: id, child: child, createdAt: nil, updatedAt: nil, - hasOneParentChildId: hasOneParentChildId) + hasOneParentChildId: hasOneParentChildId + ) } - internal init(id: String = UUID().uuidString, - child: HasOneChild? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - hasOneParentChildId: String? = nil) { + init( + id: String = UUID().uuidString, + child: HasOneChild? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + hasOneParentChildId: String? = nil + ) { self.id = id self._child = LazyReference(child) self.createdAt = createdAt @@ -35,15 +48,15 @@ public struct HasOneParent: Model { self.hasOneParentChildId = hasOneParentChildId } public mutating func setChild(_ child: HasOneChild? = nil) { - self._child = LazyReference(child) + _child = LazyReference(child) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - _child = try values.decodeIfPresent(LazyReference.self, forKey: .child) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - hasOneParentChildId = try? values.decode(String?.self, forKey: .hasOneParentChildId) + self.id = try values.decode(String.self, forKey: .id) + self._child = try values.decodeIfPresent(LazyReference.self, forKey: .child) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.hasOneParentChildId = try? values.decode(String?.self, forKey: .hasOneParentChildId) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Comment14+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Comment14+Schema.swift index 422ce7ef12..266463d581 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Comment14+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Comment14+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post @@ -12,23 +19,23 @@ extension Comment14 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment14 = Comment14.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Comment14s" - + model.attributes( .primaryKey(fields: [comment14.id]) ) - + model.fields( .field(comment14.id, is: .required, ofType: .string), .field(comment14.content, is: .optional, ofType: .string), @@ -38,32 +45,32 @@ extension Comment14 { .field(comment14.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Comment14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Comment14 { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var post: ModelPath { - Post14.Path(name: "post", parent: self) + var post: ModelPath { + Post14.Path(name: "post", parent: self) } - public var author: ModelPath { - User14.Path(name: "author", parent: self) + var author: ModelPath { + User14.Path(name: "author", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Comment14.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Comment14.swift index cab42a6f0d..906b61dbe6 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Comment14.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Comment14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,38 +12,44 @@ import Foundation public struct Comment14: Model { public let id: String public var content: String? - internal var _post: LazyReference + var _post: LazyReference public var post: Post14? { - get async throws { + get async throws { try await _post.get() - } + } } - internal var _author: LazyReference + var _author: LazyReference public var author: User14 { - get async throws { + get async throws { try await _author.require() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post14? = nil, - author: User14) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post14? = nil, + author: User14 + ) { + self.init( + id: id, content: content, post: post, author: author, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post14? = nil, - author: User14, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post14? = nil, + author: User14, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -45,19 +58,19 @@ public struct Comment14: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post14? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public mutating func setAuthor(_ author: User14) { - self._author = LazyReference(author) + _author = LazyReference(author) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try? values.decode(String?.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - _author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try? values.decode(String?.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self._author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -68,4 +81,4 @@ public struct Comment14: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/GraphQLLazyLoadUserPostCommentTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/GraphQLLazyLoadUserPostCommentTests.swift index 74defd8e58..b40bcb66ff 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/GraphQLLazyLoadUserPostCommentTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/GraphQLLazyLoadUserPostCommentTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @@ -22,16 +22,16 @@ final class GraphQLLazyLoadUserPostCommentTests: GraphQLLazyLoadBaseTest { let user = User(username: "name") try await mutate(.create(user)) } - + func testSaveUserSettings() async throws { await setup(withModels: UserPostCommentModels()) let user = User(username: "name") let savedUser = try await mutate(.create(user)) - + let userSettings = UserSettings(language: "en-us", user: savedUser) try await mutate(.create(userSettings)) } - + func testSavePost() async throws { await setup(withModels: UserPostCommentModels()) let user = User(username: "name") @@ -39,18 +39,18 @@ final class GraphQLLazyLoadUserPostCommentTests: GraphQLLazyLoadBaseTest { let post = Post(title: "title", rating: 1, status: .active, author: savedUser) try await mutate(.create(post)) } - + func testSaveComment() async throws { await setup(withModels: UserPostCommentModels()) let user = User(username: "name") let savedUser = try await mutate(.create(user)) let post = Post(title: "title", rating: 1, status: .active, author: savedUser) let savedPost = try await mutate(.create(post)) - + let comment = Comment(content: "content", post: savedPost, author: savedUser) try await mutate(.create(comment)) } - + /// LazyLoad from queried models /// /// - Given: Created models @@ -69,7 +69,7 @@ final class GraphQLLazyLoadUserPostCommentTests: GraphQLLazyLoadBaseTest { let savedPost = try await mutate(.create(post)) let comment = Comment(content: "content", post: savedPost, author: savedUser) try await mutate(.create(comment)) - + // Traverse from User let queriedUser = try await query(for: user)! try await queriedUser.posts?.fetch() @@ -79,7 +79,7 @@ final class GraphQLLazyLoadUserPostCommentTests: GraphQLLazyLoadBaseTest { // Cannot traverse from User to settings since no FK is set on the User //let queriedUserSettings = try await queriedUser.settings //XCTAssertNotNil(queriedUserSettings) - + // Traverse from UserSettings let queriedSettings = try await query(for: userSettings)! let queriedSettingsUser = try await queriedSettings.user @@ -109,7 +109,7 @@ final class GraphQLLazyLoadUserPostCommentTests: GraphQLLazyLoadBaseTest { try await mutate(.delete(user)) try await assertModelDoesNotExist(user) } - + func testIncludesNestedModels() async throws { await setup(withModels: UserPostCommentModels()) let user = User(username: "name") @@ -120,11 +120,15 @@ final class GraphQLLazyLoadUserPostCommentTests: GraphQLLazyLoadBaseTest { let savedPost = try await mutate(.create(post)) let comment = Comment(content: "content", post: savedPost, author: savedUser) try await mutate(.create(comment)) - - guard let queriedUser = try await query(.get(User.self, - byIdentifier: user.id, - includes: { user in [user.comments, - user.posts] })) else { + + guard let queriedUser = try await query(.get( + User.self, + byIdentifier: user.id, + includes: { user in [ + user.comments, + user.posts + ] } + )) else { XCTFail("Could not perform nested query for User") return } @@ -144,10 +148,12 @@ final class GraphQLLazyLoadUserPostCommentTests: GraphQLLazyLoadBaseTest { comments = try await comments.getNextPage() } XCTAssertEqual(comments.count, 1) - - guard let queriedPost = try await query(.get(Post.self, - byIdentifier: post.id, - includes: { post in [post.author, post.comments] })) else { + + guard let queriedPost = try await query(.get( + Post.self, + byIdentifier: post.id, + includes: { post in [post.author, post.comments] } + )) else { XCTFail("Could not perform nested query for Post") return } @@ -160,28 +166,30 @@ final class GraphQLLazyLoadUserPostCommentTests: GraphQLLazyLoadBaseTest { queriedPostComments = try await queriedPostComments.getNextPage() } XCTAssertEqual(queriedPostComments.count, 1) - - guard let queriedComment = try await query(.get(Comment.self, - byIdentifier: comment.id, - includes: { comment in [comment.author, comment.post] })) else { + + guard let queriedComment = try await query(.get( + Comment.self, + byIdentifier: comment.id, + includes: { comment in [comment.author, comment.post] } + )) else { XCTFail("Could not perform nested query for Comment") return } assertLazyReference(queriedComment._author, state: .loaded(model: user)) assertLazyReference(queriedComment._post, state: .loaded(model: post)) } - + func testSaveUserWithUserSettings() async throws { await setup(withModels: UserPostCommentModels()) let user = User(username: "name") var savedUser = try await mutate(.create(user)) let userSettings = UserSettings(language: "en-us", user: savedUser) try await mutate(.create(userSettings)) - + // Update the User with the UserSettings (this is required for bi-directional has-one belongs-to) savedUser.setSettings(userSettings) try await mutate(.update(savedUser)) - + let queriedUser = try await query(for: user)! let queriedUserSettings = try await queriedUser.settings XCTAssertNotNil(queriedUserSettings) @@ -193,7 +201,7 @@ extension GraphQLLazyLoadUserPostCommentTests { typealias Post = Post14 typealias Comment = Comment14 typealias UserSettings = UserSettings14 - + struct UserPostCommentModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Post14+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Post14+Schema.swift index bf1baaa6c2..a9f698c3ef 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Post14+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Post14+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case rating @@ -14,23 +21,23 @@ extension Post14 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post14 = Post14.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Post14s" - + model.attributes( .primaryKey(fields: [post14.id]) ) - + model.fields( .field(post14.id, is: .required, ofType: .string), .field(post14.title, is: .required, ofType: .string), @@ -42,35 +49,35 @@ extension Post14 { .field(post14.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Post14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Post14 { + var id: FieldPath { + string("id") } - public var title: FieldPath { - string("title") + var title: FieldPath { + string("title") } - public var rating: FieldPath { - int("rating") + var rating: FieldPath { + int("rating") } - public var comments: ModelPath { - Comment14.Path(name: "comments", isCollection: true, parent: self) + var comments: ModelPath { + Comment14.Path(name: "comments", isCollection: true, parent: self) } - public var author: ModelPath { - User14.Path(name: "author", parent: self) + var author: ModelPath { + User14.Path(name: "author", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Post14.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Post14.swift index 42d308e637..c290b4e22e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Post14.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/Post14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,38 +15,44 @@ public struct Post14: Model { public var rating: Int public var status: PostStatus public var comments: List? - internal var _author: LazyReference + var _author: LazyReference public var author: User14 { - get async throws { + get async throws { try await _author.require() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - rating: Int, - status: PostStatus, - comments: List? = [], - author: User14) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + rating: Int, + status: PostStatus, + comments: List? = [], + author: User14 + ) { + self.init( + id: id, title: title, rating: rating, status: status, comments: comments, author: author, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - rating: Int, - status: PostStatus, - comments: List? = [], - author: User14, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + rating: Int, + status: PostStatus, + comments: List? = [], + author: User14, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.rating = rating @@ -50,18 +63,18 @@ public struct Post14: Model { self.updatedAt = updatedAt } public mutating func setAuthor(_ author: User14) { - self._author = LazyReference(author) + _author = LazyReference(author) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - title = try values.decode(String.self, forKey: .title) - rating = try values.decode(Int.self, forKey: .rating) - status = try values.decode(PostStatus.self, forKey: .status) - comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() - _author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.title = try values.decode(String.self, forKey: .title) + self.rating = try values.decode(Int.self, forKey: .rating) + self.status = try values.decode(PostStatus.self, forKey: .status) + self.comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() + self._author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -74,4 +87,4 @@ public struct Post14: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/PostStatus.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/PostStatus.swift index 47329501d1..39a6c7f3e4 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/PostStatus.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/PostStatus.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,4 +12,4 @@ import Foundation public enum PostStatus: String, EnumPersistable { case active = "ACTIVE" case inactive = "INACTIVE" -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/User14+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/User14+Schema.swift index 87ab652572..20e2acd13b 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/User14+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/User14+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension User14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension User14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case username case posts @@ -14,23 +21,23 @@ extension User14 { case updatedAt case user14SettingsId } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let user14 = User14.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "User14s" - + model.attributes( .primaryKey(fields: [user14.id]) ) - + model.fields( .field(user14.id, is: .required, ofType: .string), .field(user14.username, is: .required, ofType: .string), @@ -42,38 +49,38 @@ extension User14 { .field(user14.user14SettingsId, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension User14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == User14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == User14 { + var id: FieldPath { + string("id") } - public var username: FieldPath { - string("username") + var username: FieldPath { + string("username") } - public var posts: ModelPath { - Post14.Path(name: "posts", isCollection: true, parent: self) + var posts: ModelPath { + Post14.Path(name: "posts", isCollection: true, parent: self) } - public var comments: ModelPath { - Comment14.Path(name: "comments", isCollection: true, parent: self) + var comments: ModelPath { + Comment14.Path(name: "comments", isCollection: true, parent: self) } - public var settings: ModelPath { - UserSettings14.Path(name: "settings", parent: self) + var settings: ModelPath { + UserSettings14.Path(name: "settings", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } - public var user14SettingsId: FieldPath { - string("user14SettingsId") + var user14SettingsId: FieldPath { + string("user14SettingsId") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/User14.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/User14.swift index b65799b382..7e075a3776 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/User14.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/User14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,39 +14,45 @@ public struct User14: Model { public var username: String public var posts: List? public var comments: List? - internal var _settings: LazyReference + var _settings: LazyReference public var settings: UserSettings14? { - get async throws { + get async throws { try await _settings.get() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? public var user14SettingsId: String? - - public init(id: String = UUID().uuidString, - username: String, - posts: List? = [], - comments: List? = [], - settings: UserSettings14? = nil, - user14SettingsId: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + username: String, + posts: List? = [], + comments: List? = [], + settings: UserSettings14? = nil, + user14SettingsId: String? = nil + ) { + self.init( + id: id, username: username, posts: posts, comments: comments, settings: settings, createdAt: nil, updatedAt: nil, - user14SettingsId: user14SettingsId) + user14SettingsId: user14SettingsId + ) } - internal init(id: String = UUID().uuidString, - username: String, - posts: List? = [], - comments: List? = [], - settings: UserSettings14? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - user14SettingsId: String? = nil) { + init( + id: String = UUID().uuidString, + username: String, + posts: List? = [], + comments: List? = [], + settings: UserSettings14? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + user14SettingsId: String? = nil + ) { self.id = id self.username = username self.posts = posts @@ -50,18 +63,18 @@ public struct User14: Model { self.user14SettingsId = user14SettingsId } public mutating func setSettings(_ settings: UserSettings14? = nil) { - self._settings = LazyReference(settings) + _settings = LazyReference(settings) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - username = try values.decode(String.self, forKey: .username) - posts = try values.decodeIfPresent(List?.self, forKey: .posts) ?? .init() - comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() - _settings = try values.decodeIfPresent(LazyReference.self, forKey: .settings) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - user14SettingsId = try? values.decode(String?.self, forKey: .user14SettingsId) + self.id = try values.decode(String.self, forKey: .id) + self.username = try values.decode(String.self, forKey: .username) + self.posts = try values.decodeIfPresent(List?.self, forKey: .posts) ?? .init() + self.comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() + self._settings = try values.decodeIfPresent(LazyReference.self, forKey: .settings) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.user14SettingsId = try? values.decode(String?.self, forKey: .user14SettingsId) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -74,4 +87,4 @@ public struct User14: Model { try container.encode(updatedAt, forKey: .updatedAt) try container.encode(user14SettingsId, forKey: .user14SettingsId) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/UserSettings14+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/UserSettings14+Schema.swift index 1bc8bcd441..2e8f1dfa0a 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/UserSettings14+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/UserSettings14+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension UserSettings14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension UserSettings14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case language case user case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let userSettings14 = UserSettings14.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "UserSettings14s" - + model.attributes( .primaryKey(fields: [userSettings14.id]) ) - + model.fields( .field(userSettings14.id, is: .required, ofType: .string), .field(userSettings14.language, is: .optional, ofType: .string), @@ -36,29 +43,29 @@ extension UserSettings14 { .field(userSettings14.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension UserSettings14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == UserSettings14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == UserSettings14 { + var id: FieldPath { + string("id") } - public var language: FieldPath { - string("language") + var language: FieldPath { + string("language") } - public var user: ModelPath { - User14.Path(name: "user", parent: self) + var user: ModelPath { + User14.Path(name: "user", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/UserSettings14.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/UserSettings14.swift index b0e8cbf0ff..6cc8ae97ae 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/UserSettings14.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL14/UserSettings14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,29 +12,35 @@ import Foundation public struct UserSettings14: Model { public let id: String public var language: String? - internal var _user: LazyReference + var _user: LazyReference public var user: User14 { - get async throws { + get async throws { try await _user.require() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - language: String? = nil, - user: User14) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + language: String? = nil, + user: User14 + ) { + self.init( + id: id, language: language, user: user, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - language: String? = nil, - user: User14, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + language: String? = nil, + user: User14, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.language = language self._user = LazyReference(user) @@ -35,15 +48,15 @@ public struct UserSettings14: Model { self.updatedAt = updatedAt } public mutating func setUser(_ user: User14) { - self._user = LazyReference(user) + _user = LazyReference(user) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - language = try? values.decode(String?.self, forKey: .language) - _user = try values.decodeIfPresent(LazyReference.self, forKey: .user) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.language = try? values.decode(String?.self, forKey: .language) + self._user = try values.decodeIfPresent(LazyReference.self, forKey: .user) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -53,4 +66,4 @@ public struct UserSettings14: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/EnumTestModel+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/EnumTestModel+Schema.swift index 654c541c4a..a93f3181c2 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/EnumTestModel+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/EnumTestModel+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension EnumTestModel { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension EnumTestModel { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case enumVal case nullableEnumVal @@ -15,19 +22,19 @@ extension EnumTestModel { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let enumTestModel = EnumTestModel.keys - + model.pluralName = "EnumTestModels" - + model.attributes( .primaryKey(fields: [enumTestModel.id]) ) - + model.fields( .field(enumTestModel.id, is: .required, ofType: .string), .field(enumTestModel.enumVal, is: .required, ofType: .enum(type: TestEnum.self)), @@ -40,23 +47,23 @@ extension EnumTestModel { .field(enumTestModel.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension EnumTestModel: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == EnumTestModel { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == EnumTestModel { + var id: FieldPath { + string("id") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/EnumTestModel.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/EnumTestModel.swift index 57a45cd219..de9368dd4d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/EnumTestModel.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/EnumTestModel.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct EnumTestModel: Model { public var nullableEnumNullableList: [TestEnum?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - enumVal: TestEnum, - nullableEnumVal: TestEnum? = nil, - enumList: [TestEnum] = [], - enumNullableList: [TestEnum]? = nil, - nullableEnumList: [TestEnum?] = [], - nullableEnumNullableList: [TestEnum?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + enumVal: TestEnum, + nullableEnumVal: TestEnum? = nil, + enumList: [TestEnum] = [], + enumNullableList: [TestEnum]? = nil, + nullableEnumList: [TestEnum?] = [], + nullableEnumNullableList: [TestEnum?]? = nil + ) { + self.init( + id: id, enumVal: enumVal, nullableEnumVal: nullableEnumVal, enumList: enumList, @@ -28,17 +38,20 @@ public struct EnumTestModel: Model { nullableEnumList: nullableEnumList, nullableEnumNullableList: nullableEnumNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - enumVal: TestEnum, - nullableEnumVal: TestEnum? = nil, - enumList: [TestEnum] = [], - enumNullableList: [TestEnum]? = nil, - nullableEnumList: [TestEnum?] = [], - nullableEnumNullableList: [TestEnum?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + enumVal: TestEnum, + nullableEnumVal: TestEnum? = nil, + enumList: [TestEnum] = [], + enumNullableList: [TestEnum]? = nil, + nullableEnumList: [TestEnum?] = [], + nullableEnumNullableList: [TestEnum?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.enumVal = enumVal self.nullableEnumVal = nullableEnumVal @@ -49,4 +62,4 @@ public struct EnumTestModel: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListIntContainer+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListIntContainer+Schema.swift index 45a99508b6..77b79afd91 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListIntContainer+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListIntContainer+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ListIntContainer { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ListIntContainer { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case test case nullableInt @@ -15,19 +22,19 @@ extension ListIntContainer { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let listIntContainer = ListIntContainer.keys - + model.pluralName = "ListIntContainers" - + model.attributes( .primaryKey(fields: [listIntContainer.id]) ) - + model.fields( .field(listIntContainer.id, is: .required, ofType: .string), .field(listIntContainer.test, is: .required, ofType: .int), @@ -40,41 +47,41 @@ extension ListIntContainer { .field(listIntContainer.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ListIntContainer: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == ListIntContainer { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == ListIntContainer { + var id: FieldPath { + string("id") } - public var test: FieldPath { - int("test") + var test: FieldPath { + int("test") } - public var nullableInt: FieldPath { - int("nullableInt") + var nullableInt: FieldPath { + int("nullableInt") } - public var intList: FieldPath { - int("intList") + var intList: FieldPath { + int("intList") } - public var intNullableList: FieldPath { - int("intNullableList") + var intNullableList: FieldPath { + int("intNullableList") } - public var nullableIntList: FieldPath { - int("nullableIntList") + var nullableIntList: FieldPath { + int("nullableIntList") } - public var nullableIntNullableList: FieldPath { - int("nullableIntNullableList") + var nullableIntNullableList: FieldPath { + int("nullableIntNullableList") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListIntContainer.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListIntContainer.swift index 040edd16e8..efb53081d8 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListIntContainer.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListIntContainer.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct ListIntContainer: Model { public var nullableIntNullableList: [Int?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - test: Int, - nullableInt: Int? = nil, - intList: [Int] = [], - intNullableList: [Int]? = nil, - nullableIntList: [Int?] = [], - nullableIntNullableList: [Int?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + test: Int, + nullableInt: Int? = nil, + intList: [Int] = [], + intNullableList: [Int]? = nil, + nullableIntList: [Int?] = [], + nullableIntNullableList: [Int?]? = nil + ) { + self.init( + id: id, test: test, nullableInt: nullableInt, intList: intList, @@ -28,17 +38,20 @@ public struct ListIntContainer: Model { nullableIntList: nullableIntList, nullableIntNullableList: nullableIntNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - test: Int, - nullableInt: Int? = nil, - intList: [Int] = [], - intNullableList: [Int]? = nil, - nullableIntList: [Int?] = [], - nullableIntNullableList: [Int?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + test: Int, + nullableInt: Int? = nil, + intList: [Int] = [], + intNullableList: [Int]? = nil, + nullableIntList: [Int?] = [], + nullableIntNullableList: [Int?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.test = test self.nullableInt = nullableInt @@ -49,4 +62,4 @@ public struct ListIntContainer: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListStringContainer+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListStringContainer+Schema.swift index 151cfaf8c7..505e667481 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListStringContainer+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListStringContainer+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ListStringContainer { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ListStringContainer { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case test case nullableString @@ -15,19 +22,19 @@ extension ListStringContainer { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let listStringContainer = ListStringContainer.keys - + model.pluralName = "ListStringContainers" - + model.attributes( .primaryKey(fields: [listStringContainer.id]) ) - + model.fields( .field(listStringContainer.id, is: .required, ofType: .string), .field(listStringContainer.test, is: .required, ofType: .string), @@ -40,41 +47,41 @@ extension ListStringContainer { .field(listStringContainer.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ListStringContainer: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == ListStringContainer { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == ListStringContainer { + var id: FieldPath { + string("id") } - public var test: FieldPath { - string("test") + var test: FieldPath { + string("test") } - public var nullableString: FieldPath { - string("nullableString") + var nullableString: FieldPath { + string("nullableString") } - public var stringList: FieldPath { - string("stringList") + var stringList: FieldPath { + string("stringList") } - public var stringNullableList: FieldPath { - string("stringNullableList") + var stringNullableList: FieldPath { + string("stringNullableList") } - public var nullableStringList: FieldPath { - string("nullableStringList") + var nullableStringList: FieldPath { + string("nullableStringList") } - public var nullableStringNullableList: FieldPath { - string("nullableStringNullableList") + var nullableStringNullableList: FieldPath { + string("nullableStringNullableList") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListStringContainer.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListStringContainer.swift index cfe1107366..d08e28aa86 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListStringContainer.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ListStringContainer.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct ListStringContainer: Model { public var nullableStringNullableList: [String?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - test: String, - nullableString: String? = nil, - stringList: [String] = [], - stringNullableList: [String]? = nil, - nullableStringList: [String?] = [], - nullableStringNullableList: [String?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + test: String, + nullableString: String? = nil, + stringList: [String] = [], + stringNullableList: [String]? = nil, + nullableStringList: [String?] = [], + nullableStringNullableList: [String?]? = nil + ) { + self.init( + id: id, test: test, nullableString: nullableString, stringList: stringList, @@ -28,17 +38,20 @@ public struct ListStringContainer: Model { nullableStringList: nullableStringList, nullableStringNullableList: nullableStringNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - test: String, - nullableString: String? = nil, - stringList: [String] = [], - stringNullableList: [String]? = nil, - nullableStringList: [String?] = [], - nullableStringNullableList: [String?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + test: String, + nullableString: String? = nil, + stringList: [String] = [], + stringNullableList: [String]? = nil, + nullableStringList: [String?] = [], + nullableStringNullableList: [String?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.test = test self.nullableString = nullableString @@ -49,4 +62,4 @@ public struct ListStringContainer: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/Nested+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/Nested+Schema.swift index 1c83d051d7..d2cd8eeea4 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/Nested+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/Nested+Schema.swift @@ -1,25 +1,32 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Nested { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Nested { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case valueOne case valueTwo } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let nested = Nested.keys - + model.pluralName = "Nesteds" - + model.fields( .field(nested.valueOne, is: .optional, ofType: .int), .field(nested.valueTwo, is: .optional, ofType: .string) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/Nested.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/Nested.swift index 37415d4550..19da9762a3 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/Nested.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/Nested.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,4 +12,4 @@ import Foundation public struct Nested: Embeddable { var valueOne: Int? var valueTwo: String? -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/NestedTypeTestModel+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/NestedTypeTestModel+Schema.swift index a01c7c3046..e92577edf2 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/NestedTypeTestModel+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/NestedTypeTestModel+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension NestedTypeTestModel { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension NestedTypeTestModel { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case nestedVal case nullableNestedVal @@ -15,19 +22,19 @@ extension NestedTypeTestModel { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let nestedTypeTestModel = NestedTypeTestModel.keys - + model.pluralName = "NestedTypeTestModels" - + model.attributes( .primaryKey(fields: [nestedTypeTestModel.id]) ) - + model.fields( .field(nestedTypeTestModel.id, is: .required, ofType: .string), .field(nestedTypeTestModel.nestedVal, is: .required, ofType: .embedded(type: Nested.self)), @@ -40,23 +47,23 @@ extension NestedTypeTestModel { .field(nestedTypeTestModel.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension NestedTypeTestModel: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == NestedTypeTestModel { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == NestedTypeTestModel { + var id: FieldPath { + string("id") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/NestedTypeTestModel.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/NestedTypeTestModel.swift index 2167581607..bd5c875239 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/NestedTypeTestModel.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/NestedTypeTestModel.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct NestedTypeTestModel: Model { public var nullableNestedNullableList: [Nested?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - nestedVal: Nested, - nullableNestedVal: Nested? = nil, - nestedList: [Nested] = [], - nestedNullableList: [Nested]? = nil, - nullableNestedList: [Nested?] = [], - nullableNestedNullableList: [Nested?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + nestedVal: Nested, + nullableNestedVal: Nested? = nil, + nestedList: [Nested] = [], + nestedNullableList: [Nested]? = nil, + nullableNestedList: [Nested?] = [], + nullableNestedNullableList: [Nested?]? = nil + ) { + self.init( + id: id, nestedVal: nestedVal, nullableNestedVal: nullableNestedVal, nestedList: nestedList, @@ -28,17 +38,20 @@ public struct NestedTypeTestModel: Model { nullableNestedList: nullableNestedList, nullableNestedNullableList: nullableNestedNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - nestedVal: Nested, - nullableNestedVal: Nested? = nil, - nestedList: [Nested] = [], - nestedNullableList: [Nested]? = nil, - nullableNestedList: [Nested?] = [], - nullableNestedNullableList: [Nested?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + nestedVal: Nested, + nullableNestedVal: Nested? = nil, + nestedList: [Nested] = [], + nestedNullableList: [Nested]? = nil, + nullableNestedList: [Nested?] = [], + nullableNestedNullableList: [Nested?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.nestedVal = nestedVal self.nullableNestedVal = nullableNestedVal @@ -49,4 +62,4 @@ public struct NestedTypeTestModel: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ScalarContainer+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ScalarContainer+Schema.swift index a4db044062..0af1b206bc 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ScalarContainer+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ScalarContainer+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ScalarContainer { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ScalarContainer { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case myString case myInt @@ -22,19 +29,19 @@ extension ScalarContainer { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let scalarContainer = ScalarContainer.keys - + model.pluralName = "ScalarContainers" - + model.attributes( .primaryKey(fields: [scalarContainer.id]) ) - + model.fields( .field(scalarContainer.id, is: .required, ofType: .string), .field(scalarContainer.myString, is: .optional, ofType: .string), @@ -54,62 +61,62 @@ extension ScalarContainer { .field(scalarContainer.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ScalarContainer: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == ScalarContainer { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == ScalarContainer { + var id: FieldPath { + string("id") } - public var myString: FieldPath { - string("myString") + var myString: FieldPath { + string("myString") } - public var myInt: FieldPath { - int("myInt") + var myInt: FieldPath { + int("myInt") } - public var myDouble: FieldPath { - double("myDouble") + var myDouble: FieldPath { + double("myDouble") } - public var myBool: FieldPath { - bool("myBool") + var myBool: FieldPath { + bool("myBool") } - public var myDate: FieldPath { - date("myDate") + var myDate: FieldPath { + date("myDate") } - public var myTime: FieldPath { - time("myTime") + var myTime: FieldPath { + time("myTime") } - public var myDateTime: FieldPath { - datetime("myDateTime") + var myDateTime: FieldPath { + datetime("myDateTime") } - public var myTimeStamp: FieldPath { - int("myTimeStamp") + var myTimeStamp: FieldPath { + int("myTimeStamp") } - public var myEmail: FieldPath { - string("myEmail") + var myEmail: FieldPath { + string("myEmail") } - public var myJSON: FieldPath { - string("myJSON") + var myJSON: FieldPath { + string("myJSON") } - public var myPhone: FieldPath { - string("myPhone") + var myPhone: FieldPath { + string("myPhone") } - public var myURL: FieldPath { - string("myURL") + var myURL: FieldPath { + string("myURL") } - public var myIPAddress: FieldPath { - string("myIPAddress") + var myIPAddress: FieldPath { + string("myIPAddress") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ScalarContainer.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ScalarContainer.swift index 9559211652..ee87c57ecd 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ScalarContainer.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/ScalarContainer.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -19,22 +26,25 @@ public struct ScalarContainer: Model { public var myIPAddress: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - myString: String? = nil, - myInt: Int? = nil, - myDouble: Double? = nil, - myBool: Bool? = nil, - myDate: Temporal.Date? = nil, - myTime: Temporal.Time? = nil, - myDateTime: Temporal.DateTime? = nil, - myTimeStamp: Int? = nil, - myEmail: String? = nil, - myJSON: String? = nil, - myPhone: String? = nil, - myURL: String? = nil, - myIPAddress: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + myString: String? = nil, + myInt: Int? = nil, + myDouble: Double? = nil, + myBool: Bool? = nil, + myDate: Temporal.Date? = nil, + myTime: Temporal.Time? = nil, + myDateTime: Temporal.DateTime? = nil, + myTimeStamp: Int? = nil, + myEmail: String? = nil, + myJSON: String? = nil, + myPhone: String? = nil, + myURL: String? = nil, + myIPAddress: String? = nil + ) { + self.init( + id: id, myString: myString, myInt: myInt, myDouble: myDouble, @@ -49,24 +59,27 @@ public struct ScalarContainer: Model { myURL: myURL, myIPAddress: myIPAddress, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - myString: String? = nil, - myInt: Int? = nil, - myDouble: Double? = nil, - myBool: Bool? = nil, - myDate: Temporal.Date? = nil, - myTime: Temporal.Time? = nil, - myDateTime: Temporal.DateTime? = nil, - myTimeStamp: Int? = nil, - myEmail: String? = nil, - myJSON: String? = nil, - myPhone: String? = nil, - myURL: String? = nil, - myIPAddress: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + myString: String? = nil, + myInt: Int? = nil, + myDouble: Double? = nil, + myBool: Bool? = nil, + myDate: Temporal.Date? = nil, + myTime: Temporal.Time? = nil, + myDateTime: Temporal.DateTime? = nil, + myTimeStamp: Int? = nil, + myEmail: String? = nil, + myJSON: String? = nil, + myPhone: String? = nil, + myURL: String? = nil, + myIPAddress: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.myString = myString self.myInt = myInt @@ -84,4 +97,4 @@ public struct ScalarContainer: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/TestEnum.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/TestEnum.swift index 8c0fdf51ef..774eca554f 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/TestEnum.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL15/TestEnum.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,4 +12,4 @@ import Foundation public enum TestEnum: String, EnumPersistable { case valueOne = "VALUE_ONE" case valueTwo = "VALUE_TWO" -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Blog8V2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Blog8V2+Schema.swift index ebcfd4d9ec..d7c953a7f7 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Blog8V2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Blog8V2+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Blog8V2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Blog8V2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case customs @@ -13,19 +20,19 @@ extension Blog8V2 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let blog8V2 = Blog8V2.keys - + model.pluralName = "Blog8V2s" - + model.attributes( .primaryKey(fields: [blog8V2.id]) ) - + model.fields( .field(blog8V2.id, is: .required, ofType: .string), .field(blog8V2.name, is: .required, ofType: .string), @@ -36,10 +43,10 @@ extension Blog8V2 { .field(blog8V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Blog8V2: ModelIdentifiable { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Blog8V2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Blog8V2.swift index 53a81844ff..c317d9f8c3 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Blog8V2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Blog8V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -10,27 +17,33 @@ public struct Blog8V2: Model { public var posts: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [] + ) { + self.init( + id: id, name: name, customs: customs, notes: notes, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.customs = customs diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Comment8V2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Comment8V2+Schema.swift index 87e402536b..e512164a9e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Comment8V2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Comment8V2+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment8V2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment8V2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment8V2 = Comment8V2.keys - + model.pluralName = "Comment8V2s" - + model.attributes( .index(fields: ["postId"], name: "commentByPost"), .primaryKey(fields: [comment8V2.id]) ) - + model.fields( .field(comment8V2.id, is: .required, ofType: .string), .field(comment8V2.content, is: .optional, ofType: .string), @@ -33,10 +40,10 @@ extension Comment8V2 { .field(comment8V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment8V2: ModelIdentifiable { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Comment8V2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Comment8V2.swift index 8e82e35b6c..594d741eb3 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Comment8V2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Comment8V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Comment8V2: Model { public let id: String public var content: String? - internal var _post: LazyReference + var _post: LazyReference public var post: Post8V2? { get async throws { try await _post.get() @@ -13,21 +20,27 @@ public struct Comment8V2: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8V2? = nil) { - self.init(id: id, - content: content, - post: post, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8V2? = nil + ) { + self.init( + id: id, + content: content, + post: post, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct Comment8V2: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post8V2? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try? values.decode(String?.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try? values.decode(String?.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/GraphQLLazyLoadBlogPostComment8V2Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/GraphQLLazyLoadBlogPostComment8V2Tests.swift index 20b72550dd..8bca8f1934 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/GraphQLLazyLoadBlogPostComment8V2Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/GraphQLLazyLoadBlogPostComment8V2Tests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadBlogPostComment8V2Tests: GraphQLLazyLoadBaseTest { @@ -23,7 +23,7 @@ final class GraphQLLazyLoadBlogPostComment8V2Tests: GraphQLLazyLoadBaseTest { try await queriedBlog.posts?.fetch() assertList(queriedBlog.posts!, state: .isLoaded(count: 0)) } - + func testSavePost() async throws { await setup(withModels: BlogPostComment8V2Models()) let post = Post(name: "name", randomId: "randomId") @@ -32,55 +32,55 @@ final class GraphQLLazyLoadBlogPostComment8V2Tests: GraphQLLazyLoadBaseTest { assertList(queriedPost.comments!, state: .isNotLoaded(associatedIdentifiers: [post.id], associatedFields: ["post"])) try await queriedPost.comments?.fetch() assertList(queriedPost.comments!, state: .isLoaded(count: 0)) - + assertLazyReference(queriedPost._blog, state: .notLoaded(identifiers: nil)) } - + func testSaveBlogThenPost() async throws { await setup(withModels: BlogPostComment8V2Models()) let blog = Blog(name: "name") let createdBlog = try await mutate(.create(blog)) let post = Post(name: "name", randomId: "randomId", blog: blog) let createdPost = try await mutate(.create(post)) - + // the blog can load the posts assertList(createdBlog.posts!, state: .isNotLoaded(associatedIdentifiers: [blog.id], associatedFields: ["blog"])) try await createdBlog.posts?.fetch() assertList(createdBlog.posts!, state: .isLoaded(count: 1)) assertLazyReference(createdBlog.posts!.first!._blog, state: .notLoaded(identifiers: [.init(name: "id", value: blog.id)])) - + // the post can load the blog assertLazyReference(createdPost._blog, state: .notLoaded(identifiers: [.init(name: "id", value: blog.id)])) let loadedBlog = try await createdPost.blog! assertLazyReference(createdPost._blog, state: .loaded(model: loadedBlog)) assertList(loadedBlog.posts!, state: .isNotLoaded(associatedIdentifiers: [blog.id], associatedFields: ["blog"])) } - + func testSaveComment() async throws { await setup(withModels: BlogPostComment8V2Models()) let comment = Comment(content: "content") let createdComment = try await mutate(.create(comment)) assertLazyReference(createdComment._post, state: .notLoaded(identifiers: nil)) } - + func testSavePostComment() async throws { await setup(withModels: BlogPostComment8V2Models()) let post = Post(name: "name", randomId: "randomId") let createdPost = try await mutate(.create(post)) let comment = Comment(content: "content", post: post) let createdComment = try await mutate(.create(comment)) - + // the comment can load the post assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) let loadedPost = try await createdComment.post! assertList(loadedPost.comments!, state: .isNotLoaded(associatedIdentifiers: [post.id], associatedFields: ["post"])) - + // the post can load the comment assertList(createdPost.comments!, state: .isNotLoaded(associatedIdentifiers: [post.id], associatedFields: ["post"])) try await createdPost.comments?.fetch() assertList(createdPost.comments!, state: .isLoaded(count: 1)) } - + func testSaveBlogPostComment() async throws { await setup(withModels: BlogPostComment8V2Models()) let blog = Blog(name: "name") @@ -89,14 +89,14 @@ final class GraphQLLazyLoadBlogPostComment8V2Tests: GraphQLLazyLoadBaseTest { try await mutate(.create(post)) let comment = Comment(content: "content", post: post) let createdComment = try await mutate(.create(comment)) - + // the comment can load the post and load the blog assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) let loadedPost = try await createdComment.post! assertLazyReference(loadedPost._blog, state: .notLoaded(identifiers: [.init(name: "id", value: blog.id)])) let loadedBlog = try await loadedPost.blog! assertList(loadedBlog.posts!, state: .isNotLoaded(associatedIdentifiers: [blog.id], associatedFields: ["blog"])) - + // the blog can load the post and load the comment assertList(createdBlog.posts!, state: .isNotLoaded(associatedIdentifiers: [createdBlog.id], associatedFields: ["blog"])) try await createdBlog.posts?.fetch() @@ -105,43 +105,45 @@ final class GraphQLLazyLoadBlogPostComment8V2Tests: GraphQLLazyLoadBaseTest { try await loadedPost2.comments?.fetch() assertLazyReference(loadedPost2.comments!.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) } - + func testBlogIncludesPostAndPostIncludesBlog() async throws { await setup(withModels: BlogPostComment8V2Models()) let blog = Blog(name: "name") try await mutate(.create(blog)) let post = Post(name: "name", randomId: "randomId", blog: blog) try await mutate(.create(post)) - + // blog includes post - let queriedBlogWithPost = try await query(.get(Blog.self, - byIdentifier: blog.id, - includes: { blog in + let queriedBlogWithPost = try await query(.get( + Blog.self, + byIdentifier: blog.id, + includes: { blog in [blog.posts] - }))! + } + ))! assertList(queriedBlogWithPost.posts!, state: .isLoaded(count: 1)) - + // post includes blog let queriedPostWithBlog = try await query(.get(Post.self, byIdentifier: post.id, includes: { post in [post.blog] }))! assertLazyReference(queriedPostWithBlog._blog, state: .loaded(model: blog)) } - + func testPostIncludesCommentAndCommentIncludesPost() async throws { await setup(withModels: BlogPostComment8V2Models()) let post = Post(name: "name", randomId: "randomId") try await mutate(.create(post)) let comment = Comment(content: "content", post: post) try await mutate(.create(comment)) - + // post includes comment let queriedPostWithComment = try await query(.get(Post.self, byIdentifier: post.id, includes: { post in [post.comments]}))! assertList(queriedPostWithComment.comments!, state: .isLoaded(count: 1)) - + // comment includes post let queriedCommentWithPost = try await query(.get(Comment.self, byIdentifier: comment.id, includes: { comment in [comment.post] }))! assertLazyReference(queriedCommentWithPost._post, state: .loaded(model: post)) } - + func testBlogIncludesPostAndCommentAndCommentIncludesPostAndBlog() async throws { await setup(withModels: BlogPostComment8V2Models()) let blog = Blog(name: "name") @@ -150,23 +152,25 @@ final class GraphQLLazyLoadBlogPostComment8V2Tests: GraphQLLazyLoadBaseTest { try await mutate(.create(post)) let comment = Comment(content: "content", post: post) try await mutate(.create(comment)) - + // blog includes post and comment - let queriedBlogWithPostComment = try await query(.get(Blog.self, - byIdentifier: blog.id, - includes: { blog in + let queriedBlogWithPostComment = try await query(.get( + Blog.self, + byIdentifier: blog.id, + includes: { blog in [blog.posts.comments] - }))! + } + ))! assertList(queriedBlogWithPostComment.posts!, state: .isLoaded(count: 1)) assertList(queriedBlogWithPostComment.posts!.first!.comments!, state: .isLoaded(count: 1)) - + // comment includes post and blog let queriedCommentWithPostBlog = try await query(.get(Comment.self, byIdentifier: comment.id, includes: { comment in [comment.post.blog] }))! assertLazyReference(queriedCommentWithPostBlog._post, state: .loaded(model: post)) let loadedPost = try await queriedCommentWithPostBlog.post! assertLazyReference(loadedPost._blog, state: .loaded(model: blog)) } - + func testListBlogListPostsListComments() async throws { await setup(withModels: BlogPostComment8V2Models()) let blog = Blog(name: "name") @@ -175,40 +179,46 @@ final class GraphQLLazyLoadBlogPostComment8V2Tests: GraphQLLazyLoadBaseTest { try await mutate(.create(post)) let comment = Comment(content: "content", post: post) try await mutate(.create(comment)) - + let queriedBlogs = try await listQuery(.list(Blog.self, where: Blog.keys.id == blog.id)) assertList(queriedBlogs, state: .isLoaded(count: 1)) - assertList(queriedBlogs.first!.posts!, - state: .isNotLoaded(associatedIdentifiers: [blog.id], associatedFields: ["blog"])) - + assertList( + queriedBlogs.first!.posts!, + state: .isNotLoaded(associatedIdentifiers: [blog.id], associatedFields: ["blog"]) + ) + let queriedPosts = try await listQuery(.list(Post.self, where: Post.keys.id == post.id)) assertList(queriedPosts, state: .isLoaded(count: 1)) - assertList(queriedPosts.first!.comments!, - state: .isNotLoaded(associatedIdentifiers: [post.id], associatedFields: ["post"])) - + assertList( + queriedPosts.first!.comments!, + state: .isNotLoaded(associatedIdentifiers: [post.id], associatedFields: ["post"]) + ) + let queriedComments = try await listQuery(.list(Comment.self, where: Comment.keys.id == comment.id)) assertList(queriedComments, state: .isLoaded(count: 1)) - assertLazyReference(queriedComments.first!._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.id)])) + assertLazyReference( + queriedComments.first!._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.id)]) + ) } - + func testUpdate() { - + } - + func testDelete() { - + } } extension GraphQLLazyLoadBlogPostComment8V2Tests: DefaultLogger { } extension GraphQLLazyLoadBlogPostComment8V2Tests { - + typealias Blog = Blog8V2 typealias Post = Post8V2 typealias Comment = Comment8V2 - + struct BlogPostComment8V2Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyCustomModel8+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyCustomModel8+Schema.swift index 2c926d8ab8..b243eec04e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyCustomModel8+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyCustomModel8+Schema.swift @@ -1,24 +1,31 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension MyCustomModel8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension MyCustomModel8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case desc case children } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let myCustomModel8 = MyCustomModel8.keys - + model.pluralName = "MyCustomModel8s" - + model.fields( .field(myCustomModel8.id, is: .required, ofType: .string), .field(myCustomModel8.name, is: .required, ofType: .string), @@ -26,4 +33,4 @@ extension MyCustomModel8 { .field(myCustomModel8.children, is: .optional, ofType: .embeddedCollection(of: MyNestedModel8.self)) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyCustomModel8.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyCustomModel8.swift index 6fb7a2b02d..152b045540 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyCustomModel8.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyCustomModel8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,4 +14,4 @@ public struct MyCustomModel8: Embeddable { var name: String var desc: String? var children: [MyNestedModel8?]? -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyNestedModel8+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyNestedModel8+Schema.swift index da4f5f1040..871a8a25a7 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyNestedModel8+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyNestedModel8+Schema.swift @@ -1,27 +1,34 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension MyNestedModel8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension MyNestedModel8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case nestedName case notes } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let myNestedModel8 = MyNestedModel8.keys - + model.pluralName = "MyNestedModel8s" - + model.fields( .field(myNestedModel8.id, is: .required, ofType: .string), .field(myNestedModel8.nestedName, is: .required, ofType: .string), .field(myNestedModel8.notes, is: .optional, ofType: .embeddedCollection(of: String.self)) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyNestedModel8.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyNestedModel8.swift index 9884b8a197..6a99c2e543 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyNestedModel8.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/MyNestedModel8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -6,4 +13,4 @@ public struct MyNestedModel8: Embeddable { var id: String var nestedName: String var notes: [String?]? -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Post8V2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Post8V2+Schema.swift index b9b747cba9..8e93eccf7e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Post8V2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Post8V2+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post8V2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post8V2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case randomId @@ -13,21 +20,21 @@ extension Post8V2 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post8V2 = Post8V2.keys - + model.pluralName = "Post8V2s" - + model.attributes( .index(fields: ["blogId"], name: "postByBlog"), .index(fields: ["randomId"], name: "byRandom"), .primaryKey(fields: [post8V2.id]) ) - + model.fields( .field(post8V2.id, is: .required, ofType: .string), .field(post8V2.name, is: .required, ofType: .string), @@ -38,10 +45,10 @@ extension Post8V2 { .field(post8V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post8V2: ModelIdentifiable { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Post8V2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Post8V2.swift index 7e5805afb9..9d416ecf23 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Post8V2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL2/Post8V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -6,7 +13,7 @@ public struct Post8V2: Model { public let id: String public var name: String public var randomId: String? - internal var _blog: LazyReference + var _blog: LazyReference public var blog: Blog8V2? { get async throws { try await _blog.get() @@ -15,27 +22,33 @@ public struct Post8V2: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8V2? = nil, - comments: List? = []) { - self.init(id: id, - name: name, - randomId: randomId, - blog: blog, - comments: comments, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8V2? = nil, + comments: List? = [] + ) { + self.init( + id: id, + name: name, + randomId: randomId, + blog: blog, + comments: comments, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8V2? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8V2? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.randomId = randomId @@ -45,17 +58,17 @@ public struct Post8V2: Model { self.updatedAt = updatedAt } public mutating func setBlog(_ blog: Blog8V2? = nil) { - self._blog = LazyReference(blog) + _blog = LazyReference(blog) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - name = try values.decode(String.self, forKey: .name) - randomId = try? values.decode(String?.self, forKey: .randomId) - _blog = try values.decodeIfPresent(LazyReference.self, forKey: .blog) ?? LazyReference(identifiers: nil) - comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.name = try values.decode(String.self, forKey: .name) + self.randomId = try? values.decode(String?.self, forKey: .randomId) + self._blog = try values.decodeIfPresent(LazyReference.self, forKey: .blog) ?? LazyReference(identifiers: nil) + self.comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/CommentWithCompositeKey+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/CommentWithCompositeKey+Schema.swift index 9b70a40965..d5835f7876 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/CommentWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/CommentWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CommentWithCompositeKey { +public extension CommentWithCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let commentWithCompositeKey = CommentWithCompositeKey.keys - + model.pluralName = "CommentWithCompositeKeys" - + model.attributes( .index(fields: ["id", "content"], name: nil), .primaryKey(fields: [commentWithCompositeKey.id, commentWithCompositeKey.content]) ) - + model.fields( .field(commentWithCompositeKey.id, is: .required, ofType: .string), .field(commentWithCompositeKey.content, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension CommentWithCompositeKey { .field(commentWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension CommentWithCompositeKey: ModelIdentifiable { @@ -43,26 +50,28 @@ extension CommentWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CommentWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - content: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "content", value: content)]) +public extension CommentWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + content: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "content", value: content)]) } } -extension ModelPath where ModelType == CommentWithCompositeKey { - public var id: FieldPath { +public extension ModelPath where ModelType == CommentWithCompositeKey { + var id: FieldPath { string("id") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var post: ModelPath { + var post: ModelPath { PostWithCompositeKey.Path(name: "post", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/CommentWithCompositeKey.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/CommentWithCompositeKey.swift index c3db0086aa..7e483fc203 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/CommentWithCompositeKey.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/CommentWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct CommentWithCompositeKey: Model { public let id: String public let content: String - internal var _post: LazyReference + var _post: LazyReference public var post: PostWithCompositeKey? { get async throws { try await _post.get() @@ -13,21 +20,27 @@ public struct CommentWithCompositeKey: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKey? = nil) { - self.init(id: id, - content: content, - post: post, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKey? = nil + ) { + self.init( + id: id, + content: content, + post: post, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKey? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKey? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct CommentWithCompositeKey: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: PostWithCompositeKey? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try values.decode(String.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try values.decode(String.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/GraphQLLazyLoadPostCommentWithCompositeKeyTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/GraphQLLazyLoadPostCommentWithCompositeKeyTests.swift index b3ae40b05c..f9320aa326 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/GraphQLLazyLoadPostCommentWithCompositeKeyTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/GraphQLLazyLoadPostCommentWithCompositeKeyTests.swift @@ -5,49 +5,55 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBaseTest { func testSave() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) - + let post = Post(title: "title") let comment = Comment(content: "content", post: post) let savedPost = try await mutate(.create(post)) let savedComment = try await mutate(.create(comment)) } - + func testCommentWithLazyLoadPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) - + let post = Post(title: "title") let comment = Comment(content: "content", post: post) let createdPost = try await mutate(.create(post)) let createdComment = try await mutate(.create(comment)) - + // The comment's post should not be loaded, since no `includes` is passed in. // And the codegenerated swift models have the new modelPath properties. - assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: createdPost.id), - .init(name: "title", value: createdPost.title)])) + assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: createdPost.id), + .init(name: "title", value: createdPost.title) + ])) let loadedPost = try await createdComment.post! XCTAssertEqual(loadedPost.id, createdPost.id) - + // The loaded post should have comments that are also not loaded let comments = loadedPost.comments! - assertList(comments, state: .isNotLoaded(associatedIdentifiers: [post.id, post.title], - associatedFields: ["post"])) + assertList(comments, state: .isNotLoaded( + associatedIdentifiers: [post.id, post.title], + associatedFields: ["post"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) - assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: createdPost.id), - .init(name: "title", value: createdPost.title)])) + assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: createdPost.id), + .init(name: "title", value: createdPost.title) + ])) } - + // With `includes` on `comment.post`, the comment's post should be eager loaded. func testCommentWithEagerLoadPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) @@ -61,16 +67,20 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase XCTAssertEqual(loadedPost.id, post.id) // The loaded post should have comments that are not loaded let comments = loadedPost.comments! - assertList(comments, state: .isNotLoaded(associatedIdentifiers: [post.id, post.title], - associatedFields: ["post"])) + assertList(comments, state: .isNotLoaded( + associatedIdentifiers: [post.id, post.title], + associatedFields: ["post"] + )) // load the comments try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) // further nested models should not be loaded - assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: createdPost.id), - .init(name: "title", value: createdPost.title)])) + assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: createdPost.id), + .init(name: "title", value: createdPost.title) + ])) } - + // With `includes` on `comment.post.comments`, func testCommentWithEagerLoadPostAndPostComments() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) @@ -118,10 +128,12 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase let comments = loadedPost.comments! assertList(comments, state: .isLoaded(count: 1)) // further nested models should not be loaded - assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) + assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) } - + // Without `includes` and latest codegenerated types with the model path, the post's comments should be lazy loaded func testPostWithLazyLoadComments() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) @@ -134,10 +146,12 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase assertList(comments, state: .isNotLoaded(associatedIdentifiers: [post.id, post.title], associatedFields: ["post"])) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) - assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) + assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) } - + // With `includes` on `post.comments` should eager load the post's comments func testPostWithEagerLoadComments() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) @@ -148,10 +162,12 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase let queriedPost = try await query(.get(Post.self, byIdentifier: .identifier(id: post.id, title: post.title), includes: { post in [post.comments]}))! let comments = queriedPost.comments! assertList(comments, state: .isLoaded(count: 1)) - assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) + assertLazyReference(comments.first!._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) } - + // With `includes` on `post.comments.post` should eager load the post's comments' post func testPostWithEagerLoadCommentsAndPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) @@ -159,35 +175,44 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase let comment = Comment(content: "content", post: post) let createdPost = try await mutate(.create(post)) _ = try await mutate(.create(comment)) - let queriedPost = try await query(.get(Post.self, - byIdentifier: .identifier(id: post.id, - title: post.title), - includes: { post in [post.comments.post]}))! + let queriedPost = try await query(.get( + Post.self, + byIdentifier: .identifier( + id: post.id, + title: post.title + ), + includes: { post in [post.comments.post]} + ))! let comments = queriedPost.comments! assertList(comments, state: .isLoaded(count: 1)) assertLazyReference(comments.first!._post, state: .loaded(model: createdPost)) } - + func testListPostsListComments() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") let comment = Comment(content: "content", post: post) try await mutate(.create(post)) try await mutate(.create(comment)) - + let queriedPosts = try await listQuery(.list(Post.self, where: Post.keys.id == post.id)) assertList(queriedPosts, state: .isLoaded(count: 1)) - assertList(queriedPosts.first!.comments!, - state: .isNotLoaded(associatedIdentifiers: [post.id, post.title], associatedFields: ["post"])) - + assertList( + queriedPosts.first!.comments!, + state: .isNotLoaded(associatedIdentifiers: [post.id, post.title], associatedFields: ["post"]) + ) + let queriedComments = try await listQuery(.list(Comment.self, where: Comment.keys.id == comment.id)) assertList(queriedComments, state: .isLoaded(count: 1)) - assertLazyReference(queriedComments.first!._post, - state: .notLoaded(identifiers: [ - .init(name: "id", value: post.id), - .init(name: "title", value: "title")])) + assertLazyReference( + queriedComments.first!._post, + state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: "title") + ]) + ) } - + func testCreateWithoutPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let comment = Comment(content: "content") @@ -198,18 +223,28 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase let createdPost = try await mutate(.create(post)) queriedComment.setPost(createdPost) let updateCommentWithPost = try await mutate(.update(queriedComment)) - let queriedCommentAfterUpdate = try await query(.get(Comment.self, - byIdentifier: .identifier(id: updateCommentWithPost.id, - content: updateCommentWithPost.content)))! - assertLazyReference(queriedCommentAfterUpdate._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) - let queriedCommentWithPost = try await query(.get(Comment.self, - byIdentifier: .identifier(id: queriedCommentAfterUpdate.id, - content: queriedCommentAfterUpdate.content), - includes: { comment in [comment.post]}))! + let queriedCommentAfterUpdate = try await query(.get( + Comment.self, + byIdentifier: .identifier( + id: updateCommentWithPost.id, + content: updateCommentWithPost.content + ) + ))! + assertLazyReference(queriedCommentAfterUpdate._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) + let queriedCommentWithPost = try await query(.get( + Comment.self, + byIdentifier: .identifier( + id: queriedCommentAfterUpdate.id, + content: queriedCommentAfterUpdate.content + ), + includes: { comment in [comment.post]} + ))! assertLazyReference(queriedCommentWithPost._post, state: .loaded(model: createdPost)) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") @@ -217,25 +252,37 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase try await mutate(.create(post)) try await mutate(.create(comment)) var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(id: comment.id, content: comment.content)))! - assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) - + assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) + let newPost = Post(title: "title") let createdNewPost = try await mutate(.create(newPost)) queriedComment.setPost(newPost) let updateCommentWithPost = try await mutate(.update(queriedComment)) - let queriedCommentAfterUpdate = try await query(.get(Comment.self, - byIdentifier: .identifier(id: updateCommentWithPost.id, - content: updateCommentWithPost.content)))! - assertLazyReference(queriedCommentAfterUpdate._post, state: .notLoaded(identifiers: [.init(name: "id", value: newPost.id), - .init(name: "title", value: newPost.title)])) - let queriedCommentWithPost = try await query(.get(Comment.self, - byIdentifier: .identifier(id: queriedCommentAfterUpdate.id, - content: queriedCommentAfterUpdate.content), - includes: { comment in [comment.post]}))! + let queriedCommentAfterUpdate = try await query(.get( + Comment.self, + byIdentifier: .identifier( + id: updateCommentWithPost.id, + content: updateCommentWithPost.content + ) + ))! + assertLazyReference(queriedCommentAfterUpdate._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: newPost.id), + .init(name: "title", value: newPost.title) + ])) + let queriedCommentWithPost = try await query(.get( + Comment.self, + byIdentifier: .identifier( + id: queriedCommentAfterUpdate.id, + content: queriedCommentAfterUpdate.content + ), + includes: { comment in [comment.post]} + ))! assertLazyReference(queriedCommentWithPost._post, state: .loaded(model: createdNewPost)) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") @@ -243,22 +290,24 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase try await mutate(.create(post)) try await mutate(.create(comment)) var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(id: comment.id, content: comment.content)))! - assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) - + assertLazyReference(queriedComment._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) + queriedComment.setPost(nil) let updateCommentRemovePost = try await mutate(.update(queriedComment)) let queriedCommentAfterUpdate = try await query(.get(Comment.self, byIdentifier: .identifier(id: updateCommentRemovePost.id, content: updateCommentRemovePost.content)))! assertLazyReference(queriedCommentAfterUpdate._post, state: .notLoaded(identifiers: nil)) } - + func testDelete() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") let comment = Comment(content: "content", post: post) let createdPost = try await mutate(.create(post)) try await mutate(.create(comment)) - + try await mutate(.delete(createdPost)) let queriedPost = try await query(.get(Post.self, byIdentifier: .identifier(id: post.id, title: post.title))) XCTAssertNil(queriedPost) @@ -268,7 +317,7 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase let queryDeletedComment = try await query(.get(Comment.self, byIdentifier: .identifier(id: comment.id, content: comment.content))) XCTAssertNil(queryDeletedComment) } - + func testSubscribeToComments() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") @@ -289,8 +338,10 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase switch result { case .success(let createdComment): log.verbose("Successfully got createdComment from subscription: \(createdComment)") - assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [.init(name: "id", value: post.id), - .init(name: "title", value: post.title)])) + assertLazyReference(createdComment._post, state: .notLoaded(identifiers: [ + .init(name: "id", value: post.id), + .init(name: "title", value: post.title) + ])) onCreatedComment.fulfill() case .failure(let error): XCTFail("Got failed result with \(error.errorDescription)") @@ -301,14 +352,14 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) let comment = Comment(content: "content", post: post) try await mutate(.create(comment)) await fulfillment(of: [onCreatedComment], timeout: 10) subscription.cancel() } - + // The identical `includes` parameter should be used because the selection set of the mutation // has to match the selection set of the subscription. func testSubscribeToCommentsIncludesPost() async throws { @@ -317,9 +368,11 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase try await mutate(.create(post)) let connected = expectation(description: "subscription connected") let onCreatedComment = expectation(description: "onCreatedComment received") - let subscriptionIncludes = Amplify.API.subscribe(request: .subscription(of: Comment.self, - type: .onCreate, - includes: { comment in [comment.post]})) + let subscriptionIncludes = Amplify.API.subscribe(request: .subscription( + of: Comment.self, + type: .onCreate, + includes: { comment in [comment.post]} + )) Task { do { for try await subscriptionEvent in subscriptionIncludes { @@ -344,18 +397,18 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 20) let comment = Comment(content: "content", post: post) try await mutate(.create(comment, includes: { comment in [comment.post] })) await fulfillment(of: [onCreatedComment], timeout: 20) subscriptionIncludes.cancel() } - + func testSubscribeToPosts() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") - + let connected = expectation(description: "subscription connected") let onCreatedPost = expectation(description: "onCreatedPost received") let subscription = Amplify.API.subscribe(request: .subscription(of: Post.self, type: .onCreate)) @@ -383,22 +436,24 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) try await mutate(.create(post)) await fulfillment(of: [onCreatedPost], timeout: 10) subscription.cancel() } - + func testSubscribeToPostsIncludes() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") - + let connected = expectation(description: "subscription connected") let onCreatedPost = expectation(description: "onCreatedPost received") - let subscriptionIncludes = Amplify.API.subscribe(request: .subscription(of: Post.self, - type: .onCreate, - includes: { post in [post.comments]})) + let subscriptionIncludes = Amplify.API.subscribe(request: .subscription( + of: Post.self, + type: .onCreate, + includes: { post in [post.comments]} + )) Task { do { for try await subscriptionEvent in subscriptionIncludes { @@ -423,7 +478,7 @@ final class GraphQLLazyLoadPostCommentWithCompositeKeyTests: GraphQLLazyLoadBase XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) try await mutate(.create(post, includes: { post in [post.comments]})) await fulfillment(of: [onCreatedPost], timeout: 10) @@ -436,7 +491,7 @@ extension GraphQLLazyLoadPostCommentWithCompositeKeyTests: DefaultLogger { } extension GraphQLLazyLoadPostCommentWithCompositeKeyTests { typealias Post = PostWithCompositeKey typealias Comment = CommentWithCompositeKey - + struct PostCommentWithCompositeKeyModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/PostWithCompositeKey+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/PostWithCompositeKey+Schema.swift index 04c89f21f1..a7061afc79 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/PostWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/PostWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithCompositeKey { +public extension PostWithCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let postWithCompositeKey = PostWithCompositeKey.keys - + model.pluralName = "PostWithCompositeKeys" - + model.attributes( .index(fields: ["id", "title"], name: nil), .primaryKey(fields: [postWithCompositeKey.id, postWithCompositeKey.title]) ) - + model.fields( .field(postWithCompositeKey.id, is: .required, ofType: .string), .field(postWithCompositeKey.title, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension PostWithCompositeKey { .field(postWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PostWithCompositeKey: ModelIdentifiable { @@ -43,26 +50,28 @@ extension PostWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - title: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "title", value: title)]) +public extension PostWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + title: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "title", value: title)]) } } -extension ModelPath where ModelType == PostWithCompositeKey { - public var id: FieldPath { +public extension ModelPath where ModelType == PostWithCompositeKey { + var id: FieldPath { string("id") } - public var title: FieldPath { + var title: FieldPath { string("title") } - public var comments: ModelPath { + var comments: ModelPath { CommentWithCompositeKey.Path(name: "comments", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/PostWithCompositeKey.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/PostWithCompositeKey.swift index e9de7de986..ac441cae5d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/PostWithCompositeKey.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL3/PostWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithCompositeKey: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/GraphQLLazyLoadPostTagTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/GraphQLLazyLoadPostTagTests.swift index 2448dc2970..c0353c5e7c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/GraphQLLazyLoadPostTagTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/GraphQLLazyLoadPostTagTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadPostTagTests: GraphQLLazyLoadBaseTest { - + func testLazyLoad() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -22,11 +22,11 @@ final class GraphQLLazyLoadPostTagTests: GraphQLLazyLoadBaseTest { let savedPost = try await mutate(.create(post)) let savedTag = try await mutate(.create(tag)) let savedPostTag = try await mutate(.create(postTag)) - + try await assertPost(savedPost, canLazyLoad: savedPostTag) try await assertTag(savedTag, canLazyLoad: savedPostTag) try await assertPostTag(savedPostTag, canLazyLoadTag: savedTag, canLazyLoadPost: savedPost) - + let queriedPost = try await query(.get(Post.self, byIdentifier: .identifier(postId: post.postId, title: post.title)))! try await assertPost(queriedPost, canLazyLoad: savedPostTag) let queriedTag = try await query(for: savedTag)! @@ -54,39 +54,51 @@ final class GraphQLLazyLoadPostTagTests: GraphQLLazyLoadBaseTest { """ XCTAssertEqual(request.document, expectedDocument) let queriedPostTag = try await query(request)! - + try await assertPostTag(queriedPostTag, canLazyLoadTag: savedTag, canLazyLoadPost: savedPost) } - - func assertPost(_ post: Post, - canLazyLoad postTag: PostTag) async throws { + + func assertPost( + _ post: Post, + canLazyLoad postTag: PostTag + ) async throws { guard let postTags = post.tags else { XCTFail("Missing postTags on post") return } - assertList(postTags, state: .isNotLoaded(associatedIdentifiers: [post.postId, post.title], - associatedFields: ["postWithTagsCompositeKey"])) + assertList(postTags, state: .isNotLoaded( + associatedIdentifiers: [post.postId, post.title], + associatedFields: ["postWithTagsCompositeKey"] + )) try await postTags.fetch() assertList(postTags, state: .isLoaded(count: 1)) } - - func assertTag(_ tag: Tag, - canLazyLoad postTag: PostTag) async throws { + + func assertTag( + _ tag: Tag, + canLazyLoad postTag: PostTag + ) async throws { guard let postTags = tag.posts else { XCTFail("Missing postTags on post") return } - assertList(postTags, state: .isNotLoaded(associatedIdentifiers: [tag.id, tag.name], - associatedFields: ["tagWithCompositeKey"])) + assertList(postTags, state: .isNotLoaded( + associatedIdentifiers: [tag.id, tag.name], + associatedFields: ["tagWithCompositeKey"] + )) try await postTags.fetch() assertList(postTags, state: .isLoaded(count: 1)) } - + func assertPostTag(_ postTag: PostTag, canLazyLoadTag tag: Tag, canLazyLoadPost post: Post) async throws { - assertLazyReference(postTag._tagWithCompositeKey, state: .notLoaded(identifiers: [.init(name: "id", value: tag.id), - .init(name: "name", value: tag.name)])) - assertLazyReference(postTag._postWithTagsCompositeKey, state: .notLoaded(identifiers: [.init(name: "postId", value: post.postId), - .init(name: "title", value: post.title)])) + assertLazyReference(postTag._tagWithCompositeKey, state: .notLoaded(identifiers: [ + .init(name: "id", value: tag.id), + .init(name: "name", value: tag.name) + ])) + assertLazyReference(postTag._postWithTagsCompositeKey, state: .notLoaded(identifiers: [ + .init(name: "postId", value: post.postId), + .init(name: "title", value: post.title) + ])) let loadedTag = try await postTag.tagWithCompositeKey assertLazyReference(postTag._tagWithCompositeKey, state: .loaded(model: loadedTag)) try await assertTag(loadedTag, canLazyLoad: postTag) @@ -94,7 +106,7 @@ final class GraphQLLazyLoadPostTagTests: GraphQLLazyLoadBaseTest { assertLazyReference(postTag._postWithTagsCompositeKey, state: .loaded(model: loadedPost)) try await assertPost(loadedPost, canLazyLoad: postTag) } - + func testIncludesNestedModel() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -103,11 +115,15 @@ final class GraphQLLazyLoadPostTagTests: GraphQLLazyLoadBaseTest { try await mutate(.create(post)) try await mutate(.create(tag)) try await mutate(.create(postTag)) - - guard let queriedPost = try await query(.get(Post.self, - byIdentifier: .identifier(postId: post.postId, - title: post.title), - includes: { post in [post.tags] })) else { + + guard let queriedPost = try await query(.get( + Post.self, + byIdentifier: .identifier( + postId: post.postId, + title: post.title + ), + includes: { post in [post.tags] } + )) else { XCTFail("Could not perform nested query for Post") return } @@ -119,11 +135,15 @@ final class GraphQLLazyLoadPostTagTests: GraphQLLazyLoadBaseTest { tags = try await tags.getNextPage() } XCTAssertEqual(tags.count, 1) - - guard let queriedTag = try await query(.get(Tag.self, - byIdentifier: .identifier(id: tag.id, - name: tag.name), - includes: { tag in [tag.posts] })) else { + + guard let queriedTag = try await query(.get( + Tag.self, + byIdentifier: .identifier( + id: tag.id, + name: tag.name + ), + includes: { tag in [tag.posts] } + )) else { XCTFail("Could not perform nested query for Tag") return } @@ -135,20 +155,23 @@ final class GraphQLLazyLoadPostTagTests: GraphQLLazyLoadBaseTest { posts = try await posts.getNextPage() } XCTAssertEqual(posts.count, 1) - - guard let queriedPostTag = try await query(.get(PostTag.self, - byIdentifier: postTag.id, - includes: { postTag in [ - postTag.postWithTagsCompositeKey, - postTag.tagWithCompositeKey] })) else { + + guard let queriedPostTag = try await query(.get( + PostTag.self, + byIdentifier: postTag.id, + includes: { postTag in [ + postTag.postWithTagsCompositeKey, + postTag.tagWithCompositeKey + ] } + )) else { XCTFail("Could not perform nested query for PostTag") return } - + assertLazyReference(queriedPostTag._postWithTagsCompositeKey, state: .loaded(model: post)) assertLazyReference(queriedPostTag._tagWithCompositeKey, state: .loaded(model: tag)) } - + func testListPostListTagListPostTag() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -157,29 +180,39 @@ final class GraphQLLazyLoadPostTagTests: GraphQLLazyLoadBaseTest { try await mutate(.create(post)) try await mutate(.create(tag)) try await mutate(.create(postTag)) - + let queriedPosts = try await listQuery(.list(Post.self, where: Post.keys.postId == post.postId)) assertList(queriedPosts, state: .isLoaded(count: 1)) - assertList(queriedPosts.first!.tags!, - state: .isNotLoaded(associatedIdentifiers: [post.postId, post.title], associatedFields: ["postWithTagsCompositeKey"])) - + assertList( + queriedPosts.first!.tags!, + state: .isNotLoaded(associatedIdentifiers: [post.postId, post.title], associatedFields: ["postWithTagsCompositeKey"]) + ) + let queriedTags = try await listQuery(.list(Tag.self, where: Tag.keys.id == tag.id)) assertList(queriedTags, state: .isLoaded(count: 1)) - assertList(queriedTags.first!.posts!, - state: .isNotLoaded(associatedIdentifiers: [tag.id, tag.name], associatedFields: ["tagWithCompositeKey"])) - + assertList( + queriedTags.first!.posts!, + state: .isNotLoaded(associatedIdentifiers: [tag.id, tag.name], associatedFields: ["tagWithCompositeKey"]) + ) + let queriedPostTags = try await listQuery(.list(PostTag.self, where: PostTag.keys.id == postTag.id)) assertList(queriedPostTags, state: .isLoaded(count: 1)) - assertLazyReference(queriedPostTags.first!._postWithTagsCompositeKey, - state: .notLoaded(identifiers: [ - .init(name: "postId", value: post.postId), - .init(name: "title", value: post.title)])) - assertLazyReference(queriedPostTags.first!._tagWithCompositeKey, - state: .notLoaded(identifiers: [ - .init(name: "id", value: tag.id), - .init(name: "name", value: tag.name)])) + assertLazyReference( + queriedPostTags.first!._postWithTagsCompositeKey, + state: .notLoaded(identifiers: [ + .init(name: "postId", value: post.postId), + .init(name: "title", value: post.title) + ]) + ) + assertLazyReference( + queriedPostTags.first!._tagWithCompositeKey, + state: .notLoaded(identifiers: [ + .init(name: "id", value: tag.id), + .init(name: "name", value: tag.name) + ]) + ) } - + func testUpdate() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -188,7 +221,7 @@ final class GraphQLLazyLoadPostTagTests: GraphQLLazyLoadBaseTest { let savedPost = try await mutate(.create(post)) let savedTag = try await mutate(.create(tag)) let savedPostTag = try await mutate(.create(postTag)) - + // update the post tag with a new post var queriedPostTag = try await query(for: savedPostTag)! let newPost = Post(postId: UUID().uuidString, title: "title") @@ -198,7 +231,7 @@ final class GraphQLLazyLoadPostTagTests: GraphQLLazyLoadBaseTest { assertLazyReference(savedPostTagWithNewPost._postWithTagsCompositeKey, state: .loaded(model: newPost)) let queriedPreviousPost = try await query(for: post)! try await assertPostWithNoPostTag(queriedPreviousPost) - + // update the post tag with a new tag var queriedPostTagWithNewPost = try await query(for: savedPostTagWithNewPost)! let newTag = Tag(name: "name") @@ -209,47 +242,51 @@ final class GraphQLLazyLoadPostTagTests: GraphQLLazyLoadBaseTest { let queriedPreviousTag = try await query(for: savedTag)! try await assertTagWithNoPostTag(queriedPreviousTag) } - + func assertPostWithNoPostTag(_ post: Post) async throws { guard let postTags = post.tags else { XCTFail("Missing postTags on post") return } - assertList(postTags, state: .isNotLoaded(associatedIdentifiers: [post.postId, post.title], - associatedFields: ["postWithTagsCompositeKey"])) + assertList(postTags, state: .isNotLoaded( + associatedIdentifiers: [post.postId, post.title], + associatedFields: ["postWithTagsCompositeKey"] + )) try await postTags.fetch() assertList(postTags, state: .isLoaded(count: 0)) } - + func assertTagWithNoPostTag(_ tag: Tag) async throws { guard let postTags = tag.posts else { XCTFail("Missing postTags on post") return } - assertList(postTags, state: .isNotLoaded(associatedIdentifiers: [tag.id, tag.name], - associatedFields: ["tagWithCompositeKey"])) + assertList(postTags, state: .isNotLoaded( + associatedIdentifiers: [tag.id, tag.name], + associatedFields: ["tagWithCompositeKey"] + )) try await postTags.fetch() assertList(postTags, state: .isLoaded(count: 0)) } - + func testDeletePost() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await mutate(.create(post)) - + try await mutate(.delete(savedPost)) try await assertModelDoesNotExist(savedPost) } - + func testDeleteTag() async throws { await setup(withModels: PostTagModels()) let tag = Tag(name: "name") let savedTag = try await mutate(.create(tag)) - + try await mutate(.delete(savedTag)) try await assertModelDoesNotExist(savedTag) } - + func testDeletePostTag() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -258,9 +295,9 @@ final class GraphQLLazyLoadPostTagTests: GraphQLLazyLoadBaseTest { let savedPost = try await mutate(.create(post)) let savedTag = try await mutate(.create(tag)) let savedPostTag = try await mutate(.create(postTag)) - + try await mutate(.delete(savedPostTag)) - + try await assertModelExists(savedPost) try await assertModelExists(savedTag) try await assertModelDoesNotExist(savedPostTag) @@ -273,7 +310,7 @@ extension GraphQLLazyLoadPostTagTests { typealias Post = PostWithTagsCompositeKey typealias Tag = TagWithCompositeKey typealias PostTag = PostTagsWithCompositeKey - + struct PostTagModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostTagsWithCompositeKey+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostTagsWithCompositeKey+Schema.swift index 59cd80dd74..9ea2ee8d95 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostTagsWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostTagsWithCompositeKey+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostTagsWithCompositeKey { +public extension PostTagsWithCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case postWithTagsCompositeKey case tagWithCompositeKey case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let postTagsWithCompositeKey = PostTagsWithCompositeKey.keys - + model.pluralName = "PostTagsWithCompositeKeys" - + model.attributes( .index(fields: ["postWithTagsCompositeKeyPostId", "postWithTagsCompositeKeytitle"], name: "byPostWithTagsCompositeKey"), .index(fields: ["tagWithCompositeKeyId", "tagWithCompositeKeyname"], name: "byTagWithCompositeKey"), .primaryKey(fields: [postTagsWithCompositeKey.id]) ) - + model.fields( .field(postTagsWithCompositeKey.id, is: .required, ofType: .string), .belongsTo(postTagsWithCompositeKey.postWithTagsCompositeKey, is: .required, ofType: PostWithTagsCompositeKey.self, targetNames: ["postWithTagsCompositeKeyPostId", "postWithTagsCompositeKeytitle"]), @@ -34,29 +41,29 @@ extension PostTagsWithCompositeKey { .field(postTagsWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PostTagsWithCompositeKey: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == PostTagsWithCompositeKey { - public var id: FieldPath { +public extension ModelPath where ModelType == PostTagsWithCompositeKey { + var id: FieldPath { string("id") } - public var postWithTagsCompositeKey: ModelPath { + var postWithTagsCompositeKey: ModelPath { PostWithTagsCompositeKey.Path(name: "postWithTagsCompositeKey", parent: self) } - public var tagWithCompositeKey: ModelPath { + var tagWithCompositeKey: ModelPath { TagWithCompositeKey.Path(name: "tagWithCompositeKey", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostTagsWithCompositeKey.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostTagsWithCompositeKey.swift index a248ebe072..45108cf5a8 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostTagsWithCompositeKey.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostTagsWithCompositeKey.swift @@ -1,16 +1,23 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation public struct PostTagsWithCompositeKey: Model { public let id: String - internal var _postWithTagsCompositeKey: LazyReference + var _postWithTagsCompositeKey: LazyReference public var postWithTagsCompositeKey: PostWithTagsCompositeKey { get async throws { try await _postWithTagsCompositeKey.require() } } - internal var _tagWithCompositeKey: LazyReference + var _tagWithCompositeKey: LazyReference public var tagWithCompositeKey: TagWithCompositeKey { get async throws { try await _tagWithCompositeKey.require() @@ -18,21 +25,27 @@ public struct PostTagsWithCompositeKey: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - postWithTagsCompositeKey: PostWithTagsCompositeKey, - tagWithCompositeKey: TagWithCompositeKey) { - self.init(id: id, - postWithTagsCompositeKey: postWithTagsCompositeKey, - tagWithCompositeKey: tagWithCompositeKey, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + postWithTagsCompositeKey: PostWithTagsCompositeKey, + tagWithCompositeKey: TagWithCompositeKey + ) { + self.init( + id: id, + postWithTagsCompositeKey: postWithTagsCompositeKey, + tagWithCompositeKey: tagWithCompositeKey, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - postWithTagsCompositeKey: PostWithTagsCompositeKey, - tagWithCompositeKey: TagWithCompositeKey, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + postWithTagsCompositeKey: PostWithTagsCompositeKey, + tagWithCompositeKey: TagWithCompositeKey, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self._postWithTagsCompositeKey = LazyReference(postWithTagsCompositeKey) self._tagWithCompositeKey = LazyReference(tagWithCompositeKey) @@ -40,18 +53,18 @@ public struct PostTagsWithCompositeKey: Model { self.updatedAt = updatedAt } public mutating func setPostWithTagsCompositeKey(_ postWithTagsCompositeKey: PostWithTagsCompositeKey) { - self._postWithTagsCompositeKey = LazyReference(postWithTagsCompositeKey) + _postWithTagsCompositeKey = LazyReference(postWithTagsCompositeKey) } public mutating func setTagWithCompositeKey(_ tagWithCompositeKey: TagWithCompositeKey) { - self._tagWithCompositeKey = LazyReference(tagWithCompositeKey) + _tagWithCompositeKey = LazyReference(tagWithCompositeKey) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - _postWithTagsCompositeKey = try values.decodeIfPresent(LazyReference.self, forKey: .postWithTagsCompositeKey) ?? LazyReference(identifiers: nil) - _tagWithCompositeKey = try values.decodeIfPresent(LazyReference.self, forKey: .tagWithCompositeKey) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self._postWithTagsCompositeKey = try values.decodeIfPresent(LazyReference.self, forKey: .postWithTagsCompositeKey) ?? LazyReference(identifiers: nil) + self._tagWithCompositeKey = try values.decodeIfPresent(LazyReference.self, forKey: .tagWithCompositeKey) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostWithTagsCompositeKey+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostWithTagsCompositeKey+Schema.swift index 888c9b969a..eeb2570973 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostWithTagsCompositeKey+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostWithTagsCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithTagsCompositeKey { +public extension PostWithTagsCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case postId case title case tags case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let postWithTagsCompositeKey = PostWithTagsCompositeKey.keys - + model.pluralName = "PostWithTagsCompositeKeys" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [postWithTagsCompositeKey.postId, postWithTagsCompositeKey.title]) ) - + model.fields( .field(postWithTagsCompositeKey.postId, is: .required, ofType: .string), .field(postWithTagsCompositeKey.title, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension PostWithTagsCompositeKey { .field(postWithTagsCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PostWithTagsCompositeKey: ModelIdentifiable { @@ -43,26 +50,28 @@ extension PostWithTagsCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithTagsCompositeKey.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension PostWithTagsCompositeKey.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } } -extension ModelPath where ModelType == PostWithTagsCompositeKey { - public var postId: FieldPath { +public extension ModelPath where ModelType == PostWithTagsCompositeKey { + var postId: FieldPath { string("postId") } - public var title: FieldPath { + var title: FieldPath { string("title") } - public var tags: ModelPath { + var tags: ModelPath { PostTagsWithCompositeKey.Path(name: "tags", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostWithTagsCompositeKey.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostWithTagsCompositeKey.swift index c739bc9c22..73e3e3cd7c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostWithTagsCompositeKey.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/PostWithTagsCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithTagsCompositeKey: Model { public var tags: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - tags: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + tags: List? = [] + ) { + self.init( + postId: postId, title: title, tags: tags, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - tags: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + tags: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.tags = tags self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/TagWithCompositeKey+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/TagWithCompositeKey+Schema.swift index 95a6c9bf82..c6dc88f2f2 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/TagWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/TagWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension TagWithCompositeKey { +public extension TagWithCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let tagWithCompositeKey = TagWithCompositeKey.keys - + model.pluralName = "TagWithCompositeKeys" - + model.attributes( .index(fields: ["id", "name"], name: nil), .primaryKey(fields: [tagWithCompositeKey.id, tagWithCompositeKey.name]) ) - + model.fields( .field(tagWithCompositeKey.id, is: .required, ofType: .string), .field(tagWithCompositeKey.name, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension TagWithCompositeKey { .field(tagWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension TagWithCompositeKey: ModelIdentifiable { @@ -43,26 +50,28 @@ extension TagWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension TagWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - name: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "name", value: name)]) +public extension TagWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + name: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "name", value: name)]) } } -extension ModelPath where ModelType == TagWithCompositeKey { - public var id: FieldPath { +public extension ModelPath where ModelType == TagWithCompositeKey { + var id: FieldPath { string("id") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var posts: ModelPath { + var posts: ModelPath { PostTagsWithCompositeKey.Path(name: "posts", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/TagWithCompositeKey.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/TagWithCompositeKey.swift index 8d8bbf9f26..b913c944db 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/TagWithCompositeKey.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL4/TagWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct TagWithCompositeKey: Model { public var posts: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/GraphQLLazyLoadProjectTeam1Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/GraphQLLazyLoadProjectTeam1Tests.swift index 3752dd1c72..59d1b586f9 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/GraphQLLazyLoadProjectTeam1Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/GraphQLLazyLoadProjectTeam1Tests.swift @@ -5,114 +5,124 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @testable import AWSPluginsCore class GraphQLLazyLoadProjectTeam1Tests: GraphQLLazyLoadBaseTest { - + func testSaveTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) try await assertModelExists(savedTeam) } - + func testSaveProject() async throws { await setup(withModels: ProjectTeam1Models()) - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await mutate(.create(project)) try await assertModelExists(savedProject) assertProjectDoesNotContainTeam(savedProject) } - + func testSaveProjectWithTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) - + // Project initializer variation #1 (pass both team reference and fields in) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - project1TeamTeamId: team.teamId, - project1TeamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + project1TeamTeamId: team.teamId, + project1TeamName: team.name + ) let savedProject = try await mutate(.create(project)) let queriedProject = try await query(for: savedProject)! try await assertProject(queriedProject, hasTeam: savedTeam) - + // Project initializer variation #2 (pass only team reference) - let project2 = Project(projectId: UUID().uuidString, - name: "name", - team: team) + let project2 = Project( + projectId: UUID().uuidString, + name: "name", + team: team + ) let savedProject2 = try await mutate(.create(project2)) let queriedProject2 = try await query(for: savedProject2)! try await assertProject(queriedProject2, hasTeam: savedTeam) - + // Project initializer variation #3 (pass fields in) - let project3 = Project(projectId: UUID().uuidString, - name: "name", - project1TeamTeamId: team.teamId, - project1TeamName: team.name) + let project3 = Project( + projectId: UUID().uuidString, + name: "name", + project1TeamTeamId: team.teamId, + project1TeamName: team.name + ) let savedProject3 = try await mutate(.create(project3)) let queriedProject3 = try await query(for: savedProject3)! try await assertProject(queriedProject3, hasTeam: savedTeam) } - + // The team has a FK referencing the Project and a project has a FK referencing the Team // Saving the Project with the team does not save the team on the project. // This test shows that by saving a project with a team, checking that the team doesn't have the project // Then updating the team with the project, and checking that the team has the project. func testSaveProjectWithTeamThenAccessProjectFromTeamAndTeamFromProject() async throws { await setup(withModels: ProjectTeam1Models()) - + // save project with team let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) let project = initializeProjectWithTeam(savedTeam) let savedProject = try await mutate(.create(project)) - + let queriedProject = try await query(for: savedProject)! var queriedTeam = try await query(for: savedTeam)! - + // Access team from project try await assertProject(queriedProject, hasTeam: savedTeam) // The team does not have the project because we need to save the team with the project. assertTeamDoesNotContainProject(queriedTeam) - + queriedTeam.setProject(queriedProject) let teamWithProject = try await mutate(.update(queriedTeam)) assertTeam(teamWithProject, hasProject: queriedProject) } - + func assertProject(_ project: Project, hasTeam team: Team) async throws { XCTAssertEqual(project.project1TeamTeamId, team.teamId) XCTAssertEqual(project.project1TeamName, team.name) - assertLazyReference(project._team, state: .notLoaded(identifiers: [.init(name: "teamId", value: team.teamId), - .init(name: "name", value: team.name)])) - + assertLazyReference(project._team, state: .notLoaded(identifiers: [ + .init(name: "teamId", value: team.teamId), + .init(name: "name", value: team.name) + ])) + let loadedTeam = try await project.team! XCTAssertEqual(loadedTeam.teamId, team.teamId) } - + func assertProjectDoesNotContainTeam(_ project: Project) { XCTAssertNil(project.project1TeamTeamId) XCTAssertNil(project.project1TeamName) assertLazyReference(project._team, state: .notLoaded(identifiers: nil)) } - + func assertTeam(_ team: Team, hasProject project: Project) { assertLazyReference(team._project, state: .notLoaded(identifiers: [.init(name: "projectId", value: project.projectId), .init(name: "name", value: project.name)])) } - + func assertTeamDoesNotContainProject(_ team: Team) { assertLazyReference(team._project, state: .notLoaded(identifiers: nil)) } - + func testIncludesNestedModels() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -121,28 +131,36 @@ class GraphQLLazyLoadProjectTeam1Tests: GraphQLLazyLoadBaseTest { let savedProject = try await mutate(.create(project)) savedTeam.setProject(savedProject) try await mutate(.update(savedTeam)) - - guard let queriedTeam = try await query(.get(Team.self, - byIdentifier: .identifier(teamId: team.teamId, - name: team.name), - includes: { team in [team.project]})) else { + + guard let queriedTeam = try await query(.get( + Team.self, + byIdentifier: .identifier( + teamId: team.teamId, + name: team.name + ), + includes: { team in [team.project]} + )) else { XCTFail("Could not perform nested query for Team") return } - + assertLazyReference(queriedTeam._project, state: .loaded(model: project)) - - guard let queriedProject = try await query(.get(Project.self, - byIdentifier: .identifier(projectId: project.projectId, - name: project.name), - includes: { project in [project.team]})) else { + + guard let queriedProject = try await query(.get( + Project.self, + byIdentifier: .identifier( + projectId: project.projectId, + name: project.name + ), + includes: { project in [project.team]} + )) else { XCTFail("Could not perform nested query for Project") return } - + assertLazyReference(queriedProject._team, state: .loaded(model: team)) } - + func testListProjectListTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -151,21 +169,25 @@ class GraphQLLazyLoadProjectTeam1Tests: GraphQLLazyLoadBaseTest { let savedProject = try await mutate(.create(project)) savedTeam.setProject(savedProject) try await mutate(.update(savedTeam)) - + let queriedProjects = try await listQuery(.list(Project.self, where: Project.keys.projectId == project.projectId)) assertList(queriedProjects, state: .isLoaded(count: 1)) assertLazyReference(queriedProjects.first!._team, state: .notLoaded(identifiers: [ .init(name: "teamId", value: team.teamId), - .init(name: "name", value: team.name)])) - + .init(name: "name", value: team.name) + ])) + let queriedTeams = try await listQuery(.list(Team.self, where: Team.keys.teamId == team.teamId)) assertList(queriedTeams, state: .isLoaded(count: 1)) - assertLazyReference(queriedTeams.first!._project, - state: .notLoaded(identifiers: [ - .init(name: "projectId", value: project.projectId), - .init(name: "name", value: project.name)])) + assertLazyReference( + queriedTeams.first!._project, + state: .notLoaded(identifiers: [ + .init(name: "projectId", value: project.projectId), + .init(name: "name", value: project.name) + ]) + ) } - + func testSaveProjectWithTeamThenUpdate() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -178,13 +200,13 @@ class GraphQLLazyLoadProjectTeam1Tests: GraphQLLazyLoadBaseTest { let updatedProject = try await mutate(.update(project)) try await assertProject(updatedProject, hasTeam: savedTeam) } - + func testSaveProjectWithoutTeamUpdateProjectWithTeam() async throws { await setup(withModels: ProjectTeam1Models()) let project = Project(projectId: UUID().uuidString, name: "name") let savedProject = try await mutate(.create(project)) assertProjectDoesNotContainTeam(savedProject) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) var queriedProject = try await query(for: savedProject)! @@ -195,7 +217,7 @@ class GraphQLLazyLoadProjectTeam1Tests: GraphQLLazyLoadBaseTest { let savedProjectWithNewTeam = try await mutate(.update(queriedProject)) try await assertProject(savedProjectWithNewTeam, hasTeam: savedTeam) } - + func testSaveTeamSaveProjectWithTeamUpdateProjectToNoTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -211,7 +233,7 @@ class GraphQLLazyLoadProjectTeam1Tests: GraphQLLazyLoadBaseTest { let savedProjectWithNoTeam = try await mutate(.update(queriedProject)) assertProjectDoesNotContainTeam(savedProjectWithNoTeam) } - + func testSaveProjectWithTeamUpdateProjectToNewTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -229,7 +251,7 @@ class GraphQLLazyLoadProjectTeam1Tests: GraphQLLazyLoadBaseTest { let savedProjectWithNewTeam = try await mutate(.update(queriedProject)) try await assertProject(savedProjectWithNewTeam, hasTeam: savedNewTeam) } - + func testDeleteTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -238,7 +260,7 @@ class GraphQLLazyLoadProjectTeam1Tests: GraphQLLazyLoadBaseTest { try await mutate(.delete(savedTeam)) try await assertModelDoesNotExist(savedTeam) } - + func testDeleteProject() async throws { await setup(withModels: ProjectTeam1Models()) let project = Project(projectId: UUID().uuidString, name: "name") @@ -247,22 +269,22 @@ class GraphQLLazyLoadProjectTeam1Tests: GraphQLLazyLoadBaseTest { try await mutate(.delete(savedProject)) try await assertModelDoesNotExist(savedProject) } - + func testDeleteProjectWithTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) let project = initializeProjectWithTeam(team) let savedProject = try await mutate(.create(project)) - + try await assertModelExists(savedProject) try await assertModelExists(savedTeam) - + try await mutate(.delete(savedProject)) - + try await assertModelDoesNotExist(savedProject) try await assertModelExists(savedTeam) - + try await mutate(.delete(savedTeam)) try await assertModelDoesNotExist(savedTeam) } @@ -273,7 +295,7 @@ extension GraphQLLazyLoadProjectTeam1Tests: DefaultLogger { } extension GraphQLLazyLoadProjectTeam1Tests { typealias Project = Project1 typealias Team = Team1 - + struct ProjectTeam1Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -281,12 +303,14 @@ extension GraphQLLazyLoadProjectTeam1Tests { ModelRegistry.register(modelType: Team1.self) } } - + func initializeProjectWithTeam(_ team: Team) -> Project { - return Project(projectId: UUID().uuidString, - name: "name", - team: team, - project1TeamTeamId: team.teamId, - project1TeamName: team.name) + return Project( + projectId: UUID().uuidString, + name: "name", + team: team, + project1TeamTeamId: team.teamId, + project1TeamName: team.name + ) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Project1+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Project1+Schema.swift index cb052507f7..68ffadac0f 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Project1+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Project1+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project1 { +public extension Project1 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project1 { case project1TeamTeamId case project1TeamName } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let project1 = Project1.keys - + model.pluralName = "Project1s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project1.projectId, project1.name]) ) - + model.fields( .field(project1.projectId, is: .required, ofType: .string), .field(project1.name, is: .required, ofType: .string), @@ -37,9 +44,9 @@ extension Project1 { .field(project1.project1TeamName, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Project1: ModelIdentifiable { @@ -47,32 +54,34 @@ extension Project1: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project1.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project1.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } } -extension ModelPath where ModelType == Project1 { - public var projectId: FieldPath { +public extension ModelPath where ModelType == Project1 { + var projectId: FieldPath { string("projectId") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var team: ModelPath { + var team: ModelPath { Team1.Path(name: "team", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } - public var project1TeamTeamId: FieldPath { + var project1TeamTeamId: FieldPath { string("project1TeamTeamId") } - public var project1TeamName: FieldPath { + var project1TeamName: FieldPath { string("project1TeamName") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Project1.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Project1.swift index a36917b1ba..550860a378 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Project1.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Project1.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Project1: Model { public let projectId: String public let name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team1? { get async throws { try await _team.get() @@ -15,27 +22,33 @@ public struct Project1: Model { public var updatedAt: Temporal.DateTime? public var project1TeamTeamId: String? public var project1TeamName: String? - - public init(projectId: String, - name: String, - team: Team1? = nil, - project1TeamTeamId: String? = nil, - project1TeamName: String? = nil) { - self.init(projectId: projectId, - name: name, - team: team, - createdAt: nil, - updatedAt: nil, - project1TeamTeamId: project1TeamTeamId, - project1TeamName: project1TeamName) + + public init( + projectId: String, + name: String, + team: Team1? = nil, + project1TeamTeamId: String? = nil, + project1TeamName: String? = nil + ) { + self.init( + projectId: projectId, + name: name, + team: team, + createdAt: nil, + updatedAt: nil, + project1TeamTeamId: project1TeamTeamId, + project1TeamName: project1TeamName + ) } - internal init(projectId: String, - name: String, - team: Team1? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project1TeamTeamId: String? = nil, - project1TeamName: String? = nil) { + init( + projectId: String, + name: String, + team: Team1? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project1TeamTeamId: String? = nil, + project1TeamName: String? = nil + ) { self.projectId = projectId self.name = name self._team = LazyReference(team) @@ -45,17 +58,17 @@ public struct Project1: Model { self.project1TeamName = project1TeamName } public mutating func setTeam(_ team: Team1? = nil) { - self._team = LazyReference(team) + _team = LazyReference(team) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - projectId = try values.decode(String.self, forKey: .projectId) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - project1TeamTeamId = try? values.decode(String?.self, forKey: .project1TeamTeamId) - project1TeamName = try? values.decode(String?.self, forKey: .project1TeamName) + self.projectId = try values.decode(String.self, forKey: .projectId) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.project1TeamTeamId = try? values.decode(String?.self, forKey: .project1TeamTeamId) + self.project1TeamName = try? values.decode(String?.self, forKey: .project1TeamName) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Team1+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Team1+Schema.swift index 1ac9b09f53..c29406367b 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Team1+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Team1+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team1 { +public extension Team1 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case teamId case name case project case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let team1 = Team1.keys - + model.pluralName = "Team1s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team1.teamId, team1.name]) ) - + model.fields( .field(team1.teamId, is: .required, ofType: .string), .field(team1.name, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension Team1 { .field(team1.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team1: ModelIdentifiable { @@ -43,26 +50,28 @@ extension Team1: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team1.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team1.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } } -extension ModelPath where ModelType == Team1 { - public var teamId: FieldPath { +public extension ModelPath where ModelType == Team1 { + var teamId: FieldPath { string("teamId") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var project: ModelPath { + var project: ModelPath { Project1.Path(name: "project", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Team1.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Team1.swift index c29c0e2252..8483e5515c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Team1.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL5/Team1.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Team1: Model { public let teamId: String public let name: String - internal var _project: LazyReference + var _project: LazyReference public var project: Project1? { get async throws { try await _project.get() @@ -13,21 +20,27 @@ public struct Team1: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String, - project: Project1? = nil) { - self.init(teamId: teamId, - name: name, - project: project, - createdAt: nil, - updatedAt: nil) + + public init( + teamId: String, + name: String, + project: Project1? = nil + ) { + self.init( + teamId: teamId, + name: name, + project: project, + createdAt: nil, + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - project: Project1? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + project: Project1? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self._project = LazyReference(project) @@ -35,15 +48,15 @@ public struct Team1: Model { self.updatedAt = updatedAt } public mutating func setProject(_ project: Project1? = nil) { - self._project = LazyReference(project) + _project = LazyReference(project) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - teamId = try values.decode(String.self, forKey: .teamId) - name = try values.decode(String.self, forKey: .name) - _project = try values.decodeIfPresent(LazyReference.self, forKey: .project) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.teamId = try values.decode(String.self, forKey: .teamId) + self.name = try values.decode(String.self, forKey: .name) + self._project = try values.decodeIfPresent(LazyReference.self, forKey: .project) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/GraphQLLazyLoadProjectTeam2Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/GraphQLLazyLoadProjectTeam2Tests.swift index 2fd54bcea0..92c62a47bb 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/GraphQLLazyLoadProjectTeam2Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/GraphQLLazyLoadProjectTeam2Tests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class GraphQLLazyLoadProjectTeam2Tests: GraphQLLazyLoadBaseTest { @@ -20,105 +20,120 @@ class GraphQLLazyLoadProjectTeam2Tests: GraphQLLazyLoadBaseTest { let savedTeam = try await mutate(.create(team)) try await assertModelExists(savedTeam) } - + func testSaveProject() async throws { await setup(withModels: ProjectTeam2Models()) - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await mutate(.create(project)) try await assertModelExists(savedProject) assertProjectDoesNotContainTeam(savedProject) } - + func testSaveProjectWithTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) - + // Project initializer variation #1 (pass both team reference and fields in) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - project2TeamTeamId: team.teamId, - project2TeamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + project2TeamTeamId: team.teamId, + project2TeamName: team.name + ) let savedProject = try await mutate(.create(project)) let queriedProject = try await query(for: savedProject)! try await assertProject(queriedProject, hasTeam: savedTeam) - + // Project initializer variation #2 (pass only team reference) - let project2 = Project(projectId: UUID().uuidString, - name: "name", - team: team) + let project2 = Project( + projectId: UUID().uuidString, + name: "name", + team: team + ) let savedProject2 = try await mutate(.create(project2)) let queriedProject2 = try await query(for: savedProject2)! try await assertProject(queriedProject2, hasTeam: savedTeam) - + // Project initializer variation #3 (pass fields in) - let project3 = Project(projectId: UUID().uuidString, - name: "name", - project2TeamTeamId: team.teamId, - project2TeamName: team.name) + let project3 = Project( + projectId: UUID().uuidString, + name: "name", + project2TeamTeamId: team.teamId, + project2TeamName: team.name + ) let savedProject3 = try await mutate(.create(project3)) let queriedProject3 = try await query(for: savedProject3)! try await assertProject(queriedProject3, hasTeam: savedTeam) } - + func assertProject(_ project: Project, hasTeam team: Team) async throws { XCTAssertEqual(project.project2TeamTeamId, team.teamId) XCTAssertEqual(project.project2TeamName, team.name) - assertLazyReference(project._team, state: .notLoaded(identifiers: [.init(name: "teamId", value: team.teamId), - .init(name: "name", value: team.name)])) - + assertLazyReference(project._team, state: .notLoaded(identifiers: [ + .init(name: "teamId", value: team.teamId), + .init(name: "name", value: team.name) + ])) + let loadedTeam = try await project.team! XCTAssertEqual(loadedTeam.teamId, team.teamId) } - + func assertProjectDoesNotContainTeam(_ project: Project) { XCTAssertNil(project.project2TeamTeamId) XCTAssertNil(project.project2TeamName) assertLazyReference(project._team, state: .notLoaded(identifiers: nil)) } - + func testIncludesNestedModels() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") try await mutate(.create(team)) let project = initializeProjectWithTeam(team) try await mutate(.create(project)) - - guard let queriedProject = try await query(.get(Project.self, - byIdentifier: .identifier(projectId: project.projectId, - name: project.name), - includes: { project in [project.team]})) else { + + guard let queriedProject = try await query(.get( + Project.self, + byIdentifier: .identifier( + projectId: project.projectId, + name: project.name + ), + includes: { project in [project.team]} + )) else { XCTFail("Could not perform nested query for Project") return } - + assertLazyReference(queriedProject._team, state: .loaded(model: team)) } - + func testListProjectListTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") try await mutate(.create(team)) let project = initializeProjectWithTeam(team) try await mutate(.create(project)) - + let queriedProjects = try await listQuery(.list(Project.self, where: Project.keys.projectId == project.projectId)) assertList(queriedProjects, state: .isLoaded(count: 1)) assertLazyReference(queriedProjects.first!._team, state: .notLoaded(identifiers: [ .init(name: "teamId", value: team.teamId), - .init(name: "name", value: team.name)])) - + .init(name: "name", value: team.name) + ])) + let queriedTeams = try await listQuery(.list(Team.self, where: Team.keys.teamId == team.teamId)) assertList(queriedTeams, state: .isLoaded(count: 1)) } - + func testSaveProjectWithTeamThenUpdate() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) - + let project = initializeProjectWithTeam(team) let savedProject = try await mutate(.create(project)) try await assertProject(savedProject, hasTeam: savedTeam) @@ -127,13 +142,13 @@ class GraphQLLazyLoadProjectTeam2Tests: GraphQLLazyLoadBaseTest { let updatedProject = try await mutate(.update(project)) try await assertProject(updatedProject, hasTeam: savedTeam) } - + func testSaveProjectWithoutTeamUpdateProjectWithTeam() async throws { await setup(withModels: ProjectTeam2Models()) let project = Project(projectId: UUID().uuidString, name: "name") let savedProject = try await mutate(.create(project)) assertProjectDoesNotContainTeam(savedProject) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) var queriedProject = try await query(for: savedProject)! @@ -144,7 +159,7 @@ class GraphQLLazyLoadProjectTeam2Tests: GraphQLLazyLoadBaseTest { let savedProjectWithNewTeam = try await mutate(.update(queriedProject)) try await assertProject(savedProjectWithNewTeam, hasTeam: savedTeam) } - + func testSaveTeamSaveProjectWithTeamUpdateProjectToNoTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -160,7 +175,7 @@ class GraphQLLazyLoadProjectTeam2Tests: GraphQLLazyLoadBaseTest { let savedProjectWithNoTeam = try await mutate(.update(queriedProject)) assertProjectDoesNotContainTeam(savedProjectWithNoTeam) } - + func testSaveProjectWithTeamUpdateProjectToNewTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -178,7 +193,7 @@ class GraphQLLazyLoadProjectTeam2Tests: GraphQLLazyLoadBaseTest { let savedProjectWithNewTeam = try await mutate(.update(queriedProject)) try await assertProject(savedProjectWithNewTeam, hasTeam: savedNewTeam) } - + func testDeleteTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -187,7 +202,7 @@ class GraphQLLazyLoadProjectTeam2Tests: GraphQLLazyLoadBaseTest { try await mutate(.delete(savedTeam)) try await assertModelDoesNotExist(savedTeam) } - + func testDeleteProject() async throws { await setup(withModels: ProjectTeam2Models()) let project = Project(projectId: UUID().uuidString, name: "name") @@ -196,22 +211,22 @@ class GraphQLLazyLoadProjectTeam2Tests: GraphQLLazyLoadBaseTest { try await mutate(.delete(savedProject)) try await assertModelDoesNotExist(savedProject) } - + func testDeleteProjectWithTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) let project = initializeProjectWithTeam(team) let savedProject = try await mutate(.create(project)) - + try await assertModelExists(savedProject) try await assertModelExists(savedTeam) - + try await mutate(.delete(savedProject)) - + try await assertModelDoesNotExist(savedProject) try await assertModelExists(savedTeam) - + try await mutate(.delete(savedTeam)) try await assertModelDoesNotExist(savedTeam) } @@ -220,10 +235,10 @@ class GraphQLLazyLoadProjectTeam2Tests: GraphQLLazyLoadBaseTest { extension GraphQLLazyLoadProjectTeam2Tests: DefaultLogger { } extension GraphQLLazyLoadProjectTeam2Tests { - + typealias Project = Project2 typealias Team = Team2 - + struct ProjectTeam2Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -231,12 +246,14 @@ extension GraphQLLazyLoadProjectTeam2Tests { ModelRegistry.register(modelType: Team2.self) } } - + func initializeProjectWithTeam(_ team: Team) -> Project { - return Project(projectId: UUID().uuidString, - name: "name", - team: team, - project2TeamTeamId: team.teamId, - project2TeamName: team.name) + return Project( + projectId: UUID().uuidString, + name: "name", + team: team, + project2TeamTeamId: team.teamId, + project2TeamName: team.name + ) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Project2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Project2+Schema.swift index 79361d58a5..4d90db0806 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Project2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Project2+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project2 { +public extension Project2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -14,10 +21,10 @@ extension Project2 { case project2TeamName } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project2 = Project2.keys model.pluralName = "Project2s" @@ -37,10 +44,10 @@ extension Project2 { .field(project2.project2TeamName, is: .optional, ofType: .string) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Project2: ModelIdentifiable { @@ -48,10 +55,12 @@ extension Project2: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project2.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project2.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Project2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Project2.swift index e18996f773..298dc8449e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Project2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Project2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Project2: Model { public let projectId: String public let name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team2? { get async throws { try await _team.get() @@ -15,27 +22,33 @@ public struct Project2: Model { public var updatedAt: Temporal.DateTime? public var project2TeamTeamId: String? public var project2TeamName: String? - - public init(projectId: String, - name: String, - team: Team2? = nil, - project2TeamTeamId: String? = nil, - project2TeamName: String? = nil) { - self.init(projectId: projectId, - name: name, - team: team, - createdAt: nil, - updatedAt: nil, - project2TeamTeamId: project2TeamTeamId, - project2TeamName: project2TeamName) + + public init( + projectId: String, + name: String, + team: Team2? = nil, + project2TeamTeamId: String? = nil, + project2TeamName: String? = nil + ) { + self.init( + projectId: projectId, + name: name, + team: team, + createdAt: nil, + updatedAt: nil, + project2TeamTeamId: project2TeamTeamId, + project2TeamName: project2TeamName + ) } - internal init(projectId: String, - name: String, - team: Team2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project2TeamTeamId: String? = nil, - project2TeamName: String? = nil) { + init( + projectId: String, + name: String, + team: Team2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project2TeamTeamId: String? = nil, + project2TeamName: String? = nil + ) { self.projectId = projectId self.name = name self._team = LazyReference(team) @@ -45,17 +58,17 @@ public struct Project2: Model { self.project2TeamName = project2TeamName } public mutating func setTeam(_ team: Team2? = nil) { - self._team = LazyReference(team) + _team = LazyReference(team) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - projectId = try values.decode(String.self, forKey: .projectId) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - project2TeamTeamId = try? values.decode(String?.self, forKey: .project2TeamTeamId) - project2TeamName = try? values.decode(String?.self, forKey: .project2TeamName) + self.projectId = try values.decode(String.self, forKey: .projectId) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.project2TeamTeamId = try? values.decode(String?.self, forKey: .project2TeamTeamId) + self.project2TeamName = try? values.decode(String?.self, forKey: .project2TeamName) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Team2+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Team2+Schema.swift index 58ae64d03a..bcb5656050 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Team2+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Team2+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case teamId case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team2 = Team2.keys - + model.pluralName = "Team2s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team2.teamId, team2.name]) ) - + model.fields( .field(team2.teamId, is: .required, ofType: .string), .field(team2.name, is: .required, ofType: .string), @@ -31,10 +38,10 @@ extension Team2 { .field(team2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team2: ModelIdentifiable { @@ -42,10 +49,12 @@ extension Team2: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team2.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team2.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Team2.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Team2.swift index 90d68caa79..f58e821d6e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Team2.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL6/Team2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Team2: Model { public let name: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String) { - self.init(teamId: teamId, + + public init( + teamId: String, + name: String + ) { + self.init( + teamId: teamId, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Comment4+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Comment4+Schema.swift index 0c2cc0b6bb..421e5b158c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Comment4+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Comment4+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment4 { +public extension Comment4 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case commentId case content case createdAt @@ -12,20 +19,20 @@ extension Comment4 { case post4CommentsPostId case post4CommentsTitle } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let comment4 = Comment4.keys - + model.pluralName = "Comment4s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .primaryKey(fields: [comment4.commentId, comment4.content]) ) - + model.fields( .field(comment4.commentId, is: .required, ofType: .string), .field(comment4.content, is: .required, ofType: .string), @@ -35,9 +42,9 @@ extension Comment4 { .field(comment4.post4CommentsTitle, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment4: ModelIdentifiable { @@ -45,29 +52,31 @@ extension Comment4: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment4.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment4.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == Comment4 { - public var commentId: FieldPath { +public extension ModelPath where ModelType == Comment4 { + var commentId: FieldPath { string("commentId") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } - public var post4CommentsPostId: FieldPath { + var post4CommentsPostId: FieldPath { string("post4CommentsPostId") } - public var post4CommentsTitle: FieldPath { + var post4CommentsTitle: FieldPath { string("post4CommentsTitle") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Comment4.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Comment4.swift index 8e9cc84bce..593b1efc60 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Comment4.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Comment4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Comment4: Model { public var updatedAt: Temporal.DateTime? public var post4CommentsPostId: String? public var post4CommentsTitle: String? - - public init(commentId: String, - content: String, - post4CommentsPostId: String? = nil, - post4CommentsTitle: String? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + post4CommentsPostId: String? = nil, + post4CommentsTitle: String? = nil + ) { + self.init( + commentId: commentId, content: content, createdAt: nil, updatedAt: nil, post4CommentsPostId: post4CommentsPostId, - post4CommentsTitle: post4CommentsTitle) + post4CommentsTitle: post4CommentsTitle + ) } - internal init(commentId: String, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - post4CommentsPostId: String? = nil, - post4CommentsTitle: String? = nil) { + init( + commentId: String, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + post4CommentsPostId: String? = nil, + post4CommentsTitle: String? = nil + ) { self.commentId = commentId self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/GraphQLLazyLoadPostComment4Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/GraphQLLazyLoadPostComment4Tests.swift index 4743a822f9..4fde13229e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/GraphQLLazyLoadPostComment4Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/GraphQLLazyLoadPostComment4Tests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { @@ -21,7 +21,7 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { try await mutate(.create(post)) try await mutate(.create(comment)) } - + // Without `includes` and latest codegenerated types with the model path, the post should be lazy loaded func testCommentWithLazyLoadPost() async throws { await setup(withModels: PostComment4Models()) @@ -29,21 +29,23 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { let comment = Comment(content: "content", post: post) let createdPost = try await mutate(.create(post)) let createdComment = try await mutate(.create(comment)) - + XCTAssertEqual(createdComment.post4CommentsPostId, post.postId) XCTAssertEqual(createdComment.post4CommentsTitle, post.title) - + // The created post should have comments that are also not loaded let comments = createdPost.comments! - assertList(comments, state: .isNotLoaded(associatedIdentifiers: [createdPost.postId, createdPost.title], - associatedFields: ["post4CommentsPostId", "post4CommentsTitle"])) + assertList(comments, state: .isNotLoaded( + associatedIdentifiers: [createdPost.postId, createdPost.title], + associatedFields: ["post4CommentsPostId", "post4CommentsTitle"] + )) // load the comments try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) XCTAssertEqual(comments.first!.post4CommentsPostId, post.postId) XCTAssertEqual(comments.first!.post4CommentsTitle, post.title) } - + // Without `includes` and latest codegenerated types with the model path, the post's comments should be lazy loaded func testPostWithLazyLoadComments() async throws { await setup(withModels: PostComment4Models()) @@ -53,14 +55,16 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { _ = try await mutate(.create(comment)) let queriedPost = try await query(.get(Post.self, byIdentifier: .identifier(postId: post.postId, title: post.title)))! let comments = queriedPost.comments! - assertList(comments, state: .isNotLoaded(associatedIdentifiers: [post.postId, post.title], - associatedFields: ["post4CommentsPostId", "post4CommentsTitle"])) + assertList(comments, state: .isNotLoaded( + associatedIdentifiers: [post.postId, post.title], + associatedFields: ["post4CommentsPostId", "post4CommentsTitle"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) XCTAssertEqual(comments.first!.post4CommentsPostId, post.postId) XCTAssertEqual(comments.first!.post4CommentsTitle, post.title) } - + // With `includes` on `post.comments` should eager load the post's comments func testPostWithEagerLoadComments() async throws { await setup(withModels: PostComment4Models()) @@ -74,26 +78,30 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { XCTAssertEqual(comments.first!.post4CommentsPostId, post.postId) XCTAssertEqual(comments.first!.post4CommentsTitle, post.title) } - + func testListPostsListComments() async throws { await setup(withModels: PostComment4Models()) let post = Post(title: "title") let comment = Comment(content: "content", post: post) _ = try await mutate(.create(post)) _ = try await mutate(.create(comment)) - + let queriedPosts = try await listQuery(.list(Post.self, where: Post.keys.postId == post.postId)) assertList(queriedPosts, state: .isLoaded(count: 1)) - assertList(queriedPosts.first!.comments!, - state: .isNotLoaded(associatedIdentifiers: [post.postId, post.title], - associatedFields: ["post4CommentsPostId", "post4CommentsTitle"])) - + assertList( + queriedPosts.first!.comments!, + state: .isNotLoaded( + associatedIdentifiers: [post.postId, post.title], + associatedFields: ["post4CommentsPostId", "post4CommentsTitle"] + ) + ) + let queriedComments = try await listQuery(.list(Comment.self, where: Comment.keys.commentId == comment.commentId)) assertList(queriedComments, state: .isLoaded(count: 1)) XCTAssertEqual(queriedComments.first!.post4CommentsPostId, post.postId) XCTAssertEqual(queriedComments.first!.post4CommentsTitle, post.title) } - + func testCreateWithoutPost() async throws { await setup(withModels: PostComment4Models()) let comment = Comment(content: "content") @@ -110,15 +118,17 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { XCTAssertEqual(queriedCommentAfterUpdate.post4CommentsPostId, post.postId) XCTAssertEqual(queriedCommentAfterUpdate.post4CommentsTitle, post.title) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostComment4Models()) let post = Post(title: "title") let comment = Comment(content: "content", post: post) try await mutate(.create(post)) try await mutate(.create(comment)) - var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier(commentId: comment.commentId, - content: comment.content)))! + var queriedComment = try await query(.get(Comment.self, byIdentifier: .identifier( + commentId: comment.commentId, + content: comment.content + )))! XCTAssertEqual(queriedComment.post4CommentsPostId, post.postId) XCTAssertEqual(queriedComment.post4CommentsTitle, post.title) let newPost = Post(title: "title") @@ -130,7 +140,7 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { XCTAssertEqual(queriedCommentAfterUpdate.post4CommentsPostId, newPost.postId) XCTAssertEqual(queriedCommentAfterUpdate.post4CommentsTitle, newPost.title) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostComment4Models()) let post = Post(title: "title") @@ -140,7 +150,7 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { var queriedComment = try await query(for: comment)! XCTAssertEqual(queriedComment.post4CommentsPostId, post.postId) XCTAssertEqual(queriedComment.post4CommentsTitle, post.title) - + queriedComment.post4CommentsPostId = nil queriedComment.post4CommentsTitle = nil let updateCommentRemovePost = try await mutate(.update(queriedComment)) @@ -148,14 +158,14 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { XCTAssertEqual(queriedCommentAfterUpdate.post4CommentsPostId, nil) XCTAssertEqual(queriedCommentAfterUpdate.post4CommentsTitle, nil) } - + func testDelete() async throws { await setup(withModels: PostComment4Models()) let post = Post(title: "title") let comment = Comment(content: "content", post: post) let createdPost = try await mutate(.create(post)) try await mutate(.create(comment)) - + try await mutate(.delete(createdPost)) let queriedPost = try await query(for: post) XCTAssertNil(queriedPost) @@ -166,7 +176,7 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { let queryDeletedComment = try await query(for: comment) XCTAssertNil(queryDeletedComment) } - + func testSubscribeToComments() async throws { await setup(withModels: PostComment4Models()) let post = Post(title: "title") @@ -199,18 +209,18 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) let comment = Comment(content: "content", post: post) try await mutate(.create(comment)) await fulfillment(of: [onCreatedComment], timeout: 10) subscription.cancel() } - + func testSubscribeToPosts() async throws { await setup(withModels: PostComment4Models()) let post = Post(title: "title") - + let connected = expectation(description: "subscription connected") let onCreatedPost = expectation(description: "onCreatedPost received") let subscription = Amplify.API.subscribe(request: .subscription(of: Post.self, type: .onCreate)) @@ -227,10 +237,16 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { switch result { case .success(let createdPost): log.verbose("Successfully got createdPost from subscription: \(createdPost)") - assertList(createdPost.comments!, state: .isNotLoaded(associatedIdentifiers: [post.postId, - post.title], - associatedFields: ["post4CommentsPostId", - "post4CommentsTitle"])) + assertList(createdPost.comments!, state: .isNotLoaded( + associatedIdentifiers: [ + post.postId, + post.title + ], + associatedFields: [ + "post4CommentsPostId", + "post4CommentsTitle" + ] + )) onCreatedPost.fulfill() case .failure(let error): XCTFail("Got failed result with \(error.errorDescription)") @@ -241,22 +257,24 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) try await mutate(.create(post)) await fulfillment(of: [onCreatedPost], timeout: 10) subscription.cancel() } - + func testSubscribeToPostsIncludes() async throws { await setup(withModels: PostComment4Models()) let post = Post(title: "title") - + let connected = expectation(description: "subscription connected") let onCreatedPost = expectation(description: "onCreatedPost received") - let subscriptionIncludes = Amplify.API.subscribe(request: .subscription(of: Post.self, - type: .onCreate, - includes: { post in [post.comments]})) + let subscriptionIncludes = Amplify.API.subscribe(request: .subscription( + of: Post.self, + type: .onCreate, + includes: { post in [post.comments]} + )) Task { do { for try await subscriptionEvent in subscriptionIncludes { @@ -281,7 +299,7 @@ final class GraphQLLazyLoadPostComment4Tests: GraphQLLazyLoadBaseTest { XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) try await mutate(.create(post, includes: { post in [post.comments]})) await fulfillment(of: [onCreatedPost], timeout: 10) @@ -294,7 +312,7 @@ extension GraphQLLazyLoadPostComment4Tests: DefaultLogger { } extension GraphQLLazyLoadPostComment4Tests { typealias Post = Post4 typealias Comment = Comment4 - + struct PostComment4Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -311,11 +329,15 @@ extension Post4 { } extension Comment4 { - init(content: String, - post: Post4? = nil) { - self.init(commentId: UUID().uuidString, - content: content, - post4CommentsPostId: post?.postId, - post4CommentsTitle: post?.title) + init( + content: String, + post: Post4? = nil + ) { + self.init( + commentId: UUID().uuidString, + content: content, + post4CommentsPostId: post?.postId, + post4CommentsTitle: post?.title + ) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Post4+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Post4+Schema.swift index fa09945d0d..c2d1b4f3bb 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Post4+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Post4+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post4 { +public extension Post4 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let post4 = Post4.keys - + model.pluralName = "Post4s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post4.postId, post4.title]) ) - + model.fields( .field(post4.postId, is: .required, ofType: .string), .field(post4.title, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension Post4 { .field(post4.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post4: ModelIdentifiable { @@ -43,26 +50,28 @@ extension Post4: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post4.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post4.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } } -extension ModelPath where ModelType == Post4 { - public var postId: FieldPath { +public extension ModelPath where ModelType == Post4 { + var postId: FieldPath { string("postId") } - public var title: FieldPath { + var title: FieldPath { string("title") } - public var comments: ModelPath { + var comments: ModelPath { Comment4.Path(name: "comments", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Post4.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Post4.swift index a50849704b..1d08640c37 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Post4.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL7/Post4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post4: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/GraphQLLazyLoadProjectTeam5Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/GraphQLLazyLoadProjectTeam5Tests.swift index d6fc3c3de6..d6f81a79d7 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/GraphQLLazyLoadProjectTeam5Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/GraphQLLazyLoadProjectTeam5Tests.swift @@ -5,64 +5,72 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class GraphQLLazyLoadProjectTeam5Tests: GraphQLLazyLoadBaseTest { - + func testSaveTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) try await assertModelExists(savedTeam) } - + func testSaveProject() async throws { await setup(withModels: ProjectTeam5Models()) - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await mutate(.create(project)) try await assertModelExists(savedProject) assertProjectDoesNotContainTeam(savedProject) } - + func testSaveProjectWithTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) - + // Project initializer variation #1 (pass both team reference and fields in) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) let savedProject = try await mutate(.create(project)) let queriedProject = try await query(for: savedProject)! assertProject(queriedProject, hasTeam: savedTeam) - + // Project initializer variation #2 (pass only team reference) - let project2 = Project(projectId: UUID().uuidString, - name: "name", - team: team) + let project2 = Project( + projectId: UUID().uuidString, + name: "name", + team: team + ) let savedProject2 = try await mutate(.create(project2)) let queriedProject2 = try await query(for: savedProject2)! assertProject(queriedProject2, hasTeam: savedTeam) - + // Project initializer variation #3 (pass fields in) - let project3 = Project(projectId: UUID().uuidString, - name: "name", - teamId: team.teamId, - teamName: team.name) + let project3 = Project( + projectId: UUID().uuidString, + name: "name", + teamId: team.teamId, + teamName: team.name + ) let savedProject3 = try await mutate(.create(project3)) let queriedProject3 = try await query(for: savedProject3)! assertProject(queriedProject3, hasTeam: savedTeam) } - + // One-to-One relationships do not create a foreign key for the Team or Project table // So the LazyModel does not have the FK value to be instantiated as metadata for lazy loading. // We only assert the FK fields on the Project exist and are equal to the Team's PK. @@ -70,78 +78,94 @@ class GraphQLLazyLoadProjectTeam5Tests: GraphQLLazyLoadBaseTest { XCTAssertEqual(project.teamId, team.teamId) XCTAssertEqual(project.teamName, team.name) } - + func assertProjectDoesNotContainTeam(_ project: Project) { XCTAssertNil(project.teamId) XCTAssertNil(project.teamName) } - + func testIncludesNestedModels() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") var savedTeam = try await mutate(.create(team)) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) let savedProject = try await mutate(.create(project)) savedTeam.setProject(savedProject) try await mutate(.update(savedTeam)) - - guard let queriedTeam = try await query(.get(Team.self, - byIdentifier: .identifier(teamId: team.teamId, - name: team.name), - includes: { team in [team.project]})) else { + + guard let queriedTeam = try await query(.get( + Team.self, + byIdentifier: .identifier( + teamId: team.teamId, + name: team.name + ), + includes: { team in [team.project]} + )) else { XCTFail("Could not perform nested query for Team") return } - + assertLazyReference(queriedTeam._project, state: .loaded(model: project)) - - guard let queriedProject = try await query(.get(Project.self, - byIdentifier: .identifier(projectId: project.projectId, - name: project.name), - includes: { project in [project.team]})) else { + + guard let queriedProject = try await query(.get( + Project.self, + byIdentifier: .identifier( + projectId: project.projectId, + name: project.name + ), + includes: { project in [project.team]} + )) else { XCTFail("Could not perform nested query for Project") return } - + assertLazyReference(queriedProject._team, state: .loaded(model: team)) } - + func testListProjectListTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") var savedTeam = try await mutate(.create(team)) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) let savedProject = try await mutate(.create(project)) savedTeam.setProject(savedProject) try await mutate(.update(savedTeam)) - + let queriedProjects = try await listQuery(.list(Project.self, where: Project.keys.projectId == project.projectId)) assertList(queriedProjects, state: .isLoaded(count: 1)) assertLazyReference(queriedProjects.first!._team, state: .notLoaded(identifiers: [ .init(name: "teamId", value: team.teamId), - .init(name: "name", value: team.name)])) - + .init(name: "name", value: team.name) + ])) + let queriedTeams = try await listQuery(.list(Team.self, where: Team.keys.teamId == team.teamId)) assertList(queriedTeams, state: .isLoaded(count: 1)) - assertLazyReference(queriedTeams.first!._project, - state: .notLoaded(identifiers: [ - .init(name: "projectId", value: project.projectId), - .init(name: "name", value: project.name)])) + assertLazyReference( + queriedTeams.first!._project, + state: .notLoaded(identifiers: [ + .init(name: "projectId", value: project.projectId), + .init(name: "name", value: project.name) + ]) + ) } - + func testSaveProjectWithTeamThenUpdate() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) - + let project = initializeProjectWithTeam(team) let savedProject = try await mutate(.create(project)) assertProject(savedProject, hasTeam: savedTeam) @@ -150,13 +174,13 @@ class GraphQLLazyLoadProjectTeam5Tests: GraphQLLazyLoadBaseTest { let updatedProject = try await mutate(.update(project)) assertProject(updatedProject, hasTeam: savedTeam) } - + func testSaveProjectWithoutTeamUpdateProjectWithTeam() async throws { await setup(withModels: ProjectTeam5Models()) let project = Project(projectId: UUID().uuidString, name: "name") let savedProject = try await mutate(.create(project)) assertProjectDoesNotContainTeam(savedProject) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) var queriedProject = try await query(for: savedProject)! @@ -164,7 +188,7 @@ class GraphQLLazyLoadProjectTeam5Tests: GraphQLLazyLoadBaseTest { let savedProjectWithNewTeam = try await mutate(.update(queriedProject)) assertProject(savedProjectWithNewTeam, hasTeam: savedTeam) } - + func testSaveTeamSaveProjectWithTeamUpdateProjectToNoTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -177,7 +201,7 @@ class GraphQLLazyLoadProjectTeam5Tests: GraphQLLazyLoadBaseTest { let savedProjectWithNoTeam = try await mutate(.update(queriedProject)) assertProjectDoesNotContainTeam(savedProjectWithNoTeam) } - + func testSaveProjectWithTeamUpdateProjectToNewTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -192,7 +216,7 @@ class GraphQLLazyLoadProjectTeam5Tests: GraphQLLazyLoadBaseTest { let savedProjectWithNewTeam = try await mutate(.update(queriedProject)) assertProject(savedProjectWithNewTeam, hasTeam: savedNewTeam) } - + func testDeleteTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -201,7 +225,7 @@ class GraphQLLazyLoadProjectTeam5Tests: GraphQLLazyLoadBaseTest { try await mutate(.delete(savedTeam)) try await assertModelDoesNotExist(savedTeam) } - + func testDeleteProject() async throws { await setup(withModels: ProjectTeam5Models()) let project = Project(projectId: UUID().uuidString, name: "name") @@ -210,30 +234,32 @@ class GraphQLLazyLoadProjectTeam5Tests: GraphQLLazyLoadBaseTest { try await mutate(.delete(savedProject)) try await assertModelDoesNotExist(savedProject) } - + func testDeleteProjectWithTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) let savedProject = try await mutate(.create(project)) - + try await assertModelExists(savedProject) try await assertModelExists(savedTeam) - + try await mutate(.delete(savedProject)) - + try await assertModelDoesNotExist(savedProject) try await assertModelExists(savedTeam) - + try await mutate(.delete(savedTeam)) try await assertModelDoesNotExist(savedTeam) } - + func testSubscribeToTeam() async throws { await setup(withModels: ProjectTeam5Models()) let connected = expectation(description: "subscription connected") @@ -262,16 +288,16 @@ class GraphQLLazyLoadProjectTeam5Tests: GraphQLLazyLoadBaseTest { XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) _ = savedTeam await fulfillment(of: [onCreatedTeam], timeout: 10) subscription.cancel() } - + func testSubscribeProject() async throws { await setup(withModels: ProjectTeam5Models()) let connected = expectation(description: "subscription connected") @@ -300,11 +326,13 @@ class GraphQLLazyLoadProjectTeam5Tests: GraphQLLazyLoadBaseTest { XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) - - let project = Project(projectId: UUID().uuidString, - name: "name") + + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await mutate(.create(project)) _ = savedProject @@ -316,10 +344,10 @@ class GraphQLLazyLoadProjectTeam5Tests: GraphQLLazyLoadBaseTest { extension GraphQLLazyLoadProjectTeam5Tests: DefaultLogger { } extension GraphQLLazyLoadProjectTeam5Tests { - + typealias Project = Project5 typealias Team = Team5 - + struct ProjectTeam5Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -327,12 +355,14 @@ extension GraphQLLazyLoadProjectTeam5Tests { ModelRegistry.register(modelType: Team5.self) } } - + func initializeProjectWithTeam(_ team: Team) -> Project { - return Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + return Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Project5+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Project5+Schema.swift index 16137a68f5..2874eefe08 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Project5+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Project5+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project5 { +public extension Project5 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project5 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let project5 = Project5.keys - + model.pluralName = "Project5s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project5.projectId, project5.name]) ) - + model.fields( .field(project5.projectId, is: .required, ofType: .string), .field(project5.name, is: .required, ofType: .string), @@ -37,9 +44,9 @@ extension Project5 { .field(project5.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Project5: ModelIdentifiable { @@ -47,32 +54,34 @@ extension Project5: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project5.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project5.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } } -extension ModelPath where ModelType == Project5 { - public var projectId: FieldPath { +public extension ModelPath where ModelType == Project5 { + var projectId: FieldPath { string("projectId") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var team: ModelPath { + var team: ModelPath { Team5.Path(name: "team", parent: self) } - public var teamId: FieldPath { + var teamId: FieldPath { string("teamId") } - public var teamName: FieldPath { + var teamName: FieldPath { string("teamName") } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Project5.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Project5.swift index 7dcf7a8e48..7a1f82a8bf 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Project5.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Project5.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Project5: Model { public let projectId: String public let name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team5? { get async throws { try await _team.get() @@ -15,27 +22,33 @@ public struct Project5: Model { public var teamName: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(projectId: String, - name: String, - team: Team5? = nil, - teamId: String? = nil, - teamName: String? = nil) { - self.init(projectId: projectId, + + public init( + projectId: String, + name: String, + team: Team5? = nil, + teamId: String? = nil, + teamName: String? = nil + ) { + self.init( + projectId: projectId, name: name, team: team, teamId: teamId, teamName: teamName, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(projectId: String, - name: String, - team: Team5? = nil, - teamId: String? = nil, - teamName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + projectId: String, + name: String, + team: Team5? = nil, + teamId: String? = nil, + teamName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.projectId = projectId self.name = name self._team = LazyReference(team) @@ -45,17 +58,17 @@ public struct Project5: Model { self.updatedAt = updatedAt } public mutating func setTeam(_ team: Team5? = nil) { - self._team = LazyReference(team) + _team = LazyReference(team) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - projectId = try values.decode(String.self, forKey: .projectId) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - teamId = try? values.decode(String?.self, forKey: .teamId) - teamName = try? values.decode(String?.self, forKey: .teamName) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.projectId = try values.decode(String.self, forKey: .projectId) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.teamId = try? values.decode(String?.self, forKey: .teamId) + self.teamName = try? values.decode(String?.self, forKey: .teamName) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Team5+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Team5+Schema.swift index e1f3f56c0d..3af6bcdc9c 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Team5+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Team5+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team5 { +public extension Team5 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case teamId case name case project case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let team5 = Team5.keys - + model.pluralName = "Team5s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team5.teamId, team5.name]) ) - + model.fields( .field(team5.teamId, is: .required, ofType: .string), .field(team5.name, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension Team5 { .field(team5.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team5: ModelIdentifiable { @@ -43,26 +50,28 @@ extension Team5: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team5.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team5.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } } -extension ModelPath where ModelType == Team5 { - public var teamId: FieldPath { +public extension ModelPath where ModelType == Team5 { + var teamId: FieldPath { string("teamId") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var project: ModelPath { + var project: ModelPath { Project5.Path(name: "project", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Team5.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Team5.swift index a537b5305e..1dbd1fd397 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Team5.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL8/Team5.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Team5: Model { public let teamId: String public let name: String - internal var _project: LazyReference + var _project: LazyReference public var project: Project5? { get async throws { try await _project.get() @@ -13,21 +20,27 @@ public struct Team5: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String, - project: Project5? = nil) { - self.init(teamId: teamId, + + public init( + teamId: String, + name: String, + project: Project5? = nil + ) { + self.init( + teamId: teamId, name: name, project: project, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - project: Project5? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + project: Project5? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self._project = LazyReference(project) @@ -35,15 +48,15 @@ public struct Team5: Model { self.updatedAt = updatedAt } public mutating func setProject(_ project: Project5? = nil) { - self._project = LazyReference(project) + _project = LazyReference(project) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - teamId = try values.decode(String.self, forKey: .teamId) - name = try values.decode(String.self, forKey: .name) - _project = try values.decodeIfPresent(LazyReference.self, forKey: .project) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.teamId = try values.decode(String.self, forKey: .teamId) + self.name = try values.decode(String.self, forKey: .name) + self._project = try values.decodeIfPresent(LazyReference.self, forKey: .project) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/GraphQLLazyLoadProjectTeam6Tests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/GraphQLLazyLoadProjectTeam6Tests.swift index f3f89ae3b2..a047e1adf6 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/GraphQLLazyLoadProjectTeam6Tests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/GraphQLLazyLoadProjectTeam6Tests.swift @@ -5,64 +5,72 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class GraphQLLazyLoadProjectTeam6Tests: GraphQLLazyLoadBaseTest { - + func testSaveTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) try await assertModelExists(savedTeam) } - + func testSaveProject() async throws { await setup(withModels: ProjectTeam6Models()) - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await mutate(.create(project)) try await assertModelExists(savedProject) assertProjectDoesNotContainTeam(savedProject) } - + func testSaveProjectWithTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) - + // Project initializer variation #1 (pass both team reference and fields in) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) let savedProject = try await mutate(.create(project)) let queriedProject = try await query(for: savedProject)! assertProject(queriedProject, hasTeam: savedTeam) - + // Project initializer variation #2 (pass only team reference) - let project2 = Project(projectId: UUID().uuidString, - name: "name", - team: team) + let project2 = Project( + projectId: UUID().uuidString, + name: "name", + team: team + ) let savedProject2 = try await mutate(.create(project2)) let queriedProject2 = try await query(for: savedProject2)! assertProject(queriedProject2, hasTeam: savedTeam) - + // Project initializer variation #3 (pass fields in) - let project3 = Project(projectId: UUID().uuidString, - name: "name", - teamId: team.teamId, - teamName: team.name) + let project3 = Project( + projectId: UUID().uuidString, + name: "name", + teamId: team.teamId, + teamName: team.name + ) let savedProject3 = try await mutate(.create(project3)) let queriedProject3 = try await query(for: savedProject3)! assertProject(queriedProject3, hasTeam: savedTeam) } - + // One-to-One relationships do not create a foreign key for the Team or Project table // So the LazyModel does not have the FK value to be instantiated as metadata for lazy loading. // We only assert the FK fields on the Project exist and are equal to the Team's PK. @@ -70,52 +78,57 @@ class GraphQLLazyLoadProjectTeam6Tests: GraphQLLazyLoadBaseTest { XCTAssertEqual(project.teamId, team.teamId) XCTAssertEqual(project.teamName, team.name) } - + func assertProjectDoesNotContainTeam(_ project: Project) { XCTAssertNil(project.teamId) XCTAssertNil(project.teamName) } - + func testIncludesNestedModels() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") try await mutate(.create(team)) let project = initializeProjectWithTeam(team) try await mutate(.create(project)) - - guard let queriedProject = try await query(.get(Project.self, - byIdentifier: .identifier(projectId: project.projectId, - name: project.name), - includes: { project in [project.team]})) else { + + guard let queriedProject = try await query(.get( + Project.self, + byIdentifier: .identifier( + projectId: project.projectId, + name: project.name + ), + includes: { project in [project.team]} + )) else { XCTFail("Could not perform nested query for Project") return } - + assertLazyReference(queriedProject._team, state: .loaded(model: team)) } - + func testListProjectListTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") try await mutate(.create(team)) let project = initializeProjectWithTeam(team) try await mutate(.create(project)) - + let queriedProjects = try await listQuery(.list(Project.self, where: Project.keys.projectId == project.projectId)) assertList(queriedProjects, state: .isLoaded(count: 1)) assertLazyReference(queriedProjects.first!._team, state: .notLoaded(identifiers: [ .init(name: "teamId", value: team.teamId), - .init(name: "name", value: team.name)])) - + .init(name: "name", value: team.name) + ])) + let queriedTeams = try await listQuery(.list(Team.self, where: Team.keys.teamId == team.teamId)) assertList(queriedTeams, state: .isLoaded(count: 1)) } - + func testSaveProjectWithTeamThenUpdate() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) - + let project = initializeProjectWithTeam(team) let savedProject = try await mutate(.create(project)) assertProject(savedProject, hasTeam: savedTeam) @@ -124,13 +137,13 @@ class GraphQLLazyLoadProjectTeam6Tests: GraphQLLazyLoadBaseTest { let updatedProject = try await mutate(.update(project)) assertProject(updatedProject, hasTeam: savedTeam) } - + func testSaveProjectWithoutTeamUpdateProjectWithTeam() async throws { await setup(withModels: ProjectTeam6Models()) let project = Project(projectId: UUID().uuidString, name: "name") let savedProject = try await mutate(.create(project)) assertProjectDoesNotContainTeam(savedProject) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) var queriedProject = try await query(for: savedProject)! @@ -138,7 +151,7 @@ class GraphQLLazyLoadProjectTeam6Tests: GraphQLLazyLoadBaseTest { let savedProjectWithNewTeam = try await mutate(.update(queriedProject)) assertProject(savedProjectWithNewTeam, hasTeam: savedTeam) } - + func testSaveTeamSaveProjectWithTeamUpdateProjectToNoTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -151,7 +164,7 @@ class GraphQLLazyLoadProjectTeam6Tests: GraphQLLazyLoadBaseTest { let savedProjectWithNoTeam = try await mutate(.update(queriedProject)) assertProjectDoesNotContainTeam(savedProjectWithNoTeam) } - + func testSaveProjectWithTeamUpdateProjectToNewTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -167,7 +180,7 @@ class GraphQLLazyLoadProjectTeam6Tests: GraphQLLazyLoadBaseTest { let savedProjectWithNewTeam = try await mutate(.update(queriedProject)) assertProject(queriedProject, hasTeam: savedNewTeam) } - + func testDeleteTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -176,7 +189,7 @@ class GraphQLLazyLoadProjectTeam6Tests: GraphQLLazyLoadBaseTest { try await mutate(.delete(savedTeam)) try await assertModelDoesNotExist(savedTeam) } - + func testDeleteProject() async throws { await setup(withModels: ProjectTeam6Models()) let project = Project(projectId: UUID().uuidString, name: "name") @@ -185,26 +198,26 @@ class GraphQLLazyLoadProjectTeam6Tests: GraphQLLazyLoadBaseTest { try await mutate(.delete(savedProject)) try await assertModelDoesNotExist(savedProject) } - + func testDeleteProjectWithTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) let project = initializeProjectWithTeam(team) let savedProject = try await mutate(.create(project)) - + try await assertModelExists(savedProject) try await assertModelExists(savedTeam) - + try await mutate(.delete(savedProject)) - + try await assertModelDoesNotExist(savedProject) try await assertModelExists(savedTeam) - + try await mutate(.delete(savedTeam)) try await assertModelDoesNotExist(savedTeam) } - + func testSubscribeToTeam() async throws { await setup(withModels: ProjectTeam6Models()) let connected = expectation(description: "subscription connected") @@ -233,15 +246,15 @@ class GraphQLLazyLoadProjectTeam6Tests: GraphQLLazyLoadBaseTest { XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await mutate(.create(team)) await fulfillment(of: [onCreatedTeam], timeout: 10) subscription.cancel() } - + func testSubscribeProject() async throws { await setup(withModels: ProjectTeam6Models()) let connected = expectation(description: "subscription connected") @@ -270,11 +283,13 @@ class GraphQLLazyLoadProjectTeam6Tests: GraphQLLazyLoadBaseTest { XCTFail("Subscription has terminated with \(error)") } } - + await fulfillment(of: [connected], timeout: 10) - - let project = Project(projectId: UUID().uuidString, - name: "name") + + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await mutate(.create(project)) _ = savedProject @@ -286,10 +301,10 @@ class GraphQLLazyLoadProjectTeam6Tests: GraphQLLazyLoadBaseTest { extension GraphQLLazyLoadProjectTeam6Tests: DefaultLogger { } extension GraphQLLazyLoadProjectTeam6Tests { - + typealias Project = Project6 typealias Team = Team6 - + struct ProjectTeam6Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -297,12 +312,14 @@ extension GraphQLLazyLoadProjectTeam6Tests { ModelRegistry.register(modelType: Team6.self) } } - + func initializeProjectWithTeam(_ team: Team) -> Project { - return Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + return Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Project6+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Project6+Schema.swift index 42f4e459b9..7b3851e013 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Project6+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Project6+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project6 { +public extension Project6 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project6 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let project6 = Project6.keys - + model.pluralName = "Project6s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project6.projectId, project6.name]) ) - + model.fields( .field(project6.projectId, is: .required, ofType: .string), .field(project6.name, is: .required, ofType: .string), @@ -37,9 +44,9 @@ extension Project6 { .field(project6.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Project6: ModelIdentifiable { @@ -47,32 +54,34 @@ extension Project6: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project6.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project6.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } } -extension ModelPath where ModelType == Project6 { - public var projectId: FieldPath { +public extension ModelPath where ModelType == Project6 { + var projectId: FieldPath { string("projectId") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var team: ModelPath { + var team: ModelPath { Team6.Path(name: "team", parent: self) } - public var teamId: FieldPath { + var teamId: FieldPath { string("teamId") } - public var teamName: FieldPath { + var teamName: FieldPath { string("teamName") } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Project6.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Project6.swift index 3d1edb33d0..5ca78076b4 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Project6.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Project6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Project6: Model { public let projectId: String public let name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team6? { get async throws { try await _team.get() @@ -15,27 +22,33 @@ public struct Project6: Model { public var teamName: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(projectId: String, - name: String, - team: Team6? = nil, - teamId: String? = nil, - teamName: String? = nil) { - self.init(projectId: projectId, + + public init( + projectId: String, + name: String, + team: Team6? = nil, + teamId: String? = nil, + teamName: String? = nil + ) { + self.init( + projectId: projectId, name: name, team: team, teamId: teamId, teamName: teamName, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(projectId: String, - name: String, - team: Team6? = nil, - teamId: String? = nil, - teamName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + projectId: String, + name: String, + team: Team6? = nil, + teamId: String? = nil, + teamName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.projectId = projectId self.name = name self._team = LazyReference(team) @@ -45,17 +58,17 @@ public struct Project6: Model { self.updatedAt = updatedAt } public mutating func setTeam(_ team: Team6? = nil) { - self._team = LazyReference(team) + _team = LazyReference(team) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - projectId = try values.decode(String.self, forKey: .projectId) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - teamId = try? values.decode(String?.self, forKey: .teamId) - teamName = try? values.decode(String?.self, forKey: .teamName) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.projectId = try values.decode(String.self, forKey: .projectId) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.teamId = try? values.decode(String?.self, forKey: .teamId) + self.teamName = try? values.decode(String?.self, forKey: .teamName) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Team6+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Team6+Schema.swift index 43413e34c5..22b66249ec 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Team6+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Team6+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team6 { +public extension Team6 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case teamId case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let team6 = Team6.keys - + model.pluralName = "Team6s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team6.teamId, team6.name]) ) - + model.fields( .field(team6.teamId, is: .required, ofType: .string), .field(team6.name, is: .required, ofType: .string), @@ -31,9 +38,9 @@ extension Team6 { .field(team6.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team6: ModelIdentifiable { @@ -41,23 +48,25 @@ extension Team6: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team6.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team6.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } } -extension ModelPath where ModelType == Team6 { - public var teamId: FieldPath { +public extension ModelPath where ModelType == Team6 { + var teamId: FieldPath { string("teamId") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Team6.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Team6.swift index b247d9bffd..3a45fc3f04 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Team6.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginLazyLoadTests/LL9/Team6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,18 +14,24 @@ public struct Team6: Model { public let name: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String) { - self.init(teamId: teamId, + + public init( + teamId: String, + name: String + ) { + self.init( + teamId: teamId, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginRESTIAMTests/RESTWithIAMIntegrationTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginRESTIAMTests/RESTWithIAMIntegrationTests.swift index b63c8d2fda..409adefe90 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginRESTIAMTests/RESTWithIAMIntegrationTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginRESTIAMTests/RESTWithIAMIntegrationTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSAPIPlugin import AWSCognitoAuthPlugin +import XCTest @testable import Amplify #if os(watchOS) @@ -19,7 +19,7 @@ import AWSCognitoAuthPlugin class RESTWithIAMIntegrationTests: XCTestCase { static let amplifyConfiguration = "testconfiguration/RESTWithIAMIntegrationTests-amplifyconfiguration" - + override func setUp() async throws { do { @@ -58,7 +58,7 @@ class RESTWithIAMIntegrationTests: XCTestCase { XCTFail("Error should be APIError") return } - + guard case let .httpStatusError(statusCode, response) = apiError else { XCTFail("Error should be httpStatusError") return @@ -80,22 +80,26 @@ class RESTWithIAMIntegrationTests: XCTestCase { // TODO: Should not be HTTPStatusError func testGetAPIWithQueryParamsSuccess() async throws { - let request = RESTRequest(path: "/items", - queryParameters: [ - "user": "hello@email.com", - "created": "2021-06-18T09:00:00Z" - ]) + let request = RESTRequest( + path: "/items", + queryParameters: [ + "user": "hello@email.com", + "created": "2021-06-18T09:00:00Z" + ] + ) let data = try await Amplify.API.get(request: request) let result = String(decoding: data, as: UTF8.self) log.info(result) } func testGetAPIWithEncodedQueryParamsSuccess() async throws { - let request = RESTRequest(path: "/items", - queryParameters: [ - "user": "hello%40email.com", - "created": "2021-06-18T09%3A00%3A00Z" - ]) + let request = RESTRequest( + path: "/items", + queryParameters: [ + "user": "hello%40email.com", + "created": "2021-06-18T09%3A00%3A00Z" + ] + ) let data = try await Amplify.API.get(request: request) let result = String(decoding: data, as: UTF8.self) log.info(result) @@ -136,7 +140,7 @@ class RESTWithIAMIntegrationTests: XCTestCase { XCTFail("Error should be httpStatusError") return } - + XCTAssertEqual(statusCode, 403) } } @@ -155,7 +159,7 @@ class RESTWithIAMIntegrationTests: XCTestCase { XCTFail("Error should be httpStatusError") return } - + XCTAssertEqual(statusCode, 404) } } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginRESTUserPoolTests/RESTWithUserPoolIntegrationTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginRESTUserPoolTests/RESTWithUserPoolIntegrationTests.swift index a60d362d98..2ed35f9a7e 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginRESTUserPoolTests/RESTWithUserPoolIntegrationTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/AWSAPIPluginRESTUserPoolTests/RESTWithUserPoolIntegrationTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSAPIPlugin import AWSCognitoAuthPlugin import AWSPluginsCore +import XCTest @testable import Amplify @testable import APIHostApp @@ -27,7 +27,7 @@ class RESTWithUserPoolIntegrationTests: XCTestCase { try Amplify.add(plugin: AWSAPIPlugin()) try Amplify.add(plugin: AWSCognitoAuthPlugin()) let amplifyConfig = try TestConfigHelper.retrieveAmplifyConfiguration( - forResource:RESTWithUserPoolIntegrationTests.amplifyConfigurationFile) + forResource: RESTWithUserPoolIntegrationTests.amplifyConfigurationFile) try Amplify.configure(amplifyConfig) } catch { XCTFail("Error during setup: \(error)") @@ -40,7 +40,7 @@ class RESTWithUserPoolIntegrationTests: XCTestCase { } await Amplify.reset() } - + func testSetUp() { XCTAssertTrue(true) } @@ -48,7 +48,7 @@ class RESTWithUserPoolIntegrationTests: XCTestCase { func testCreateUser() async throws { try await createAuthenticatedUser() } - + func testCreateUserAndGetToken() async throws { try await createAuthenticatedUser() let session = try await Amplify.Auth.fetchAuthSession() @@ -59,7 +59,7 @@ class RESTWithUserPoolIntegrationTests: XCTestCase { print("Access token - \(tokens.accessToken) ") } } - + func testGetAPISuccess() async throws { try await createAuthenticatedUser() let request = RESTRequest(path: "/items") @@ -70,11 +70,13 @@ class RESTWithUserPoolIntegrationTests: XCTestCase { func testGetAPIWithQueryParamsSuccess() async throws { try await createAuthenticatedUser() - let request = RESTRequest(path: "/items", - queryParameters: [ - "user": "hello@email.com", - "created": "2021-06-18T09:00:00Z" - ]) + let request = RESTRequest( + path: "/items", + queryParameters: [ + "user": "hello@email.com", + "created": "2021-06-18T09:00:00Z" + ] + ) let data = try await Amplify.API.get(request: request) let result = String(decoding: data, as: UTF8.self) print(result) @@ -82,11 +84,13 @@ class RESTWithUserPoolIntegrationTests: XCTestCase { func testGetAPIWithEncodedQueryParamsSuccess() async throws { try await createAuthenticatedUser() - let request = RESTRequest(path: "/items", - queryParameters: [ - "user": "hello%40email.com", - "created": "2021-06-18T09%3A00%3A00Z" - ]) + let request = RESTRequest( + path: "/items", + queryParameters: [ + "user": "hello%40email.com", + "created": "2021-06-18T09%3A00%3A00Z" + ] + ) let data = try await Amplify.API.get(request: request) let result = String(decoding: data, as: UTF8.self) print(result) @@ -103,7 +107,7 @@ class RESTWithUserPoolIntegrationTests: XCTestCase { XCTFail("Should be APIError") return } - + guard case let .operationError(_, _, underlyingError) = apiError else { XCTFail("Error should be operationError") return @@ -120,9 +124,9 @@ class RESTWithUserPoolIntegrationTests: XCTestCase { } } } - + // MARK: - Auth Helpers - + func createAuthenticatedUser() async throws { if try await isSignedIn() { await signOut() @@ -130,12 +134,12 @@ class RESTWithUserPoolIntegrationTests: XCTestCase { try await signUp() try await signIn() } - + func isSignedIn() async throws -> Bool { let authSession = try await Amplify.Auth.fetchAuthSession() return authSession.isSignedIn } - + func signUp() async throws { let signUpResult = try await Amplify.Auth.signUp(username: username, password: password) guard signUpResult.isSignUpComplete else { @@ -144,16 +148,18 @@ class RESTWithUserPoolIntegrationTests: XCTestCase { } } - + func signIn() async throws { - let signInResult = try await Amplify.Auth.signIn(username: username, - password: password) + let signInResult = try await Amplify.Auth.signIn( + username: username, + password: password + ) guard signInResult.isSignedIn else { XCTFail("Sign in successful but not complete") return } } - + func signOut() async { _ = await Amplify.Auth.signOut() } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/GraphQLAPIStressTests.swift b/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/GraphQLAPIStressTests.swift index 2746a5fea3..219783795d 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/GraphQLAPIStressTests.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/GraphQLAPIStressTests.swift @@ -6,48 +6,48 @@ // import XCTest -@testable import AWSAPIPlugin @testable import Amplify @testable import APIHostApp +@testable import AWSAPIPlugin /* Model Schema - + type Post @model @auth(rules: [{ allow: public }]) { id: ID! title: String! status: PostStatus! content: String! } - + enum PostStatus { ACTIVE INACTIVE } - + */ final class APIStressTests: XCTestCase { static let amplifyConfiguration = "testconfiguration/AWSGraphQLAPIStressTests-amplifyconfiguration" let concurrencyLimit = 50 - - final public class TestModelRegistration: AmplifyModelRegistration { + + public final class TestModelRegistration: AmplifyModelRegistration { public func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post.self) } - + public let version: String = "1" } - + override func setUp() async throws { await Amplify.reset() Amplify.Logging.logLevel = .verbose let plugin = AWSAPIPlugin(modelRegistration: TestModelRegistration()) - + do { try Amplify.add(plugin: plugin) - + let amplifyConfig = try TestConfigHelper.retrieveAmplifyConfiguration( forResource: Self.amplifyConfiguration) try Amplify.configure(amplifyConfig) @@ -55,13 +55,13 @@ final class APIStressTests: XCTestCase { XCTFail("Error during setup: \(error)") } } - + override func tearDown() async throws { await Amplify.reset() } // MARK: - Stress tests - + /// - Given: APIPlugin configured with valid configuration and schema /// - When: I create 50 subsciptions on createPost mutation and then create a Post /// - Then: Subscriptions should receive connected, disconnected and progress events correctly @@ -108,23 +108,23 @@ final class APIStressTests: XCTestCase { } completedInvoked.fulfill() } - + await sequenceActor.append(sequence: subscription) } } - + await fulfillment(of: [connectedInvoked], timeout: TestCommonConstants.networkTimeout) - + let sequenceCount = await sequenceActor.sequences.count XCTAssertEqual(sequenceCount, concurrencyLimit) - + guard try await createPost(id: uuid, title: title) != nil else { XCTFail("Failed to create post") return } await fulfillment(of: [progressInvoked], timeout: TestCommonConstants.networkTimeout) - + DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in Task { await sequenceActor.sequences[index].cancel() @@ -133,7 +133,7 @@ final class APIStressTests: XCTestCase { await fulfillment(of: [disconnectedInvoked, completedInvoked], timeout: TestCommonConstants.networkTimeout) } - + /// - Given: APIPlugin configured with valid configuration and schema /// - When: I create 50 posts simultaneously /// - Then: Operation should succeed @@ -151,10 +151,10 @@ final class APIStressTests: XCTestCase { postCreateExpectation.fulfill() } } - + await fulfillment(of: [postCreateExpectation], timeout: TestCommonConstants.networkTimeout) } - + /// - Given: APIPlugin configured with valid configuration and schema and 50 posts saved /// - When: I update 50 post simultaneously /// - Then: Operation should succeed @@ -164,7 +164,7 @@ final class APIStressTests: XCTestCase { let postUpdateExpectation = expectation(description: "Post was updated successfully") postUpdateExpectation.expectedFulfillmentCount = concurrencyLimit let postActor = PostActor() - + DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in Task { let id = UUID().uuidString @@ -179,7 +179,7 @@ final class APIStressTests: XCTestCase { } await fulfillment(of: [postCreateExpectation], timeout: TestCommonConstants.networkTimeout) - + DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in Task { var post = await postActor.posts[index] @@ -191,10 +191,10 @@ final class APIStressTests: XCTestCase { postUpdateExpectation.fulfill() } } - + await fulfillment(of: [postUpdateExpectation], timeout: TestCommonConstants.networkTimeout) } - + /// - Given: APIPlugin configured with valid configuration, schema and 50 posts saved /// - When: I delete 50 post simultaneously /// - Then: Operation should succeed @@ -206,7 +206,7 @@ final class APIStressTests: XCTestCase { postDeleteExpectation.expectedFulfillmentCount = concurrencyLimit let postActor = PostActor() - + DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in Task { let id = UUID().uuidString @@ -221,7 +221,7 @@ final class APIStressTests: XCTestCase { } await fulfillment(of: [postCreateExpectation], timeout: TestCommonConstants.networkTimeout) - + DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in Task { let post = await postActor.posts[index] @@ -232,10 +232,10 @@ final class APIStressTests: XCTestCase { postDeleteExpectation.fulfill() } } - + await fulfillment(of: [postDeleteExpectation], timeout: TestCommonConstants.networkTimeout) } - + /// - Given: APIPlugin configured with valid configuration, schema and 50 posts saved /// - When: I query for 50 posts simultaneously /// - Then: Operation should succeed @@ -247,7 +247,7 @@ final class APIStressTests: XCTestCase { postQueryExpectation.expectedFulfillmentCount = concurrencyLimit let postActor = PostActor() - + DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in Task { let id = UUID().uuidString @@ -262,7 +262,7 @@ final class APIStressTests: XCTestCase { } await fulfillment(of: [postCreateExpectation], timeout: TestCommonConstants.networkTimeout) - + DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in Task { let post = await postActor.posts[index] @@ -281,24 +281,24 @@ final class APIStressTests: XCTestCase { postQueryExpectation.fulfill() } } - + await fulfillment(of: [postQueryExpectation], timeout: TestCommonConstants.networkTimeout) } - + actor PostActor { var posts: [Post] = [] func append(post: Post) { posts.append(post) } } - + actor SequenceActor { var sequences: [AmplifyAsyncThrowingSequence>] = [] func append(sequence: AmplifyAsyncThrowingSequence>) { sequences.append(sequence) } } - + // MARK: - Helpers func createPost(id: String, title: String) async throws -> Post? { diff --git a/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/Models/AmplifyModels.swift b/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/Models/AmplifyModels.swift index 96eef29957..167804f3b4 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/Models/AmplifyModels.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/Models/AmplifyModels.swift @@ -9,11 +9,11 @@ import Amplify import Foundation -// Contains the set of classes that conforms to the `Model` protocol. +// Contains the set of classes that conforms to the `Model` protocol. -final public class AmplifyModels: AmplifyModelRegistration { +public final class AmplifyModels: AmplifyModelRegistration { public let version: String = "9ddf09113aaee75fdec53f41fd7a73d7" - + public func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post.self) } diff --git a/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/Models/Post+Schema.swift b/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/Models/Post+Schema.swift index 96d24f0a99..a1b369d614 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/Models/Post+Schema.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/Models/Post+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case status @@ -19,23 +19,23 @@ extension Post { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post = Post.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Posts" - + model.attributes( .primaryKey(fields: [post.id]) ) - + model.fields( .field(post.id, is: .required, ofType: .string), .field(post.title, is: .required, ofType: .string), diff --git a/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/Models/Post.swift b/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/Models/Post.swift index 3658db511f..c5a0adeaac 100644 --- a/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/Models/Post.swift +++ b/AmplifyPlugins/API/Tests/APIHostApp/GraphQLAPIStressTests/Models/Post.swift @@ -16,24 +16,30 @@ public struct Post: Model { public var content: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - status: PostStatus, - content: String) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + status: PostStatus, + content: String + ) { + self.init( + id: id, title: title, status: status, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - status: PostStatus, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + status: PostStatus, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.status = status diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTestCommon/Model/Todo.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTestCommon/Model/Todo.swift index 90ef943ad5..67bb6fb833 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTestCommon/Model/Todo.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTestCommon/Model/Todo.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// TODO: Replace with AmplifyTestCommon's DataStore's geneated model /// This model corresponds to the resources created for the Todo graphQL endpoint. As a developer, this is @@ -51,13 +51,13 @@ class CreateTodoMutation { static func variables(id: String? = nil, name: String, description: String? = nil) -> [String: Any] { var input: [String: Any] = [:] - if let id = id { + if let id { input.updateValue(id, forKey: "id") } input.updateValue(name, forKey: "name") - if let description = description { + if let description { input.updateValue(description, forKey: "description") } @@ -93,10 +93,10 @@ class UpdateTodoMutation { static func variables(id: String, name: String? = nil, description: String? = nil) -> [String: Any] { var input: [String: Any] = [:] input.updateValue(id, forKey: "id") - if let name = name { + if let name { input.updateValue(name, forKey: "name") } - if let description = description { + if let description { input.updateValue(description, forKey: "description") } return ["input": input] @@ -120,7 +120,7 @@ class DeleteTodoMutation { static func variables(id: String?) -> [String: Any] { var input: [String: Any] = [:] - if let id = id { + if let id { input.updateValue(id, forKey: "id") } @@ -167,20 +167,22 @@ class ListTodosQuery { }\n} """ - static func variables(filter: [String: Any]? = nil, - limit: Int? = nil, - nextToken: String? = nil) -> [String: Any] { + static func variables( + filter: [String: Any]? = nil, + limit: Int? = nil, + nextToken: String? = nil + ) -> [String: Any] { var input: [String: Any] = [:] - if let filter = filter { + if let filter { input.updateValue(filter, forKey: "filter") } - if let limit = limit { + if let limit { input.updateValue(limit, forKey: "limit") } - if let nextToken = nextToken { + if let nextToken { input.updateValue(nextToken, forKey: "nextToken") } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/APISwiftCompatibility/API.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/APISwiftCompatibility/API.swift index 30ac29f279..e6d668e899 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/APISwiftCompatibility/API.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/APISwiftCompatibility/API.swift @@ -1,11 +1,20 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // This file was automatically generated and should not be edited. +// swiftlint:disable all +// swiftformat:disable all #if canImport(AWSAPIPlugin) import Foundation public protocol GraphQLInputValue { } public struct GraphQLVariable { let name: String - + public init(_ name: String) { self.name = name } @@ -39,13 +48,13 @@ public extension GraphQLMapConvertible { } public typealias GraphQLID = String public protocol APISwiftGraphQLOperation: AnyObject { - + static var operationString: String { get } static var requestString: String { get } static var operationIdentifier: String? { get } - + var variables: GraphQLMap? { get } - + associatedtype Data: GraphQLSelectionSet } public extension APISwiftGraphQLOperation { @@ -68,7 +77,7 @@ public protocol GraphQLFragment: GraphQLSelectionSet { public typealias Snapshot = [String: Any?] public protocol GraphQLSelectionSet: Decodable { static var selections: [GraphQLSelection] { get } - + var snapshot: Snapshot { get } init(snapshot: Snapshot) } @@ -92,10 +101,10 @@ enum APISwiftJSONValue: Codable { case object([String: APISwiftJSONValue]) case string(String) case null - + init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() - + if let value = try? container.decode([String: APISwiftJSONValue].self) { self = .object(value) } else if let value = try? container.decode([APISwiftJSONValue].self) { @@ -110,10 +119,10 @@ enum APISwiftJSONValue: Codable { self = .null } } - + func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() - + switch self { case .array(let value): try container.encode(value) @@ -136,19 +145,19 @@ public struct GraphQLField: GraphQLSelection { let name: String let alias: String? let arguments: [String: GraphQLInputValue]? - + var responseKey: String { return alias ?? name } - + let type: GraphQLOutputType - + public init(_ name: String, alias: String? = nil, arguments: [String: GraphQLInputValue]? = nil, type: GraphQLOutputType) { self.name = name self.alias = alias - + self.arguments = arguments - + self.type = type } } @@ -157,7 +166,7 @@ public indirect enum GraphQLOutputType { case object([GraphQLSelection]) case nonNull(GraphQLOutputType) case list(GraphQLOutputType) - + var namedType: GraphQLOutputType { switch self { case .nonNull(let innerType), .list(let innerType): @@ -171,7 +180,7 @@ public struct GraphQLBooleanCondition: GraphQLSelection { let variableName: String let inverted: Bool let selections: [GraphQLSelection] - + public init(variableName: String, inverted: Bool, selections: [GraphQLSelection]) { self.variableName = variableName self.inverted = inverted; @@ -181,7 +190,7 @@ public struct GraphQLBooleanCondition: GraphQLSelection { public struct GraphQLTypeCondition: GraphQLSelection { let possibleTypes: [String] let selections: [GraphQLSelection] - + public init(possibleTypes: [String], selections: [GraphQLSelection]) { self.possibleTypes = possibleTypes self.selections = selections; @@ -189,7 +198,7 @@ public struct GraphQLTypeCondition: GraphQLSelection { } public struct GraphQLFragmentSpread: GraphQLSelection { let fragment: GraphQLFragment.Type - + public init(_ fragment: GraphQLFragment.Type) { self.fragment = fragment } @@ -197,7 +206,7 @@ public struct GraphQLFragmentSpread: GraphQLSelection { public struct GraphQLTypeCase: GraphQLSelection { let variants: [String: [GraphQLSelection]] let `default`: [GraphQLSelection] - + public init(variants: [String: [GraphQLSelection]], default: [GraphQLSelection]) { self.variants = variants self.default = `default`; @@ -215,7 +224,7 @@ public enum JSONDecodingError: Error, LocalizedError { case nullValue case wrongType case couldNotConvert(value: Any, to: Any.Type) - + public var errorDescription: String? { switch self { case .missingValue: @@ -324,7 +333,7 @@ extension Dictionary: JSONEncodable { public var jsonValue: Any { return jsonObject } - + public var jsonObject: JSONObject { var jsonObject = JSONObject(minimumCapacity: count) for (key, value) in self { diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/APISwiftCompatibility/APISwiftTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/APISwiftCompatibility/APISwiftTests.swift index e2b405da1d..482021a53f 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/APISwiftCompatibility/APISwiftTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/APISwiftCompatibility/APISwiftTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest final class APISwiftTests: XCTestCase { @@ -15,12 +15,13 @@ final class APISwiftTests: XCTestCase { let input = CreateBlogInput(name: "name", file: file) let condition = ModelBlogConditionInput(name: .init(eq: "name")) let mutation = CreateBlogMutation(input: input) - + let request = GraphQLRequest( document: CreateBlogMutation.requestString, variables: mutation.variables?.jsonObject, - responseType: CreateBlogMutation.Data.self) - + responseType: CreateBlogMutation.Data.self + ) + var expectedDocument = """ mutation CreateBlog($input: CreateBlogInput!, $condition: ModelBlogConditionInput) { createBlog(input: $input, condition: $condition) { diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+ConfigureTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+ConfigureTests.swift index 8d16c47b05..340abe5027 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+ConfigureTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+ConfigureTests.swift @@ -43,7 +43,8 @@ class AWSAPICategoryPluginConfigureTests: AWSAPICategoryPluginTestBase { let plugin = AWSAPIPlugin() XCTAssertThrowsError(try plugin.configure(using: nil)) { error in guard let apiError = error as? PluginError, - case .pluginConfigurationError = apiError else { + case .pluginConfigurationError = apiError + else { XCTFail("Should throw invalidConfiguration exception. But received \(error) ") return } @@ -58,7 +59,8 @@ class AWSAPICategoryPluginConfigureTests: AWSAPICategoryPluginTestBase { modelIntrospection: nil, apiKey: "apiKey123", defaultAuthorizationType: .amazonCognitoUserPools, - authorizationTypes: [.apiKey, .awsIAM])) + authorizationTypes: [.apiKey, .awsIAM] + )) let plugin = AWSAPIPlugin() try plugin.configure(using: config) @@ -82,7 +84,8 @@ class AWSAPICategoryPluginConfigureTests: AWSAPICategoryPluginTestBase { let plugin = AWSAPIPlugin() XCTAssertThrowsError(try plugin.configure(using: config)) { error in guard let apiError = error as? PluginError, - case .pluginConfigurationError = apiError else { + case .pluginConfigurationError = apiError + else { XCTFail("Should throw invalidConfiguration exception. But received \(error) ") return } @@ -97,12 +100,14 @@ class AWSAPICategoryPluginConfigureTests: AWSAPICategoryPluginTestBase { modelIntrospection: nil, apiKey: nil, defaultAuthorizationType: .apiKey, - authorizationTypes: [])) + authorizationTypes: [] + )) let plugin = AWSAPIPlugin() XCTAssertThrowsError(try plugin.configure(using: config)) { error in guard let apiError = error as? PluginError, - case .pluginConfigurationError = apiError else { + case .pluginConfigurationError = apiError + else { XCTFail("Should throw invalidConfiguration exception. But received \(error) ") return } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+GraphQLBehaviorTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+GraphQLBehaviorTests.swift index 74065cd3e5..a76766b5e1 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+GraphQLBehaviorTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+GraphQLBehaviorTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify -@testable import AWSAPIPlugin import AWSPluginsCore +import XCTest +@testable import AWSAPIPlugin class AWSAPICategoryPluginGraphQLBehaviorTests: AWSAPICategoryPluginTestBase { @@ -16,11 +16,13 @@ class AWSAPICategoryPluginGraphQLBehaviorTests: AWSAPICategoryPluginTestBase { func testQuery() async { let operationFinished = expectation(description: "Operation should finish") - let request = GraphQLRequest(apiName: apiName, - document: testDocument, - variables: nil, - responseType: JSONValue.self, - authMode: AWSAuthorizationType.apiKey) + let request = GraphQLRequest( + apiName: apiName, + document: testDocument, + variables: nil, + responseType: JSONValue.self, + authMode: AWSAuthorizationType.apiKey + ) let operation = apiPlugin.query(request: request) { _ in operationFinished.fulfill() } @@ -46,10 +48,12 @@ class AWSAPICategoryPluginGraphQLBehaviorTests: AWSAPICategoryPluginTestBase { func testMutate() async { let operationFinished = expectation(description: "Operation should finish") - let request = GraphQLRequest(apiName: apiName, - document: testDocument, - variables: nil, - responseType: JSONValue.self) + let request = GraphQLRequest( + apiName: apiName, + document: testDocument, + variables: nil, + responseType: JSONValue.self + ) let operation = apiPlugin.mutate(request: request) { _ in operationFinished.fulfill() } @@ -75,10 +79,12 @@ class AWSAPICategoryPluginGraphQLBehaviorTests: AWSAPICategoryPluginTestBase { func testSubscribe() async { let operationFinished = expectation(description: "Operation should finish") - let request = GraphQLRequest(apiName: apiName, - document: testDocument, - variables: nil, - responseType: JSONValue.self) + let request = GraphQLRequest( + apiName: apiName, + document: testDocument, + variables: nil, + responseType: JSONValue.self + ) let operation = apiPlugin.subscribe(request: request, valueListener: nil) { _ in operationFinished.fulfill() } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+InterceptorBehaviorTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+InterceptorBehaviorTests.swift index ac458b9992..258229e3b3 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+InterceptorBehaviorTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+InterceptorBehaviorTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -@testable import AWSAPIPlugin import AWSPluginsCore import InternalAmplifyCredentials +import XCTest +@testable import AWSAPIPlugin // swiftlint:disable:next type_name class AWSAPICategoryPluginInterceptorBehaviorTests: AWSAPICategoryPluginTestBase { diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+RESTClientBehaviorTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+RESTClientBehaviorTests.swift index 84647ff9dd..8f8857f922 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+RESTClientBehaviorTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+RESTClientBehaviorTests.swift @@ -8,8 +8,8 @@ import XCTest @testable import Amplify -@testable import AWSAPIPlugin @testable import AmplifyTestCommon +@testable import AWSAPIPlugin // swiftlint:disable:next type_name class AWSAPICategoryPluginRESTClientBehaviorTests: AWSAPICategoryPluginTestBase { diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+ReachabilityTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+ReachabilityTests.swift index 2d005cbdf1..5a3108758f 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+ReachabilityTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+ReachabilityTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Foundation import AWSPluginsCore +import Foundation +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -31,7 +31,7 @@ class AWSAPICategoryPluginReachabilityTests: XCTestCase { func testReachabilityReturnsGraphQLAPI() throws { let graphQLAPI = "graphQLAPI" do { - let endpointConfig = [graphQLAPI: try getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL)] + let endpointConfig = try [graphQLAPI: getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL)] let pluginConfig = AWSAPICategoryPluginConfiguration(endpoints: endpointConfig) let dependencies = AWSAPIPlugin.ConfigurationDependencies( pluginConfig: pluginConfig, @@ -58,8 +58,10 @@ class AWSAPICategoryPluginReachabilityTests: XCTestCase { let graphQLAPI = "graphQLAPI" let restAPI = "restAPI" do { - let endpointConfig = [graphQLAPI: try getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), - restAPI: try getEndpointConfig(apiName: restAPI, endpointType: .rest)] + let endpointConfig = try [ + graphQLAPI: getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), + restAPI: getEndpointConfig(apiName: restAPI, endpointType: .rest) + ] let pluginConfig = AWSAPICategoryPluginConfiguration(endpoints: endpointConfig) let dependencies = AWSAPIPlugin.ConfigurationDependencies( pluginConfig: pluginConfig, @@ -86,8 +88,10 @@ class AWSAPICategoryPluginReachabilityTests: XCTestCase { let graphQLAPI = "graphQLAPI" let restAPI = "restAPI" do { - let endpointConfig = [graphQLAPI: try getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), - restAPI: try getEndpointConfig(apiName: restAPI, endpointType: .rest)] + let endpointConfig = try [ + graphQLAPI: getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), + restAPI: getEndpointConfig(apiName: restAPI, endpointType: .rest) + ] let pluginConfig = AWSAPICategoryPluginConfiguration(endpoints: endpointConfig) let dependencies = AWSAPIPlugin.ConfigurationDependencies( pluginConfig: pluginConfig, @@ -128,6 +132,7 @@ class AWSAPICategoryPluginReachabilityTests: XCTestCase { region: nil, authorizationType: AWSAuthorizationType.none, endpointType: endpointType, - apiAuthProviderFactory: APIAuthProviderFactory()) + apiAuthProviderFactory: APIAuthProviderFactory() + ) } } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPluginAmplifyVersionableTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPluginAmplifyVersionableTests.swift index a6e412c5cd..f033051f18 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPluginAmplifyVersionableTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPluginAmplifyVersionableTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSAPIPlugin +import XCTest // swiftlint:disable:next type_name class AWSAPICategoryPluginAmplifyVersionableTests: XCTestCase { diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPluginTestBase.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPluginTestBase.swift index 9d6fa2b283..d270f0c6ac 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPluginTestBase.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPluginTestBase.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Foundation +import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSAPIPlugin @@ -38,18 +38,22 @@ class AWSAPICategoryPluginTestBase: XCTestCase { self.authService = authService do { - let endpointConfig = [apiName: try AWSAPICategoryPluginConfiguration.EndpointConfig( + let endpointConfig = try [apiName: AWSAPICategoryPluginConfiguration.EndpointConfig( name: apiName, baseURL: baseURL, region: region, authorizationType: AWSAuthorizationType.none, endpointType: .graphQL, - apiAuthProviderFactory: apiAuthProvider)] + apiAuthProviderFactory: apiAuthProvider + )] let interceptors = [apiName: AWSAPIEndpointInterceptors( - endpointName: apiName, - apiAuthProviderFactory: apiAuthProvider)] - let pluginConfig = AWSAPICategoryPluginConfiguration(endpoints: endpointConfig, - interceptors: interceptors) + endpointName: apiName, + apiAuthProviderFactory: apiAuthProvider + )] + let pluginConfig = AWSAPICategoryPluginConfiguration( + endpoints: endpointConfig, + interceptors: interceptors + ) self.pluginConfig = pluginConfig let dependencies = AWSAPIPlugin.ConfigurationDependencies( diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AppSyncRealTimeClient/AppSyncRealTimeClientTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AppSyncRealTimeClient/AppSyncRealTimeClientTests.swift index 99b36943f1..b1358f463e 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AppSyncRealTimeClient/AppSyncRealTimeClientTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AppSyncRealTimeClient/AppSyncRealTimeClientTests.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - -import XCTest -import Combine import Amplify +import Combine +import XCTest @_spi(WebSocket) import AWSPluginsCore @testable import AWSAPIPlugin @@ -58,7 +57,7 @@ class AppSyncRealTimeClientTests: XCTestCase { } } Task { - try await Task.sleep(nanoseconds: 80 * 1000) + try await Task.sleep(nanoseconds: 80 * 1_000) await appSyncClient.subject.send(.success(.init(id: nil, payload: nil, type: .connectionAck))) } await fulfillment(of: [finishExpectation], timeout: timeout + 1) @@ -90,7 +89,7 @@ class AppSyncRealTimeClientTests: XCTestCase { } } Task { - try await Task.sleep(nanoseconds: 80 * 1000) + try await Task.sleep(nanoseconds: 80 * 1_000) await appSyncClient.subject.send(.success(.init( id: id, payload: .object([ @@ -133,7 +132,7 @@ class AppSyncRealTimeClientTests: XCTestCase { } Task { - try await Task.sleep(nanoseconds: 80 * 1000) + try await Task.sleep(nanoseconds: 80 * 1_000) await appSyncClient.subject.send(.success(.init( id: id, payload: .object([ @@ -180,7 +179,7 @@ class AppSyncRealTimeClientTests: XCTestCase { } Task { - try await Task.sleep(nanoseconds: 80 * 1000) + try await Task.sleep(nanoseconds: 80 * 1_000) await appSyncClient.subject.send(.success(.init( id: id, payload: .object([ @@ -519,8 +518,7 @@ class AppSyncRealTimeClientTests: XCTestCase { errors.count == 1, let error = errors.first, let connectionLostError = error as? WebSocketClient.Error, - connectionLostError == WebSocketClient.Error.connectionLost - { + connectionLostError == WebSocketClient.Error.connectionLost { errorReceived.fulfill() } }.store(in: &cancellables) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AppSyncRealTimeClient/AppSyncRealTimeRequestAuthTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AppSyncRealTimeClient/AppSyncRealTimeRequestAuthTests.swift index ba57f00238..a6fc741fe6 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AppSyncRealTimeClient/AppSyncRealTimeRequestAuthTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AppSyncRealTimeClient/AppSyncRealTimeRequestAuthTests.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import XCTest @testable import AWSAPIPlugin @@ -180,9 +179,9 @@ class AppSyncRealTimeRequestAuthTests: XCTestCase { } } -fileprivate extension String { +private extension String { func shrink() -> String { - return self.replacingOccurrences(of: "\n", with: "") + return replacingOccurrences(of: "\n", with: "") .replacingOccurrences(of: " ", with: "") } } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Configuration/AWSAPICategoryPluginConfigurationEndpointConfigTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Configuration/AWSAPICategoryPluginConfigurationEndpointConfigTests.swift index be200d23a2..717233ab6b 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Configuration/AWSAPICategoryPluginConfigurationEndpointConfigTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Configuration/AWSAPICategoryPluginConfigurationEndpointConfigTests.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore +import XCTest @testable import Amplify -@testable import AWSAPIPlugin @testable import AmplifyTestCommon +@testable import AWSAPIPlugin // swiftlint:disable:next type_name class AWSAPICategoryPluginConfigurationEndpointConfigTests: XCTestCase { @@ -20,7 +20,7 @@ class AWSAPICategoryPluginConfigurationEndpointConfigTests: XCTestCase { let restAPI2 = "restAPI2" func testGetConfigAPIName() throws { - let endpointConfig = [graphQLAPI: try getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL)] + let endpointConfig = try [graphQLAPI: getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL)] let endpoint = try endpointConfig.getConfig(for: graphQLAPI) @@ -29,7 +29,7 @@ class AWSAPICategoryPluginConfigurationEndpointConfigTests: XCTestCase { } func testGetConfigAPINameFailsWhenInvalidAPIName() throws { - let endpointConfig = [graphQLAPI: try getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL)] + let endpointConfig = try [graphQLAPI: getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL)] do { _ = try endpointConfig.getConfig(for: "incorrectAPIName") @@ -44,8 +44,10 @@ class AWSAPICategoryPluginConfigurationEndpointConfigTests: XCTestCase { } func testGetConfigEndpointTypeForGraphQL() throws { - let endpointConfig = [graphQLAPI: try getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), - restAPI: try getEndpointConfig(apiName: restAPI, endpointType: .rest)] + let endpointConfig = try [ + graphQLAPI: getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), + restAPI: getEndpointConfig(apiName: restAPI, endpointType: .rest) + ] let endpoint = try endpointConfig.getConfig(endpointType: .graphQL) @@ -54,8 +56,10 @@ class AWSAPICategoryPluginConfigurationEndpointConfigTests: XCTestCase { } func testGetConfigEndpointTypeFailsWhenMoreThanOneEndpointOfTheTypeExists() throws { - let endpointConfig = [graphQLAPI: try getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), - graphQLAPI2: try getEndpointConfig(apiName: graphQLAPI2, endpointType: .graphQL)] + let endpointConfig = try [ + graphQLAPI: getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), + graphQLAPI2: getEndpointConfig(apiName: graphQLAPI2, endpointType: .graphQL) + ] do { _ = try endpointConfig.getConfig(endpointType: .graphQL) @@ -70,7 +74,7 @@ class AWSAPICategoryPluginConfigurationEndpointConfigTests: XCTestCase { } func testGetConfigEndpointTypeFailsWhenMissingEndpointForType() throws { - let endpointConfig = [restAPI: try getEndpointConfig(apiName: restAPI, endpointType: .rest)] + let endpointConfig = try [restAPI: getEndpointConfig(apiName: restAPI, endpointType: .rest)] do { _ = try endpointConfig.getConfig(endpointType: .graphQL) @@ -85,7 +89,7 @@ class AWSAPICategoryPluginConfigurationEndpointConfigTests: XCTestCase { } func testGetConfigEndpointTypeForREST() throws { - let endpointConfig = [restAPI: try getEndpointConfig(apiName: restAPI, endpointType: .rest)] + let endpointConfig = try [restAPI: getEndpointConfig(apiName: restAPI, endpointType: .rest)] let endpoint = try endpointConfig.getConfig(endpointType: .rest) @@ -94,8 +98,10 @@ class AWSAPICategoryPluginConfigurationEndpointConfigTests: XCTestCase { } func testGetConfigForOneGraphQLAndOneRESTEndpoint() throws { - let endpointConfig = [graphQLAPI: try getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), - restAPI: try getEndpointConfig(apiName: restAPI, endpointType: .rest)] + let endpointConfig = try [ + graphQLAPI: getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), + restAPI: getEndpointConfig(apiName: restAPI, endpointType: .rest) + ] let endpoint = try endpointConfig.getConfig() @@ -104,9 +110,11 @@ class AWSAPICategoryPluginConfigurationEndpointConfigTests: XCTestCase { } func testGetConfigForMoreThanOneGraphQLAndOneRESTEndpoint() throws { - let endpointConfig = [graphQLAPI: try getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), - graphQLAPI2: try getEndpointConfig(apiName: graphQLAPI2, endpointType: .graphQL), - restAPI: try getEndpointConfig(apiName: restAPI, endpointType: .rest)] + let endpointConfig = try [ + graphQLAPI: getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), + graphQLAPI2: getEndpointConfig(apiName: graphQLAPI2, endpointType: .graphQL), + restAPI: getEndpointConfig(apiName: restAPI, endpointType: .rest) + ] let endpoint = try endpointConfig.getConfig() @@ -115,9 +123,11 @@ class AWSAPICategoryPluginConfigurationEndpointConfigTests: XCTestCase { } func testGetConfigForOneGraphQLAndMoreThanOneRESTEndpoint() throws { - let endpointConfig = [graphQLAPI: try getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), - restAPI: try getEndpointConfig(apiName: restAPI, endpointType: .rest), - restAPI2: try getEndpointConfig(apiName: restAPI2, endpointType: .rest)] + let endpointConfig = try [ + graphQLAPI: getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), + restAPI: getEndpointConfig(apiName: restAPI, endpointType: .rest), + restAPI2: getEndpointConfig(apiName: restAPI2, endpointType: .rest) + ] let endpoint = try endpointConfig.getConfig() @@ -126,10 +136,12 @@ class AWSAPICategoryPluginConfigurationEndpointConfigTests: XCTestCase { } func testGetConfigShouldFailForMoreThanOneGraphQLAndRESTEndpoints() throws { - let endpointConfig = [graphQLAPI: try getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), - graphQLAPI2: try getEndpointConfig(apiName: graphQLAPI2, endpointType: .graphQL), - restAPI: try getEndpointConfig(apiName: restAPI, endpointType: .rest), - restAPI2: try getEndpointConfig(apiName: restAPI2, endpointType: .rest)] + let endpointConfig = try [ + graphQLAPI: getEndpointConfig(apiName: graphQLAPI, endpointType: .graphQL), + graphQLAPI2: getEndpointConfig(apiName: graphQLAPI2, endpointType: .graphQL), + restAPI: getEndpointConfig(apiName: restAPI, endpointType: .rest), + restAPI2: getEndpointConfig(apiName: restAPI2, endpointType: .rest) + ] do { _ = try endpointConfig.getConfig() @@ -153,6 +165,7 @@ class AWSAPICategoryPluginConfigurationEndpointConfigTests: XCTestCase { region: nil, authorizationType: AWSAuthorizationType.none, endpointType: endpointType, - apiAuthProviderFactory: APIAuthProviderFactory()) + apiAuthProviderFactory: APIAuthProviderFactory() + ) } } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Configuration/AWSAPICategoryPluginConfigurationTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Configuration/AWSAPICategoryPluginConfigurationTests.swift index b71e5491a8..0cdd8f3620 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Configuration/AWSAPICategoryPluginConfigurationTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Configuration/AWSAPICategoryPluginConfigurationTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest +import AWSPluginsCore import Foundation +import InternalAmplifyCredentials +import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSAPIPlugin @testable import AWSPluginsTestCommon -import AWSPluginsCore -import InternalAmplifyCredentials class AWSAPICategoryPluginConfigurationTests: XCTestCase { let graphQLAPI = "graphQLAPI" @@ -27,12 +27,15 @@ class AWSAPICategoryPluginConfigurationTests: XCTestCase { let interceptorsConfig = AWSAPIEndpointInterceptors( endpointName: graphQLAPI, - apiAuthProviderFactory: apiAuthProviderFactory) - - config = AWSAPICategoryPluginConfiguration(endpoints: [graphQLAPI: endpointConfig!], - interceptors: [graphQLAPI: interceptorsConfig], - apiAuthProviderFactory: apiAuthProviderFactory, - authService: MockAWSAuthService()) + apiAuthProviderFactory: apiAuthProviderFactory + ) + + config = AWSAPICategoryPluginConfiguration( + endpoints: [graphQLAPI: endpointConfig!], + interceptors: [graphQLAPI: interceptorsConfig], + apiAuthProviderFactory: apiAuthProviderFactory, + authService: MockAWSAuthService() + ) } func testThrowsOnMissingConfig() async throws { @@ -86,8 +89,10 @@ class AWSAPICategoryPluginConfigurationTests: XCTestCase { config?.addInterceptor(apiKeyInterceptor, toEndpoint: graphQLAPI) config?.addInterceptor(CustomURLInterceptor(), toEndpoint: graphQLAPI) - let interceptors = try config?.interceptorsForEndpoint(withConfig: endpointConfig!, - authType: .amazonCognitoUserPools) + let interceptors = try config?.interceptorsForEndpoint( + withConfig: endpointConfig!, + authType: .amazonCognitoUserPools + ) XCTAssertEqual(interceptors!.preludeInterceptors.count, 1) XCTAssertNotNil(interceptors!.preludeInterceptors[0] as? AuthTokenURLRequestInterceptor) @@ -119,7 +124,8 @@ class AWSAPICategoryPluginConfigurationTests: XCTestCase { authorizationType: AWSAuthorizationType.apiKey, endpointType: endpointType, apiKey: apiKey, - apiAuthProviderFactory: APIAuthProviderFactory()) + apiAuthProviderFactory: APIAuthProviderFactory() + ) } struct CustomURLInterceptor: URLRequestInterceptor { @@ -129,7 +135,7 @@ class AWSAPICategoryPluginConfigurationTests: XCTestCase { } struct MockTokenProvider: AuthTokenProvider { - + func getUserPoolAccessToken() async throws -> String { "token" } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Configuration/AWSAPIEndpointInterceptorsTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Configuration/AWSAPIEndpointInterceptorsTests.swift index 03520086ef..19a2a76cc0 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Configuration/AWSAPIEndpointInterceptorsTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Configuration/AWSAPIEndpointInterceptorsTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify import AWSPluginsCore import InternalAmplifyCredentials +import XCTest @testable import AmplifyTestCommon @testable import AWSAPIPlugin @testable import AWSPluginsTestCommon @@ -19,9 +19,11 @@ class AWSAPIEndpointInterceptorsTests: XCTestCase { var config: AWSAuthorizationConfiguration? override func setUpWithError() throws { - config = try AWSAuthorizationConfiguration.makeConfiguration(authType: .apiKey, - region: "us-west-2", - apiKey: apiKey) + config = try AWSAuthorizationConfiguration.makeConfiguration( + authType: .apiKey, + region: "us-west-2", + apiKey: apiKey + ) } /// Given: an AWSAPIEndpointInterceptors @@ -52,26 +54,38 @@ class AWSAPIEndpointInterceptorsTests: XCTestCase { } func testaddMultipleAuthInterceptors() throws { - let apiKeyConfig = try AWSAuthorizationConfiguration.makeConfiguration(authType: .apiKey, - region: "us-west-2", - apiKey: apiKey) - - let awsIAMConfig = try AWSAuthorizationConfiguration.makeConfiguration(authType: .awsIAM, - region: "us-west-2", - apiKey: apiKey) - - let userPoolConfig = try AWSAuthorizationConfiguration.makeConfiguration(authType: .amazonCognitoUserPools, - region: "us-west-2", - apiKey: nil) + let apiKeyConfig = try AWSAuthorizationConfiguration.makeConfiguration( + authType: .apiKey, + region: "us-west-2", + apiKey: apiKey + ) + + let awsIAMConfig = try AWSAuthorizationConfiguration.makeConfiguration( + authType: .awsIAM, + region: "us-west-2", + apiKey: apiKey + ) + + let userPoolConfig = try AWSAuthorizationConfiguration.makeConfiguration( + authType: .amazonCognitoUserPools, + region: "us-west-2", + apiKey: nil + ) var interceptorConfig = createAPIInterceptorConfig() - try interceptorConfig.addAuthInterceptorsToEndpoint(endpointType: .graphQL, - authConfiguration: apiKeyConfig) - try interceptorConfig.addAuthInterceptorsToEndpoint(endpointType: .graphQL, - authConfiguration: awsIAMConfig) - - try interceptorConfig.addAuthInterceptorsToEndpoint(endpointType: .graphQL, - authConfiguration: userPoolConfig) + try interceptorConfig.addAuthInterceptorsToEndpoint( + endpointType: .graphQL, + authConfiguration: apiKeyConfig + ) + try interceptorConfig.addAuthInterceptorsToEndpoint( + endpointType: .graphQL, + authConfiguration: awsIAMConfig + ) + + try interceptorConfig.addAuthInterceptorsToEndpoint( + endpointType: .graphQL, + authConfiguration: userPoolConfig + ) XCTAssertEqual(interceptorConfig.preludeInterceptors.count, 2) XCTAssertEqual(interceptorConfig.interceptors.count, 0) @@ -86,28 +100,29 @@ class AWSAPIEndpointInterceptorsTests: XCTestCase { let authService = MockAWSAuthService() authService.tokenClaims = ["exp": validToken as AnyObject] let interceptorConfig = createAPIInterceptorConfig(authService: authService) - + let result = interceptorConfig.expiryValidator("") XCTAssertFalse(result) } - + func testExpiryValidator_Expired() { let expiredToken = Date().timeIntervalSince1970 - 1 let authService = MockAWSAuthService() authService.tokenClaims = ["exp": expiredToken as AnyObject] let interceptorConfig = createAPIInterceptorConfig(authService: authService) - + let result = interceptorConfig.expiryValidator("") XCTAssertTrue(result) } - + // MARK: - Test Helpers func createAPIInterceptorConfig(authService: AWSAuthCredentialsProviderBehavior = MockAWSAuthService()) -> AWSAPIEndpointInterceptors { return AWSAPIEndpointInterceptors( endpointName: endpointName, apiAuthProviderFactory: APIAuthProviderFactory(), - authService: authService) + authService: authService + ) } struct CustomInterceptor: URLRequestInterceptor { diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListDecoderTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListDecoderTests.swift index 87b2917b08..2e27a54ce4 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListDecoderTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListDecoderTests.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import AWSPluginsCore +import XCTest @testable import AmplifyTestCommon @testable import AWSAPIPlugin -import AWSPluginsCore class AppSyncListDecoderTests: XCTestCase { @@ -77,10 +77,12 @@ class AppSyncListDecoderTests: XCTestCase { } func testShouldDecodeFromModelMetadata() throws { - let modelMetadata = AppSyncListDecoder.Metadata(appSyncAssociatedIdentifiers: ["postId"], - appSyncAssociatedFields: ["post"], - apiName: "apiName", - authMode: nil) + let modelMetadata = AppSyncListDecoder.Metadata( + appSyncAssociatedIdentifiers: ["postId"], + appSyncAssociatedFields: ["post"], + apiName: "apiName", + authMode: nil + ) let data = try encoder.encode(modelMetadata) let harness = try decoder.decode(AppSyncListDecoderHarness.self, from: data) XCTAssertNotNil(harness.listProvider) @@ -97,9 +99,13 @@ class AppSyncListDecoderTests: XCTestCase { } func testShouldDecodeFromAWSAppSyncListResponse() throws { - let listResponse = AppSyncListResponse(items: [Post4(title: "title"), - Post4(title: "title")], - nextToken: "nextToken") + let listResponse = AppSyncListResponse( + items: [ + Post4(title: "title"), + Post4(title: "title") + ], + nextToken: "nextToken" + ) let data = try encoder.encode(listResponse) let harness = try decoder.decode(AppSyncListDecoderHarness.self, from: data) XCTAssertNotNil(harness.listProvider) @@ -119,8 +125,8 @@ class AppSyncListDecoderTests: XCTestCase { func testInvalidPayload() throws { let json = "json" let data = try encoder.encode(json) - let result = try self.decoder.decode(AppSyncListDecoderHarness.self, from: data) + let result = try decoder.decode(AppSyncListDecoderHarness.self, from: data) XCTAssertNil(result.listProvider) - + } } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListPayloadTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListPayloadTests.swift index 51fac4dac3..bfc2784d3d 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListPayloadTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListPayloadTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest @testable import AWSAPIPlugin class AppSyncListPayloadTests: XCTestCase { @@ -20,10 +20,12 @@ class AppSyncListPayloadTests: XCTestCase { ], "limit": 500 ] - let payload = AppSyncListPayload(graphQLData: JSONValue.null, - apiName: "apiName", - authMode: nil, - variables: variables) + let payload = AppSyncListPayload( + graphQLData: JSONValue.null, + apiName: "apiName", + authMode: nil, + variables: variables + ) guard let limit = payload.limit else { XCTFail("Could not get limit from payload") @@ -51,20 +53,24 @@ class AppSyncListPayloadTests: XCTestCase { ], "missingLimit": 500 ] - let payload = AppSyncListPayload(graphQLData: JSONValue.null, - apiName: "apiName", - authMode: nil, - variables: variables) + let payload = AppSyncListPayload( + graphQLData: JSONValue.null, + apiName: "apiName", + authMode: nil, + variables: variables + ) XCTAssertNil(payload.graphQLFilter) XCTAssertNil(payload.limit) } func testRetrieveNilFilterAndLimit_MissingVariables() { - let payload = AppSyncListPayload(graphQLData: JSONValue.null, - apiName: "apiName", - authMode: nil, - variables: nil) + let payload = AppSyncListPayload( + graphQLData: JSONValue.null, + apiName: "apiName", + authMode: nil, + variables: nil + ) XCTAssertNil(payload.graphQLFilter) XCTAssertNil(payload.limit) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListProviderPaginationTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListProviderPaginationTests.swift index 410077d90d..3755b5f96f 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListProviderPaginationTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListProviderPaginationTests.swift @@ -6,10 +6,10 @@ // import XCTest -@testable import AWSPluginsCore @testable import Amplify @testable import AmplifyTestCommon @testable import AWSAPIPlugin +@testable import AWSPluginsCore extension AppSyncListProviderTests { @@ -34,10 +34,12 @@ extension AppSyncListProviderTests { } func testNotLoadedStateHasNextPageFalse() { - let modelMetadata = AppSyncListDecoder.Metadata(appSyncAssociatedIdentifiers: ["postId"], - appSyncAssociatedFields: ["post"], - apiName: "apiName", - authMode: nil) + let modelMetadata = AppSyncListDecoder.Metadata( + appSyncAssociatedIdentifiers: ["postId"], + appSyncAssociatedFields: ["post"], + apiName: "apiName", + authMode: nil + ) let provider = AppSyncListProvider(metadata: modelMetadata) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") @@ -50,9 +52,11 @@ extension AppSyncListProviderTests { Amplify.Logging.logLevel = .verbose mockAPIPlugin.responders[.queryRequestResponse] = QueryRequestResponder> { _ in - let nextPage = List(elements: [Comment4(content: "content"), - Comment4(content: "content"), - Comment4(content: "content")]) + let nextPage = List(elements: [ + Comment4(content: "content"), + Comment4(content: "content"), + Comment4(content: "content") + ]) return .success(nextPage) } let elements = [Comment4(content: "content")] @@ -136,10 +140,12 @@ extension AppSyncListProviderTests { } func testNotLoadedStateGetNextPageFailure() async { - let modelMetadata = AppSyncListDecoder.Metadata(appSyncAssociatedIdentifiers: ["postId"], - appSyncAssociatedFields: ["post"], - apiName: "apiName", - authMode: nil) + let modelMetadata = AppSyncListDecoder.Metadata( + appSyncAssociatedIdentifiers: ["postId"], + appSyncAssociatedFields: ["post"], + apiName: "apiName", + authMode: nil + ) let provider = AppSyncListProvider(metadata: modelMetadata) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListProviderTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListProviderTests.swift index 87bb380f50..501ff76f63 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListProviderTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListProviderTests.swift @@ -6,10 +6,10 @@ // import XCTest -@testable import AWSPluginsCore @testable import Amplify @testable import AmplifyTestCommon @testable import AWSAPIPlugin +@testable import AWSPluginsCore class AppSyncListProviderTests: XCTestCase { var mockAPIPlugin: MockAPICategoryPlugin! @@ -59,10 +59,12 @@ class AppSyncListProviderTests: XCTestCase { ], "limit": 500 ] - let appSyncPayload = AppSyncListPayload(graphQLData: json, - apiName: "apiName", - authMode: nil, - variables: variables) + let appSyncPayload = AppSyncListPayload( + graphQLData: json, + apiName: "apiName", + authMode: nil, + variables: variables + ) let provider = try AppSyncListProvider(payload: appSyncPayload) guard case .loaded(let elements, let nextToken, let filter) = provider.loadedState else { XCTFail("Should be in loaded state") @@ -85,10 +87,12 @@ class AppSyncListProviderTests: XCTestCase { ], "nextToken": "nextToken" ] - let appSyncPayload = AppSyncListPayload(graphQLData: json, - apiName: nil, - authMode: nil, - variables: nil) + let appSyncPayload = AppSyncListPayload( + graphQLData: json, + apiName: nil, + authMode: nil, + variables: nil + ) do { _ = try AppSyncListProvider(payload: appSyncPayload) } catch _ as DecodingError { @@ -99,10 +103,12 @@ class AppSyncListProviderTests: XCTestCase { } func testInitWithModelMetadataShouldBeNotLoadedState() throws { - let modelMetadata = AppSyncListDecoder.Metadata(appSyncAssociatedIdentifiers: ["postId"], - appSyncAssociatedFields: ["post"], - apiName: "apiName", - authMode: nil) + let modelMetadata = AppSyncListDecoder.Metadata( + appSyncAssociatedIdentifiers: ["postId"], + appSyncAssociatedFields: ["post"], + apiName: "apiName", + authMode: nil + ) let provider = AppSyncListProvider(metadata: modelMetadata) guard case .notLoaded(let associatedIdentifiers, let associatedFields) = provider.loadedState else { XCTFail("Should be in not loaded state") @@ -116,7 +122,7 @@ class AppSyncListProviderTests: XCTestCase { let elements = [Post4(title: "title"), Post4(title: "title")] let listProvider = AppSyncListProvider(elements: elements) let loadCompleted = expectation(description: "Load Completed") - + Task { let posts = try await listProvider.load() XCTAssertEqual(posts.count, 2) @@ -144,23 +150,25 @@ class AppSyncListProviderTests: XCTestCase { ] return .success(json) } - let modelMetadata = AppSyncListDecoder.Metadata(appSyncAssociatedIdentifiers: ["postId"], - appSyncAssociatedFields: ["post"], - apiName: "apiName", - authMode: .amazonCognitoUserPools) + let modelMetadata = AppSyncListDecoder.Metadata( + appSyncAssociatedIdentifiers: ["postId"], + appSyncAssociatedFields: ["post"], + apiName: "apiName", + authMode: .amazonCognitoUserPools + ) let provider = AppSyncListProvider(metadata: modelMetadata) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") return } let loadCompleted = expectation(description: "Load Completed") - + Task { _ = try await provider.load() loadCompleted.fulfill() } await fulfillment(of: [loadCompleted], timeout: 1) - + guard case .loaded(let elements, let nextToken, let filterOptional) = provider.loadedState else { XCTFail("Should be loaded") return @@ -175,15 +183,17 @@ class AppSyncListProviderTests: XCTestCase { } XCTAssertEqual(postId, "postId") } - + func testNotLoadedStateSynchronousLoadFailure() async { mockAPIPlugin.responders[.queryRequestResponse] = QueryRequestResponder { _ in throw APIError.unknown("", "", nil) } - let modelMetadata = AppSyncListDecoder.Metadata(appSyncAssociatedIdentifiers: ["postId"], - appSyncAssociatedFields: ["post"], - apiName: "apiName", - authMode: nil) + let modelMetadata = AppSyncListDecoder.Metadata( + appSyncAssociatedIdentifiers: ["postId"], + appSyncAssociatedFields: ["post"], + apiName: "apiName", + authMode: nil + ) let provider = AppSyncListProvider(metadata: modelMetadata) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") @@ -209,7 +219,7 @@ class AppSyncListProviderTests: XCTestCase { } await fulfillment(of: [loadCompleted], timeout: 1) } - + func testNotLoadedStateLoadWithCompletionSuccess() async { mockAPIPlugin.responders[.queryRequestResponse] = QueryRequestResponder { _ in @@ -227,10 +237,12 @@ class AppSyncListProviderTests: XCTestCase { ] return .success(json) } - let modelMetadata = AppSyncListDecoder.Metadata(appSyncAssociatedIdentifiers: ["postId"], - appSyncAssociatedFields: ["post"], - apiName: "apiName", - authMode: nil) + let modelMetadata = AppSyncListDecoder.Metadata( + appSyncAssociatedIdentifiers: ["postId"], + appSyncAssociatedFields: ["post"], + apiName: "apiName", + authMode: nil + ) let provider = AppSyncListProvider(metadata: modelMetadata) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") @@ -241,9 +253,9 @@ class AppSyncListProviderTests: XCTestCase { _ = try await provider.load() loadComplete.fulfill() } - + await fulfillment(of: [loadComplete], timeout: 1) - + guard case .loaded(let elements, let nextToken, let filterOptional) = provider.loadedState else { XCTFail("Should be loaded") return @@ -263,10 +275,12 @@ class AppSyncListProviderTests: XCTestCase { mockAPIPlugin.responders[.queryRequestResponse] = QueryRequestResponder { _ in throw APIError.unknown("", "", nil) } - let modelMetadata = AppSyncListDecoder.Metadata(appSyncAssociatedIdentifiers: ["postId"], - appSyncAssociatedFields: ["post"], - apiName: "apiName", - authMode: nil) + let modelMetadata = AppSyncListDecoder.Metadata( + appSyncAssociatedIdentifiers: ["postId"], + appSyncAssociatedFields: ["post"], + apiName: "apiName", + authMode: nil + ) let provider = AppSyncListProvider(metadata: modelMetadata) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") @@ -297,10 +311,12 @@ class AppSyncListProviderTests: XCTestCase { mockAPIPlugin.responders[.queryRequestResponse] = QueryRequestResponder { _ in return .failure(GraphQLResponseError.error([GraphQLError]())) } - let modelMetadata = AppSyncListDecoder.Metadata(appSyncAssociatedIdentifiers: ["postId"], - appSyncAssociatedFields: ["post"], - apiName: "apiName", - authMode: nil) + let modelMetadata = AppSyncListDecoder.Metadata( + appSyncAssociatedIdentifiers: ["postId"], + appSyncAssociatedFields: ["post"], + apiName: "apiName", + authMode: nil + ) let provider = AppSyncListProvider(metadata: modelMetadata) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") @@ -308,7 +324,7 @@ class AppSyncListProviderTests: XCTestCase { } let loadComplete = expectation(description: "Load completed") Task { - + do { _ = try await provider.load() XCTFail("Should have failed") @@ -320,7 +336,7 @@ class AppSyncListProviderTests: XCTestCase { } loadComplete.fulfill() } - + } await fulfillment(of: [loadComplete], timeout: 1) guard case .notLoaded = provider.loadedState else { @@ -328,7 +344,7 @@ class AppSyncListProviderTests: XCTestCase { return } } - + func testNotLoadedStateLoadWithCompletionFailure_AWSAppSyncListResponseFailure() async { mockAPIPlugin.responders[.queryRequestResponse] = QueryRequestResponder { _ in @@ -346,10 +362,12 @@ class AppSyncListProviderTests: XCTestCase { ] return .success(json) } - let modelMetadata = AppSyncListDecoder.Metadata(appSyncAssociatedIdentifiers: ["postId"], - appSyncAssociatedFields: ["post"], - apiName: "apiName", - authMode: nil) + let modelMetadata = AppSyncListDecoder.Metadata( + appSyncAssociatedIdentifiers: ["postId"], + appSyncAssociatedFields: ["post"], + apiName: "apiName", + authMode: nil + ) let provider = AppSyncListProvider(metadata: modelMetadata) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") @@ -366,7 +384,7 @@ class AppSyncListProviderTests: XCTestCase { return } loadComplete.fulfill() - + } } await fulfillment(of: [loadComplete], timeout: 2) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListResponseTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListResponseTests.swift index 37910a8fc9..857a91c154 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListResponseTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncListResponseTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AmplifyTestCommon +import XCTest @testable import Amplify @testable import AWSAPIPlugin @@ -36,10 +36,12 @@ class AppSyncListResponseTests: XCTestCase { ], "nextToken": "nextToken" ] - let listResponse = try AppSyncListResponse.initWithMetadata(type: Post4.self, - graphQLData: graphQLData, - apiName: "apiName", - authMode: nil) + let listResponse = try AppSyncListResponse.initWithMetadata( + type: Post4.self, + graphQLData: graphQLData, + apiName: "apiName", + authMode: nil + ) XCTAssertEqual(listResponse.items.count, 2) XCTAssertEqual(listResponse.nextToken, "nextToken") @@ -59,10 +61,12 @@ class AppSyncListResponseTests: XCTestCase { ] ] ] - let listResponse = try AppSyncListResponse.initWithMetadata(type: Comment4.self, - graphQLData: graphQLData, - apiName: "apiName", - authMode: nil) + let listResponse = try AppSyncListResponse.initWithMetadata( + type: Comment4.self, + graphQLData: graphQLData, + apiName: "apiName", + authMode: nil + ) XCTAssertEqual(listResponse.items.count, 2) XCTAssertNil(listResponse.nextToken) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncModelMetadataTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncModelMetadataTests.swift index f2ca4b3148..ac8ec972d9 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncModelMetadataTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/AppSyncModelMetadataTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AmplifyTestCommon +import XCTest @testable import Amplify @testable import AWSAPIPlugin @@ -54,9 +54,11 @@ class ModelMetadataTests: XCTestCase { "__typename": "Post4" ] ] - let posts = AppSyncModelMetadataUtils.addMetadata(toModelArray: jsonArray, - apiName: "apiName", - authMode: .amazonCognitoUserPools) + let posts = AppSyncModelMetadataUtils.addMetadata( + toModelArray: jsonArray, + apiName: "apiName", + authMode: .amazonCognitoUserPools + ) XCTAssertEqual(posts.count, 2) for post in posts { guard case .object(let associationData) = post["comments"], diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/ListTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/ListTests.swift index ad28849701..061952e153 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/ListTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Core/ListTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify import AmplifyTestCommon +import XCTest @testable import AWSAPIPlugin class ListTests: XCTestCase { @@ -17,9 +17,11 @@ class ListTests: XCTestCase { } func testDecodeToResponseTypeList() async throws { - let request = GraphQLRequest>(document: "", - responseType: List.self, - decodePath: "listComments") + let request = GraphQLRequest>( + document: "", + responseType: List.self, + decodePath: "listComments" + ) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ "listComments": [ diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/APIKeyURLRequestInterceptorTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/APIKeyURLRequestInterceptorTests.swift index fff55d800d..67b0fb91ae 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/APIKeyURLRequestInterceptorTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/APIKeyURLRequestInterceptorTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore +import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSAPIPlugin diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/AuthTokenURLRequestInterceptorTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/AuthTokenURLRequestInterceptorTests.swift index 74e1041f82..293a77a6f1 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/AuthTokenURLRequestInterceptorTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/AuthTokenURLRequestInterceptorTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore import InternalAmplifyCredentials +import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSAPIPlugin @@ -32,23 +32,26 @@ class AuthTokenURLRequestInterceptorTests: XCTestCase { XCTAssertNotNil(headers[URLRequestConstants.Header.xAmzDate]) XCTAssertNotNil(headers[URLRequestConstants.Header.userAgent]) } - + func testAuthTokenInterceptor_ThrowsInvalid() async throws { let mockTokenProvider = MockTokenProvider() - let interceptor = AuthTokenURLRequestInterceptor(authTokenProvider: mockTokenProvider, - isTokenExpired: { _ in return true }) + let interceptor = AuthTokenURLRequestInterceptor( + authTokenProvider: mockTokenProvider, + isTokenExpired: { _ in return true } + ) let request = RESTOperationRequestUtils.constructURLRequest( with: URL(string: "http://anapiendpoint.ca")!, operationType: .get, requestPayload: nil ) - + do { _ = try await interceptor.intercept(request).allHTTPHeaderFields } catch { guard case .operationError(let description, _, let underlyingError) = error as? APIError, let authError = underlyingError as? AuthError, - case .sessionExpired = authError else { + case .sessionExpired = authError + else { XCTFail("Should be API.operationError with underlying AuthError.sessionExpired") return } @@ -60,7 +63,7 @@ class AuthTokenURLRequestInterceptorTests: XCTestCase { extension AuthTokenURLRequestInterceptorTests { class MockTokenProvider: AuthTokenProvider { let authorizationToken = "authorizationToken" - + func getUserPoolAccessToken() async throws -> String { authorizationToken } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/SubscriptionInterceptor/APIKeyAuthInterceptorTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/SubscriptionInterceptor/APIKeyAuthInterceptorTests.swift index 7c8ebff620..15f7ea8346 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/SubscriptionInterceptor/APIKeyAuthInterceptorTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/SubscriptionInterceptor/APIKeyAuthInterceptorTests.swift @@ -5,9 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // - -import XCTest import Amplify +import XCTest @testable import AWSAPIPlugin class APIKeyAuthInterceptorTests: XCTestCase { @@ -16,7 +15,7 @@ class APIKeyAuthInterceptorTests: XCTestCase { let apiKey = UUID().uuidString let interceptor = APIKeyAuthInterceptor(apiKey: apiKey) let resultUrlRequest = await interceptor.interceptConnection(request: URLRequest(url: URL(string: "https://example.com")!)) - + let header = resultUrlRequest.value(forHTTPHeaderField: "x-api-key") XCTAssertEqual(header, apiKey) } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/SubscriptionInterceptor/CognitoAuthInterceptorTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/SubscriptionInterceptor/CognitoAuthInterceptorTests.swift index d0383bff21..3ae450d91f 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/SubscriptionInterceptor/CognitoAuthInterceptorTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Interceptor/SubscriptionInterceptor/CognitoAuthInterceptorTests.swift @@ -5,9 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // - -import XCTest import Amplify +import XCTest @testable import AWSAPIPlugin @testable @_spi(WebSocket) import AWSPluginsCore @@ -17,7 +16,7 @@ class CognitoAuthInterceptorTests: XCTestCase { let authTokenProvider = MockAuthTokenProvider() let interceptor = AuthTokenInterceptor(authTokenProvider: authTokenProvider) - let decoratedURLRequest = await interceptor.interceptConnection(request: URLRequest(url:URL(string: "https://example.com")!)) + let decoratedURLRequest = await interceptor.interceptConnection(request: URLRequest(url: URL(string: "https://example.com")!)) XCTAssertEqual(authTokenProvider.authToken, decoratedURLRequest.value(forHTTPHeaderField: "Authorization")) XCTAssertEqual("example.com", decoratedURLRequest.value(forHTTPHeaderField: "host")) @@ -27,7 +26,7 @@ class CognitoAuthInterceptorTests: XCTestCase { let authTokenProvider = MockAuthTokenProviderFailed() let interceptor = AuthTokenInterceptor(authTokenProvider: authTokenProvider) - let decoratedURLRequest = await interceptor.interceptConnection(request: URLRequest(url:URL(string: "https://example.com")!)) + let decoratedURLRequest = await interceptor.interceptConnection(request: URLRequest(url: URL(string: "https://example.com")!)) XCTAssertEqual("", decoratedURLRequest.value(forHTTPHeaderField: "Authorization")) XCTAssertEqual("example.com", decoratedURLRequest.value(forHTTPHeaderField: "host")) @@ -78,14 +77,14 @@ class CognitoAuthInterceptorTests: XCTestCase { } } -fileprivate class MockAuthTokenProvider: AmplifyAuthTokenProvider { +private class MockAuthTokenProvider: AmplifyAuthTokenProvider { let authToken = UUID().uuidString func getLatestAuthToken() async throws -> String { return authToken } } -fileprivate class MockAuthTokenProviderFailed: AmplifyAuthTokenProvider { +private class MockAuthTokenProviderFailed: AmplifyAuthTokenProvider { let authToken = UUID().uuidString func getLatestAuthToken() async throws -> String { throw "Intended" diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockReachability.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockReachability.swift index 3befe8e8a1..10e31757cd 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockReachability.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockReachability.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSAPIPlugin +import Foundation class MockNetworkReachabilityProvidingFactory: NetworkReachabilityProvidingFactory { #if os(watchOS) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockSessionFactory.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockSessionFactory.swift index ad04a70279..9ab63c60ab 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockSessionFactory.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockSessionFactory.swift @@ -6,8 +6,8 @@ // @testable import Amplify -@testable import AWSAPIPlugin @testable import AmplifyTestCommon +@testable import AWSAPIPlugin struct MockSessionFactory: URLSessionBehaviorFactory { let session: MockURLSession diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockSubscription.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockSubscription.swift index 51c1feea3e..660b516661 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockSubscription.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockSubscription.swift @@ -57,12 +57,12 @@ class MockAppSyncRealTimeClient: AppSyncRealTimeClientProtocol { } return subject.eraseToAnyPublisher() } - + func unsubscribe(id: String) async throws { try await Task.sleep(seconds: 0.45) subject.send(.unsubscribed) } - + func connect() async throws { } func disconnectWhenIdel() async { } @@ -138,6 +138,6 @@ actor MockWebSocketClient: AppSyncWebSocketClientProtocol { } func setStateToConnected() { - self.state = .connected + state = .connected } } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockURLSession.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockURLSession.swift index 3e1a4e3b89..e588ba380f 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockURLSession.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockURLSession.swift @@ -6,8 +6,8 @@ // import Foundation -@testable import AWSAPIPlugin @testable import Amplify +@testable import AWSAPIPlugin class MockURLSession: URLSessionBehavior { weak var sessionBehaviorDelegate: URLSessionBehaviorDelegate? @@ -17,8 +17,10 @@ class MockURLSession: URLSessionBehavior { var onTaskForRequest: (URLRequest) -> URLSessionDataTaskBehavior var onReset: ((BasicClosure?) -> Void)? - init(onTaskForRequest: @escaping (URLRequest) -> URLSessionDataTaskBehavior, - onReset: ((BasicClosure?) -> Void)? = MockURLSession.defaultOnReset) { + init( + onTaskForRequest: @escaping (URLRequest) -> URLSessionDataTaskBehavior, + onReset: ((BasicClosure?) -> Void)? = MockURLSession.defaultOnReset + ) { self.onTaskForRequest = onTaskForRequest self.onReset = onReset } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockURLSessionTask.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockURLSessionTask.swift index 1c06ec3212..7cf5e46fce 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockURLSessionTask.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Mocks/MockURLSessionTask.swift @@ -6,9 +6,9 @@ // import Foundation -@testable import AWSAPIPlugin @testable import Amplify @testable import AmplifyTestCommon +@testable import AWSAPIPlugin class MockURLSessionTask: URLSessionDataTaskBehavior { static var counter = AtomicValue(initialValue: 0) @@ -26,9 +26,11 @@ class MockURLSessionTask: URLSessionDataTaskBehavior { var onPause: BasicClosure? var onResume: BasicClosure? - init(onCancel: BasicClosure? = nil, - onPause: BasicClosure? = nil, - onResume: BasicClosure? = nil) { + init( + onCancel: BasicClosure? = nil, + onPause: BasicClosure? = nil, + onResume: BasicClosure? = nil + ) { self.onCancel = onCancel self.onPause = onPause self.onResume = onResume diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLOperationTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLOperationTests.swift index 9400006ebd..400b47b58e 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLOperationTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLOperationTests.swift @@ -5,21 +5,23 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSPluginsCore import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSAPIPlugin @testable import AWSPluginsTestCommon -import AWSPluginsCore class AWSGraphQLOperationTests: AWSAPICategoryPluginTestBase { /// Tests that upon completion, the operation is removed from the task mapper. func testOperationCleanup() async { - let request = GraphQLRequest(apiName: apiName, - document: testDocument, - variables: nil, - responseType: JSONValue.self) + let request = GraphQLRequest( + apiName: apiName, + document: testDocument, + variables: nil, + responseType: JSONValue.self + ) let operation = apiPlugin.query(request: request, listener: nil) @@ -43,30 +45,37 @@ class AWSGraphQLOperationTests: AWSAPICategoryPluginTestBase { /// Request for `.amazonCognitoUserPool` at runtime with `request` while passing in what /// is configured as `.apiKey`. Expect that the interceptor is the token interceptor func testGetEndpointInterceptors() throws { - let request = GraphQLRequest(apiName: apiName, - document: testDocument, - variables: nil, - responseType: JSONValue.self, - authMode: AWSAuthorizationType.amazonCognitoUserPools) + let request = GraphQLRequest( + apiName: apiName, + document: testDocument, + variables: nil, + responseType: JSONValue.self, + authMode: AWSAuthorizationType.amazonCognitoUserPools + ) let task = try OperationTestBase.makeSingleValueErrorMockTask() let mockSession = MockURLSession(onTaskForRequest: { _ in task }) - let pluginConfig = AWSAPICategoryPluginConfiguration( + let pluginConfig = try AWSAPICategoryPluginConfiguration( endpoints: [ - apiName: try .init( + apiName: .init( name: apiName, baseURL: URL(string: "url")!, region: "us-test-1", authorizationType: .apiKey, endpointType: .graphQL, apiKey: "apiKey", - apiAuthProviderFactory: .init())], + apiAuthProviderFactory: .init() + ) + ], apiAuthProviderFactory: .init(), - authService: MockAWSAuthService()) - let operation = AWSGraphQLOperation(request: request.toOperationRequest(operationType: .query), - session: mockSession, - mapper: OperationTaskMapper(), - pluginConfig: pluginConfig, - resultListener: { _ in }) + authService: MockAWSAuthService() + ) + let operation = AWSGraphQLOperation( + request: request.toOperationRequest(operationType: .query), + session: mockSession, + mapper: OperationTaskMapper(), + pluginConfig: pluginConfig, + resultListener: { _ in } + ) // Act let results = operation.getEndpointInterceptors() @@ -74,7 +83,8 @@ class AWSGraphQLOperationTests: AWSAPICategoryPluginTestBase { // Assert guard case let .success(interceptors) = results, let interceptor = interceptors?.preludeInterceptors.first, - (interceptor as? AuthTokenURLRequestInterceptor) != nil else { + (interceptor as? AuthTokenURLRequestInterceptor) != nil + else { XCTFail("Should be token interceptor for Cognito User Pool") return } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionOperationCancelTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionOperationCancelTests.swift index 95fc5b8e63..9911aa02e6 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionOperationCancelTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionOperationCancelTests.swift @@ -8,8 +8,8 @@ import XCTest @testable import Amplify -@testable import AWSAPIPlugin @testable import AmplifyTestCommon +@testable import AWSAPIPlugin @testable @_spi(WebSocket) import AWSPluginsCore @testable import AWSPluginsTestCommon @@ -36,13 +36,14 @@ class AWSGraphQLSubscriptionOperationCancelTests: XCTestCase { self.authService = authService do { - let endpointConfig = [apiName: try AWSAPICategoryPluginConfiguration.EndpointConfig( + let endpointConfig = try [apiName: AWSAPICategoryPluginConfiguration.EndpointConfig( name: apiName, baseURL: baseURL, region: region, authorizationType: AWSAuthorizationType.none, endpointType: .graphQL, - apiAuthProviderFactory: APIAuthProviderFactory())] + apiAuthProviderFactory: APIAuthProviderFactory() + )] let pluginConfig = AWSAPICategoryPluginConfiguration(endpoints: endpointConfig) self.pluginConfig = pluginConfig @@ -72,10 +73,12 @@ class AWSGraphQLSubscriptionOperationCancelTests: XCTestCase { }) await setUp(mockAppSyncRealTimeClientFactory: mockSubscriptionConnectionFactory) - let request = GraphQLRequest(apiName: apiName, - document: testDocument, - variables: nil, - responseType: JSONValue.self) + let request = GraphQLRequest( + apiName: apiName, + document: testDocument, + variables: nil, + responseType: JSONValue.self + ) let receivedValueConnecting = expectation(description: "Received value for connecting") @@ -135,7 +138,7 @@ class AWSGraphQLSubscriptionOperationCancelTests: XCTestCase { receivedCompletion.fulfill() } }) - + operation.cancel() XCTAssert(operation.isCancelled) @@ -144,7 +147,7 @@ class AWSGraphQLSubscriptionOperationCancelTests: XCTestCase { timeout: 1 ) } - + func testFailureOnConnection() async { let mockSubscriptionConnectionFactory = MockSubscriptionConnectionFactory(onGetOrCreateConnection: { _, _, _, _, _ in throw APIError.invalidConfiguration("something went wrong", "", nil) @@ -152,10 +155,12 @@ class AWSGraphQLSubscriptionOperationCancelTests: XCTestCase { await setUp(mockAppSyncRealTimeClientFactory: mockSubscriptionConnectionFactory) - let request = GraphQLRequest(apiName: apiName, - document: testDocument, - variables: nil, - responseType: JSONValue.self) + let request = GraphQLRequest( + apiName: apiName, + document: testDocument, + variables: nil, + responseType: JSONValue.self + ) let receivedCompletion = expectation(description: "Received completion") receivedCompletion.isInverted = true @@ -199,12 +204,14 @@ class AWSGraphQLSubscriptionOperationCancelTests: XCTestCase { await setUp(mockAppSyncRealTimeClientFactory: mockSubscriptionConnectionFactory) - let request = GraphQLRequest(apiName: apiName, - document: testDocument, - variables: nil, - responseType: JSONValue.self) - - + let request = GraphQLRequest( + apiName: apiName, + document: testDocument, + variables: nil, + responseType: JSONValue.self + ) + + let receivedValue = expectation(description: "Received value for connecting") receivedValue.assertForOverFulfill = false @@ -225,7 +232,7 @@ class AWSGraphQLSubscriptionOperationCancelTests: XCTestCase { let receivedFailure = expectation(description: "Received failure") receivedFailure.isInverted = true let receivedCompletion = expectation(description: "Received completion") - + _ = operation.subscribe(resultListener: { result in switch result { case .failure: @@ -234,7 +241,7 @@ class AWSGraphQLSubscriptionOperationCancelTests: XCTestCase { receivedCompletion.fulfill() } }) - + operation.cancel() XCTAssert(operation.isCancelled) await fulfillment( diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionTaskRunnerCancelTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionTaskRunnerCancelTests.swift index a06001515f..ce2d2b0981 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionTaskRunnerCancelTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionTaskRunnerCancelTests.swift @@ -8,8 +8,8 @@ import XCTest @testable import Amplify -@testable import AWSAPIPlugin @testable import AmplifyTestCommon +@testable import AWSAPIPlugin @testable import AWSPluginsCore @testable import AWSPluginsTestCommon @@ -36,13 +36,14 @@ class AWSGraphQLSubscriptionTaskRunnerCancelTests: XCTestCase { self.authService = authService do { - let endpointConfig = [apiName: try AWSAPICategoryPluginConfiguration.EndpointConfig( + let endpointConfig = try [apiName: AWSAPICategoryPluginConfiguration.EndpointConfig( name: apiName, baseURL: baseURL, region: region, authorizationType: AWSAuthorizationType.none, endpointType: .graphQL, - apiAuthProviderFactory: APIAuthProviderFactory())] + apiAuthProviderFactory: APIAuthProviderFactory() + )] let pluginConfig = AWSAPICategoryPluginConfiguration(endpoints: endpointConfig) self.pluginConfig = pluginConfig @@ -65,7 +66,7 @@ class AWSGraphQLSubscriptionTaskRunnerCancelTests: XCTestCase { XCTFail("Error setting up Amplify: \(error)") } } - + func testCancelSendsCompletion() async throws { let mockSubscriptionConnectionFactory = MockSubscriptionConnectionFactory(onGetOrCreateConnection: { _, _, _, _, _ in return MockAppSyncRealTimeClient() @@ -73,10 +74,12 @@ class AWSGraphQLSubscriptionTaskRunnerCancelTests: XCTestCase { await setUp(appSyncRealTimeClientFactory: mockSubscriptionConnectionFactory) - let request = GraphQLRequest(apiName: apiName, - document: testDocument, - variables: nil, - responseType: JSONValue.self) + let request = GraphQLRequest( + apiName: apiName, + document: testDocument, + variables: nil, + responseType: JSONValue.self + ) let receivedValueConnecting = expectation(description: "Received value for connecting") let receivedValueDisconnected = expectation(description: "Received value for disconnected") @@ -111,7 +114,7 @@ class AWSGraphQLSubscriptionTaskRunnerCancelTests: XCTestCase { try await MockAppSyncRealTimeClient.waitForUnsubscirbed() await fulfillment(of: [receivedValueDisconnected, receivedCompletion, receivedFailure], timeout: 1) } - + func testFailureOnConnection() async { let mockAppSyncRealTimeClientFactory = MockSubscriptionConnectionFactory(onGetOrCreateConnection: { _, _, _, _, _ in throw APIError.invalidConfiguration("something went wrong", "", nil) @@ -119,10 +122,12 @@ class AWSGraphQLSubscriptionTaskRunnerCancelTests: XCTestCase { await setUp(appSyncRealTimeClientFactory: mockAppSyncRealTimeClientFactory) - let request = GraphQLRequest(apiName: apiName, - document: testDocument, - variables: nil, - responseType: JSONValue.self) + let request = GraphQLRequest( + apiName: apiName, + document: testDocument, + variables: nil, + responseType: JSONValue.self + ) let receivedCompletion = expectation(description: "Received completion") receivedCompletion.isInverted = true @@ -141,7 +146,7 @@ class AWSGraphQLSubscriptionTaskRunnerCancelTests: XCTestCase { receivedFailure.fulfill() } } - + await fulfillment(of: [receivedValue, receivedFailure, receivedCompletion], timeout: 0.3) } @@ -154,11 +159,13 @@ class AWSGraphQLSubscriptionTaskRunnerCancelTests: XCTestCase { await setUp(appSyncRealTimeClientFactory: mockSubscriptionConnectionFactory) - let request = GraphQLRequest(apiName: apiName, - document: testDocument, - variables: nil, - responseType: JSONValue.self) - + let request = GraphQLRequest( + apiName: apiName, + document: testDocument, + variables: nil, + responseType: JSONValue.self + ) + let receivedValue = expectation(description: "Received value for connecting") receivedValue.expectedFulfillmentCount = 1 receivedValue.assertForOverFulfill = false @@ -167,7 +174,7 @@ class AWSGraphQLSubscriptionTaskRunnerCancelTests: XCTestCase { receivedFailure.isInverted = true let receivedCompletion = expectation(description: "Received completion") - + let subscriptionEvents = apiPlugin.subscribe(request: request) Task { do { diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSHTTPURLResponseTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSHTTPURLResponseTests.swift index 9cc06f34f6..8b55d2da64 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSHTTPURLResponseTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSHTTPURLResponseTests.swift @@ -12,11 +12,15 @@ class AWSHTTPURLResponseTests: XCTestCase { func testAWSHTTPURLResponse() throws { let body = Data("responseBody".utf8) - let httpResponse = HTTPURLResponse(url: URL(string: "dummyString")!, - statusCode: 200, - httpVersion: "1.1", - headerFields: ["key1": "value1", - "key2": "value2"])! + let httpResponse = HTTPURLResponse( + url: URL(string: "dummyString")!, + statusCode: 200, + httpVersion: "1.1", + headerFields: [ + "key1": "value1", + "key2": "value2" + ] + )! if let response = AWSHTTPURLResponse(response: httpResponse, body: body) { XCTAssertNotNil(response.body) XCTAssertNotNil(response.url) @@ -36,16 +40,20 @@ class AWSHTTPURLResponseTests: XCTestCase { func testAWSHTTPURLResponseNSCoding() { let body = Data("responseBody".utf8) - let httpResponse = HTTPURLResponse(url: URL(string: "dummyString")!, - statusCode: 200, - httpVersion: "1.1", - headerFields: ["key1": "value1", - "key2": "value2"])! + let httpResponse = HTTPURLResponse( + url: URL(string: "dummyString")!, + statusCode: 200, + httpVersion: "1.1", + headerFields: [ + "key1": "value1", + "key2": "value2" + ] + )! guard let response = AWSHTTPURLResponse(response: httpResponse, body: body) else { XCTFail("Failed to initialize `AWSHTTPURLResponse`") return } - let data : Data + let data: Data do { data = try NSKeyedArchiver.archivedData(withRootObject: response, requiringSecureCoding: false) XCTAssertNotNil(data) @@ -53,7 +61,7 @@ class AWSHTTPURLResponseTests: XCTestCase { XCTFail("Failed to archive data : \(error)") return } - + do { guard let unarchivedResponse = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? AWSHTTPURLResponse else { XCTFail("Failure while unarchiving") diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSRESTOperationTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSRESTOperationTests.swift index e6917c412c..9dca78a71e 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSRESTOperationTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSRESTOperationTests.swift @@ -122,7 +122,7 @@ class AWSRESTOperationTests: OperationTestBase { } -fileprivate struct TestURLRequestInterceptor: URLRequestInterceptor { +private struct TestURLRequestInterceptor: URLRequestInterceptor { let validate: (URLRequest) -> Bool func intercept(_ request: URLRequest) async throws -> URLRequest { diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLMutateCombineTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLMutateCombineTests.swift index 51a53fd429..82553bdfe6 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLMutateCombineTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLMutateCombineTests.swift @@ -8,8 +8,8 @@ import XCTest @testable import Amplify -@testable import AWSAPIPlugin @testable import AmplifyTestCommon +@testable import AWSAPIPlugin class GraphQLMutateCombineTests: OperationTestBase { let testDocument = "mutate { updateTodo { id name description }}" @@ -98,7 +98,7 @@ class GraphQLMutateCombineTests: OperationTestBase { let receivedFinish = expectation(description: "Received finished") receivedFinish.isInverted = true let receivedFailure = expectation(description: "Received failed") - + let sink = Amplify.Publisher.create { try await self.apiPlugin.mutate(request: request) }.sink(receiveCompletion: { completion in diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLQueryCombineTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLQueryCombineTests.swift index b25059ec02..01f9a44327 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLQueryCombineTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLQueryCombineTests.swift @@ -8,8 +8,8 @@ import XCTest @testable import Amplify -@testable import AWSAPIPlugin @testable import AmplifyTestCommon +@testable import AWSAPIPlugin class GraphQLQueryCombineTests: OperationTestBase { let testDocument = "query { getTodo { id name description }}" @@ -46,13 +46,16 @@ class GraphQLQueryCombineTests: OperationTestBase { receivedResponseError.fulfill() } }) - - await fulfillment(of: [receivedValue, - receivedFinish, - receivedFailure, - receivedResponseError - ], - timeout: 0.05) + + await fulfillment( + of: [ + receivedValue, + receivedFinish, + receivedFailure, + receivedResponseError + ], + timeout: 0.05 + ) sink.cancel() } @@ -86,13 +89,16 @@ class GraphQLQueryCombineTests: OperationTestBase { receivedResponseError.fulfill() } }) - - await fulfillment(of: [receivedValue, - receivedFinish, - receivedFailure, - receivedResponseError - ], - timeout: 0.05) + + await fulfillment( + of: [ + receivedValue, + receivedFinish, + receivedFailure, + receivedResponseError + ], + timeout: 0.05 + ) sink.cancel() } @@ -109,7 +115,7 @@ class GraphQLQueryCombineTests: OperationTestBase { let receivedFinish = expectation(description: "Received finished") receivedFinish.isInverted = true let receivedFailure = expectation(description: "Received failed") - + let sink = Amplify.Publisher.create { try await self.apiPlugin.query(request: request) }.sink(receiveCompletion: { completion in @@ -128,12 +134,15 @@ class GraphQLQueryCombineTests: OperationTestBase { } }) - await fulfillment(of: [receivedValue, - receivedFinish, - receivedFailure, - receivedResponseError - ], - timeout: 0.05) + await fulfillment( + of: [ + receivedValue, + receivedFinish, + receivedFailure, + receivedResponseError + ], + timeout: 0.05 + ) sink.cancel() } } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift index cbe8ad220c..304a76eb49 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift @@ -9,14 +9,14 @@ import Combine import XCTest import Amplify +@_implementationOnly import AmplifyAsyncTesting @testable import AmplifyTestCommon @testable import AWSAPIPlugin -@_implementationOnly import AmplifyAsyncTesting class GraphQLSubscribeCombineTests: OperationTestBase { var sink: AnyCancellable? - + // Setup expectations var onSubscribeInvoked: XCTestExpectation! var receivedCompletionSuccess: XCTestExpectation! @@ -54,30 +54,32 @@ class GraphQLSubscribeCombineTests: OperationTestBase { } override func tearDown() async throws { - self.sink?.cancel() - self.connectionStateSink?.cancel() - self.subscriptionDataSink?.cancel() - self.onSubscribeInvoked = nil - self.receivedCompletionFailure = nil - self.receivedCompletionSuccess = nil - self.receivedDataValueError = nil - self.receivedDataValueSuccess = nil - self.receivedStateValueConnected = nil - self.receivedStateValueConnecting = nil - self.receivedStateValueDisconnected = nil + sink?.cancel() + connectionStateSink?.cancel() + subscriptionDataSink?.cancel() + onSubscribeInvoked = nil + receivedCompletionFailure = nil + receivedCompletionSuccess = nil + receivedDataValueError = nil + receivedDataValueSuccess = nil + receivedStateValueConnected = nil + receivedStateValueConnecting = nil + receivedStateValueDisconnected = nil try await super.tearDown() } func waitForSubscriptionExpectations() async { - await fulfillment(of: [receivedCompletionSuccess, - receivedCompletionFailure, - receivedStateValueConnecting, - receivedStateValueConnected, - receivedStateValueDisconnected, - receivedDataValueSuccess, - receivedDataValueError], timeout: 0.05) + await fulfillment(of: [ + receivedCompletionSuccess, + receivedCompletionFailure, + receivedStateValueConnecting, + receivedStateValueConnected, + receivedStateValueDisconnected, + receivedDataValueSuccess, + receivedDataValueError + ], timeout: 0.05) } - + func testHappyPath() async throws { receivedCompletionFailure.isInverted = true receivedDataValueError.isInverted = true @@ -254,7 +256,7 @@ class GraphQLSubscribeCombineTests: OperationTestBase { case .data(let result): switch result { case .success(let actualValue): - if let expectedValue = expectedValue { + if let expectedValue { XCTAssertEqual(actualValue, expectedValue) } self.receivedDataValueSuccess.fulfill() diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift index d632e131c7..768ad32e4e 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift @@ -9,9 +9,9 @@ import Combine import XCTest import Amplify +@_implementationOnly import AmplifyAsyncTesting @testable import AmplifyTestCommon @testable import AWSAPIPlugin -@_implementationOnly import AmplifyAsyncTesting class GraphQLSubscribeTasksTests: OperationTestBase { @@ -82,7 +82,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase { timeout: 0.05 ) } - + func testHappyPath() async throws { receivedCompletionFailure.isInverted = true receivedDataValueError.isInverted = true @@ -134,7 +134,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase { expectedCompletionFailureError = APIError.operationError("", "", AppSyncRealTimeRequest.Error.limitExceeded) await waitForSubscriptionExpectations() } - + func testConnectionErrorWithConnectionUnauthorizedError() async throws { receivedCompletionSuccess.isInverted = true receivedStateValueConnected.isInverted = true @@ -155,7 +155,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase { ) await waitForSubscriptionExpectations() } - + func testConnectionErrorWithAppSyncConnectionError() async throws { receivedCompletionSuccess.isInverted = true receivedStateValueConnected.isInverted = true @@ -174,7 +174,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase { func testDecodingError() async throws { let testData: JSONValue = [ - "data": [ "foo": true ], + "data": ["foo": true], "errors": [] ] receivedCompletionFailure.isInverted = true @@ -193,7 +193,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase { func testMultipleSuccessValues() async throws { let testJSON: JSONValue = ["foo": true] let testData: JSONValue = [ - "data": [ "foo": true ] + "data": ["foo": true] ] receivedCompletionFailure.isInverted = true @@ -214,10 +214,10 @@ class GraphQLSubscribeTasksTests: OperationTestBase { func testMixedSuccessAndErrorValues() async throws { let successfulTestData: JSONValue = [ - "data": [ "foo": true ] + "data": ["foo": true] ] let invalidTestData: JSONValue = [ - "data": [ "foo": true ], + "data": ["foo": true], "errors": [] ] @@ -281,7 +281,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase { case .data(let result): switch result { case .success(let actualValue): - if let expectedValue = expectedValue { + if let expectedValue { XCTAssertEqual(actualValue, expectedValue) } self.receivedDataValueSuccess.fulfill() @@ -290,20 +290,20 @@ class GraphQLSubscribeTasksTests: OperationTestBase { } } } - + self.receivedCompletionSuccess.fulfill() } catch { if let apiError = error as? APIError, let expectedError = expectedCompletionFailureError { XCTAssertEqual(apiError, expectedError) } - + self.receivedCompletionFailure.fulfill() } } } } - + extension APIError: Equatable { public static func == (lhs: APIError, rhs: APIError) -> Bool { switch (lhs, rhs) { diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift index b052ca2384..3f7d32eace 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift @@ -85,7 +85,7 @@ class GraphQLSubscribeTests: OperationTestBase { func testHappyPath() async throws { let testJSON: JSONValue = ["foo": true] let testData: JSONValue = [ - "data": [ "foo": true ] + "data": ["foo": true] ] receivedCompletionFinish.shouldTrigger = true receivedCompletionFailure.shouldTrigger = false @@ -102,14 +102,17 @@ class GraphQLSubscribeTests: OperationTestBase { mockAppSyncRealTimeClient.triggerEvent(.data(testData)) mockAppSyncRealTimeClient.triggerEvent(.unsubscribed) - await fulfillment(of: [receivedCompletionFinish, - receivedCompletionFailure, - receivedConnected, - receivedDisconnected, - receivedSubscriptionEventData, - receivedSubscriptionEventError - ], - timeout: 0.05) + await fulfillment( + of: [ + receivedCompletionFinish, + receivedCompletionFailure, + receivedConnected, + receivedDisconnected, + receivedSubscriptionEventData, + receivedSubscriptionEventError + ], + timeout: 0.05 + ) } /// Lifecycle test @@ -138,14 +141,17 @@ class GraphQLSubscribeTests: OperationTestBase { try await MockAppSyncRealTimeClient.waitForSubscirbed() mockAppSyncRealTimeClient.triggerEvent(.unsubscribed) - await fulfillment(of: [receivedCompletionFinish, - receivedCompletionFailure, - receivedConnected, - receivedDisconnected, - receivedSubscriptionEventData, - receivedSubscriptionEventError - ], - timeout: 0.05) + await fulfillment( + of: [ + receivedCompletionFinish, + receivedCompletionFailure, + receivedConnected, + receivedDisconnected, + receivedSubscriptionEventData, + receivedSubscriptionEventError + ], + timeout: 0.05 + ) } /// Lifecycle test @@ -172,14 +178,17 @@ class GraphQLSubscribeTests: OperationTestBase { try await MockAppSyncRealTimeClient.waitForSubscirbing() mockAppSyncRealTimeClient.triggerEvent(.error(["Error"])) - await fulfillment(of: [receivedCompletionFinish, - receivedCompletionFailure, - receivedConnected, - receivedDisconnected, - receivedSubscriptionEventData, - receivedSubscriptionEventError - ], - timeout: 0.05) + await fulfillment( + of: [ + receivedCompletionFinish, + receivedCompletionFailure, + receivedConnected, + receivedDisconnected, + receivedSubscriptionEventData, + receivedSubscriptionEventError + ], + timeout: 0.05 + ) } /// Lifecycle test @@ -196,8 +205,8 @@ class GraphQLSubscribeTests: OperationTestBase { /// - The completion handler is invoked with a normal termination func testDecodingError() async throws { let testData: JSONValue = [ - "data": [ "foo": true ], - "errors": [ ] + "data": ["foo": true], + "errors": [] ] receivedCompletionFinish.shouldTrigger = true receivedCompletionFailure.shouldTrigger = false @@ -214,14 +223,17 @@ class GraphQLSubscribeTests: OperationTestBase { mockAppSyncRealTimeClient.triggerEvent(.data(testData)) mockAppSyncRealTimeClient.triggerEvent(.unsubscribed) - await fulfillment(of: [receivedCompletionFinish, - receivedCompletionFailure, - receivedConnected, - receivedDisconnected, - receivedSubscriptionEventData, - receivedSubscriptionEventError - ], - timeout: 0.05) + await fulfillment( + of: [ + receivedCompletionFinish, + receivedCompletionFailure, + receivedConnected, + receivedDisconnected, + receivedSubscriptionEventData, + receivedSubscriptionEventError + ], + timeout: 0.05 + ) } func testMultipleSuccessValues() async throws { @@ -248,14 +260,17 @@ class GraphQLSubscribeTests: OperationTestBase { mockAppSyncRealTimeClient.triggerEvent(.data(testData)) mockAppSyncRealTimeClient.triggerEvent(.unsubscribed) - await fulfillment(of: [receivedCompletionFinish, - receivedCompletionFailure, - receivedConnected, - receivedDisconnected, - receivedSubscriptionEventData, - receivedSubscriptionEventError - ], - timeout: 0.05) + await fulfillment( + of: [ + receivedCompletionFinish, + receivedCompletionFailure, + receivedConnected, + receivedDisconnected, + receivedSubscriptionEventData, + receivedSubscriptionEventError + ], + timeout: 0.05 + ) } func testMixedSuccessAndErrorValues() async throws { @@ -288,14 +303,17 @@ class GraphQLSubscribeTests: OperationTestBase { mockAppSyncRealTimeClient.triggerEvent(.data(successfulTestData)) mockAppSyncRealTimeClient.triggerEvent(.unsubscribed) - await fulfillment(of: [receivedCompletionFinish, - receivedCompletionFailure, - receivedConnected, - receivedDisconnected, - receivedSubscriptionEventData, - receivedSubscriptionEventError - ], - timeout: 0.05) + await fulfillment( + of: [ + receivedCompletionFinish, + receivedCompletionFailure, + receivedConnected, + receivedDisconnected, + receivedSubscriptionEventData, + receivedSubscriptionEventError + ], + timeout: 0.05 + ) } // MARK: - Utilities @@ -344,7 +362,7 @@ class GraphQLSubscribeTests: OperationTestBase { case .data(let result): switch result { case .success(let actualValue): - if let expectedValue = expectedValue { + if let expectedValue { XCTAssertEqual(actualValue, expectedValue) } self.receivedSubscriptionEventData.fulfill() @@ -359,7 +377,8 @@ class GraphQLSubscribeTests: OperationTestBase { case .success: self.receivedCompletionFinish.fulfill() } - }) + } + ) return operation } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/OperationTestBase.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/OperationTestBase.swift index b36ea8ccf0..f80837a92e 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/OperationTestBase.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/OperationTestBase.swift @@ -6,10 +6,10 @@ // import XCTest -@testable import AWSPluginsTestCommon @testable import Amplify @testable import AmplifyTestCommon @testable import AWSAPIPlugin +@testable import AWSPluginsTestCommon class OperationTestBase: XCTestCase { @@ -86,13 +86,17 @@ class OperationTestBase: XCTestCase { return } - delegate.urlSessionBehavior(mockSession, - dataTaskBehavior: mockTask, - didReceive: data) - - delegate.urlSessionBehavior(mockSession, - dataTaskBehavior: mockTask, - didCompleteWithError: nil) + delegate.urlSessionBehavior( + mockSession, + dataTaskBehavior: mockTask, + didReceive: data + ) + + delegate.urlSessionBehavior( + mockSession, + dataTaskBehavior: mockTask, + didCompleteWithError: nil + ) }) guard let task = mockTask else { @@ -111,9 +115,11 @@ class OperationTestBase: XCTestCase { return } - delegate.urlSessionBehavior(mockSession, - dataTaskBehavior: mockTask, - didCompleteWithError: URLError(.badServerResponse)) + delegate.urlSessionBehavior( + mockSession, + dataTaskBehavior: mockTask, + didCompleteWithError: URLError(.badServerResponse) + ) }) guard let task = mockTask else { diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/RESTCombineTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/RESTCombineTests.swift index e2c91d45c2..82f25bdd12 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/RESTCombineTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/RESTCombineTests.swift @@ -8,8 +8,8 @@ import XCTest @testable import Amplify -@testable import AWSAPIPlugin @testable import AmplifyTestCommon +@testable import AWSAPIPlugin class RESTCombineTests: OperationTestBase { @@ -23,7 +23,7 @@ class RESTCombineTests: OperationTestBase { let receivedFinish = expectation(description: "Received finished") let receivedFailure = expectation(description: "Received failed") receivedFailure.isInverted = true - + let sink = Amplify.Publisher.create { try await self.apiPlugin.get(request: request) }.sink(receiveCompletion: { completion in diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Reachability/NetworkReachabilityNotifierTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Reachability/NetworkReachabilityNotifierTests.swift index 9777f3b291..14b16a79a3 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Reachability/NetworkReachabilityNotifierTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Reachability/NetworkReachabilityNotifierTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AWSAPIPlugin @@ -34,7 +34,7 @@ class NetworkReachabilityNotifierTests: XCTestCase { var values = [Bool]() let cancellable = notifier.publisher.sink(receiveCompletion: { _ in XCTFail("Not expecting any error") - }, receiveValue: { (value: ReachabilityUpdate) -> Void in + }, receiveValue: { (value: ReachabilityUpdate) in values.append(value.isOnline) if values.count == 2 { XCTAssertFalse(values[0]) @@ -55,7 +55,7 @@ class NetworkReachabilityNotifierTests: XCTestCase { var values = [Bool]() let cancellable = notifier.publisher.sink(receiveCompletion: { _ in XCTFail("Not expecting any error") - }, receiveValue: { (value: ReachabilityUpdate) -> Void in + }, receiveValue: { (value: ReachabilityUpdate) in values.append(value.isOnline) if values.count == 2 { XCTAssertFalse(values[0]) @@ -77,7 +77,7 @@ class NetworkReachabilityNotifierTests: XCTestCase { var values = [Bool]() let cancellable = notifier.publisher.sink(receiveCompletion: { _ in XCTFail("Not expecting any error") - }, receiveValue: { (value: ReachabilityUpdate) -> Void in + }, receiveValue: { (value: ReachabilityUpdate) in values.append(value.isOnline) if values.count == 2 { XCTAssertFalse(values[0]) @@ -99,7 +99,7 @@ class NetworkReachabilityNotifierTests: XCTestCase { let completeExpect = expectation(description: ".sink receives completion") let cancellable = notifier.publisher.sink(receiveCompletion: { _ in completeExpect.fulfill() - }, receiveValue: { (value: ReachabilityUpdate) -> Void in + }, receiveValue: { (value: ReachabilityUpdate) in XCTAssertFalse(value.isOnline) defaultValueExpect.fulfill() }) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Request/GraphQLOperationRequestUtilsTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Request/GraphQLOperationRequestUtilsTests.swift index bd02b693b3..d5778b4b67 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Request/GraphQLOperationRequestUtilsTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Request/GraphQLOperationRequestUtilsTests.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import XCTest + import Amplify +import XCTest @testable import AWSAPIPlugin class GraphQLOperationRequestUtilsTests: XCTestCase { @@ -14,8 +15,10 @@ class GraphQLOperationRequestUtilsTests: XCTestCase { let testDocument = "testDocument" func testGraphQLOperationRequestWithCache() throws { - let request = GraphQLOperationRequestUtils.constructRequest(with: baseURL, - requestPayload: Data()) + let request = GraphQLOperationRequestUtils.constructRequest( + with: baseURL, + requestPayload: Data() + ) XCTAssertEqual(request.allHTTPHeaderFields?["Cache-Control"], "no-store") } } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Request/GraphQLOperationRequestValidateTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Request/GraphQLOperationRequestValidateTests.swift index d56296a56a..7b93e94ce8 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Request/GraphQLOperationRequestValidateTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Request/GraphQLOperationRequestValidateTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest @testable import AWSAPIPlugin class GraphQLOperationRequestValidateTests: XCTestCase { @@ -16,11 +16,13 @@ class GraphQLOperationRequestValidateTests: XCTestCase { func testGraphQLOperationRequestValidate() throws { let requestOptions = GraphQLOperationRequest.Options(pluginOptions: nil) - let graphQLOperationRequest = GraphQLOperationRequest(apiName: testApiName, - operationType: .mutation, - document: testDocument, - responseType: String.self, - options: requestOptions) + let graphQLOperationRequest = GraphQLOperationRequest( + apiName: testApiName, + operationType: .mutation, + document: testDocument, + responseType: String.self, + options: requestOptions + ) XCTAssertNoThrow(try graphQLOperationRequest.validate()) } } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Request/RESTOperationRequestValidateTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Request/RESTOperationRequestValidateTests.swift index 557e67e8fa..e6514dcf7c 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Request/RESTOperationRequestValidateTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Request/RESTOperationRequestValidateTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest @testable import AWSAPIPlugin class RESTOperationRequestValidateTests: XCTestCase { @@ -14,9 +14,11 @@ class RESTOperationRequestValidateTests: XCTestCase { let testApiName = "testApiName" func testRESTOperationRequestValidate() { - let restOperationRequest = RESTOperationRequest(apiName: testApiName, - operationType: .get, - options: RESTOperationRequest.Options()) + let restOperationRequest = RESTOperationRequest( + apiName: testApiName, + operationType: .get, + options: RESTOperationRequest.Options() + ) XCTAssertNoThrow(try restOperationRequest.validate()) } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/SubscriptionFactory/AppSyncRealTimeClientFactoryTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/SubscriptionFactory/AppSyncRealTimeClientFactoryTests.swift index 15ca8c7858..001698eb2c 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/SubscriptionFactory/AppSyncRealTimeClientFactoryTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/SubscriptionFactory/AppSyncRealTimeClientFactoryTests.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import XCTest @testable import AWSAPIPlugin diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLErrorDecoderTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLErrorDecoderTests.swift index e5a61e779e..0cc481a97e 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLErrorDecoderTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLErrorDecoderTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest @testable import AWSAPIPlugin class GraphQLErrorDecoderTests: XCTestCase { @@ -105,8 +105,10 @@ class GraphQLErrorDecoderTests: XCTestCase { } XCTAssertEqual(data["id"], "EF48518C-92EB-4F7A-A64E-D1B9325205CF") XCTAssertEqual(data["title"], "new3") - XCTAssertEqual(data["content"], - "Original content from DataStoreEndToEndTests at 2020-03-26 21:55:47 +0000") + XCTAssertEqual( + data["content"], + "Original content from DataStoreEndToEndTests at 2020-03-26 21:55:47 +0000" + ) XCTAssertEqual(data["_version"], 2) guard case let .string(errorType) = extensions["errorType"] else { diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoder+DecodeDataTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoder+DecodeDataTests.swift index 332fcd44fd..d81a8a8561 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoder+DecodeDataTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoder+DecodeDataTests.swift @@ -5,19 +5,21 @@ // SPDX-License-Identifier: Apache-2.0 // +@_implementationOnly import AmplifyAsyncTesting +import AWSPluginsCore import XCTest @testable import Amplify -import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSAPIPlugin -@_implementationOnly import AmplifyAsyncTesting extension GraphQLResponseDecoderTests { func testDecodeToResponseTypeForString() throws { - let request = GraphQLRequest(document: "", - responseType: String.self, - decodePath: "getSimpleModel") + let request = GraphQLRequest( + document: "", + responseType: String.self, + decodePath: "getSimpleModel" + ) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ "getSimpleModel": [ @@ -31,9 +33,11 @@ extension GraphQLResponseDecoderTests { func testDecodeToResponseTypeForAnyModel() throws { ModelRegistry.register(modelType: SimpleModel.self) - let request = GraphQLRequest(document: "", - responseType: AnyModel.self, - decodePath: "getSimpleModel") + let request = GraphQLRequest( + document: "", + responseType: AnyModel.self, + decodePath: "getSimpleModel" + ) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ "getSimpleModel": [ @@ -54,9 +58,11 @@ extension GraphQLResponseDecoderTests { } func testDecodeToResponseTypeForModel() throws { - let request = GraphQLRequest(document: "", - responseType: SimpleModel.self, - decodePath: "getSimpleModel") + let request = GraphQLRequest( + document: "", + responseType: SimpleModel.self, + decodePath: "getSimpleModel" + ) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ "getSimpleModel": [ @@ -70,9 +76,11 @@ extension GraphQLResponseDecoderTests { } func testDecodeToResponseTypeForModelWithArrayAssoiation() throws { - let request = GraphQLRequest(document: "", - responseType: Post4.self, - decodePath: "getPost") + let request = GraphQLRequest( + document: "", + responseType: Post4.self, + decodePath: "getPost" + ) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ "getPost": [ @@ -90,9 +98,11 @@ extension GraphQLResponseDecoderTests { } func testDecodeToResponseTypeForList() async throws { - let request = GraphQLRequest>(document: "", - responseType: List.self, - decodePath: "listSimpleModel") + let request = GraphQLRequest>( + document: "", + responseType: List.self, + decodePath: "listSimpleModel" + ) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ "listSimpleModel": [ @@ -123,18 +133,22 @@ extension GraphQLResponseDecoderTests { func testDecodeToResponseTypeForCodable() throws { - let request = GraphQLRequest(document: "", - responseType: SimpleCodable.self, - decodePath: "getSimpleCodable") + let request = GraphQLRequest( + document: "", + responseType: SimpleCodable.self, + decodePath: "getSimpleCodable" + ) let graphQLDecoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) - let expectedObject = SimpleCodable(myBool: true, - myDouble: 1.0, - myInt: 1, - myString: "string", - myDate: .now(), - myDateTime: .now(), - myTime: .now()) + let expectedObject = SimpleCodable( + myBool: true, + myDouble: 1.0, + myInt: 1, + myString: "string", + myDate: .now(), + myDateTime: .now(), + myTime: .now() + ) let data = try encoder.encode(expectedObject) let objectJSON = try decoder.decode(JSONValue.self, from: data) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoderLazyPostComment4V2Tests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoderLazyPostComment4V2Tests.swift index fe72e229af..dc588ec8bd 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoderLazyPostComment4V2Tests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoderLazyPostComment4V2Tests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSPluginsCore import XCTest @testable import Amplify -import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSAPIPlugin @@ -16,7 +16,7 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases let decoder = JSONDecoder() let encoder = JSONEncoder() - + override func setUp() async throws { await Amplify.reset() Amplify.Logging.logLevel = .verbose @@ -28,7 +28,7 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases decoder.dateDecodingStrategy = ModelDateFormatting.decodingStrategy encoder.dateEncodingStrategy = ModelDateFormatting.encodingStrategy } - + func testSaveCommentThenQueryComment() async throws { let comment = LazyChildComment4V2(content: "content") // Create request @@ -53,13 +53,14 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases """ XCTAssertEqual(request.document, documentString) guard let variables = request.variables, - let input = variables["input"] as? [String: Any] else { + let input = variables["input"] as? [String: Any] + else { XCTFail("Missing request.variables input") return } XCTAssertEqual(input["id"] as? String, comment.id) XCTAssertEqual(input["content"] as? String, comment.content) - + // Get request let getRequest = GraphQLRequest.get(LazyChildComment4V2.self, byId: comment.id) documentString = """ @@ -82,12 +83,13 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases """ XCTAssertEqual(getRequest.document, documentString) guard let variables = getRequest.variables, - let id = variables["id"] as? String else { + let id = variables["id"] as? String + else { XCTFail("Missing request.variables id") return } XCTAssertEqual(id, comment.id) - + // Decode data let decoder = GraphQLResponseDecoder(request: getRequest.toOperationRequest(operationType: .mutation)) let graphQLData: [String: JSONValue] = [ @@ -114,10 +116,10 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases XCTFail("should be not loaded, with `nil` identifiers") } } - + func testSavePostThenQueryPost() async throws { let post = LazyParentPost4V2(title: "title") - + // Create request let request = GraphQLRequest.create(post) var documentString = """ @@ -133,13 +135,14 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases """ XCTAssertEqual(request.document, documentString) guard let variables = request.variables, - let input = variables["input"] as? [String: Any] else { + let input = variables["input"] as? [String: Any] + else { XCTFail("Missing request.variables input") return } XCTAssertEqual(input["id"] as? String, post.id) XCTAssertEqual(input["title"] as? String, post.title) - + // Get request let getRequest = GraphQLRequest.get(LazyParentPost4V2.self, byId: post.id) documentString = """ @@ -155,12 +158,13 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases """ XCTAssertEqual(getRequest.document, documentString) guard let variables = getRequest.variables, - let id = variables["id"] as? String else { + let id = variables["id"] as? String + else { XCTFail("Missing request.variables id") return } XCTAssertEqual(id, post.id) - + // Decode data let decoder = GraphQLResponseDecoder(request: getRequest.toOperationRequest(operationType: .mutation)) let graphQLData: [String: JSONValue] = [ @@ -191,7 +195,7 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases XCTFail("Should be not loaded with post data") } } - + func testSaveMultipleThenQueryComments() async throws { let request = GraphQLRequest.list(LazyChildComment4V2.self) let documentString = """ @@ -217,14 +221,15 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases """ XCTAssertEqual(request.document, documentString) guard let variables = request.variables, - let limit = variables["limit"] as? Int else { + let limit = variables["limit"] as? Int + else { XCTFail("Missing request.variables input") return } - XCTAssertEqual(limit, 1000) + XCTAssertEqual(limit, 1_000) let decoder = GraphQLResponseDecoder>( request: request.toOperationRequest(operationType: .query)) - + let date = Temporal.DateTime.now().iso8601String let graphQLData: [String: JSONValue] = [ "\(request.decodePath!)": [ @@ -264,7 +269,7 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases XCTAssertNotNil(comment2) XCTAssertTrue(queriedList.hasNextPage()) } - + func testSaveMultipleThenQueryPosts() async throws { let request = GraphQLRequest.list(LazyParentPost4V2.self) let documentString = """ @@ -283,13 +288,14 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases """ XCTAssertEqual(request.document, documentString) guard let variables = request.variables, - let limit = variables["limit"] as? Int else { + let limit = variables["limit"] as? Int + else { XCTFail("Missing request.variables input") return } - XCTAssertEqual(limit, 1000) + XCTAssertEqual(limit, 1_000) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) - + let graphQLData: [String: JSONValue] = [ "\(request.decodePath!)": [ "items": [ @@ -315,21 +321,22 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases XCTAssertNotNil(post1) XCTAssertNotNil(post2) } - + func testSaveCommentWithPostThenQueryCommentAndAccessPost() async throws { let post = LazyParentPost4V2(title: "title") let comment = LazyChildComment4V2(content: "content", post: post) - + let request = GraphQLRequest.create(comment) guard let variables = request.variables, - let input = variables["input"] as? [String: Any] else { + let input = variables["input"] as? [String: Any] + else { XCTFail("Missing request.variables input") return } XCTAssertEqual(input["id"] as? String, comment.id) XCTAssertEqual(input["content"] as? String, comment.content) XCTAssertEqual(input["postID"] as? String, post.id) - + let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) var graphQLData: [String: JSONValue] = [ "\(request.decodePath!)": [ @@ -361,7 +368,7 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases } XCTAssertEqual(loadedPost.id, post.id) } - + graphQLData = [ "\(request.decodePath!)": [ "id": "id", @@ -386,7 +393,7 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases XCTAssertEqual(commentWithLazyLoadPost.content, "content") switch commentWithLazyLoadPost._post.modelProvider.getState() { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { + guard let identifiers else { XCTFail("Missing identifiers") return } @@ -395,10 +402,10 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases XCTFail("should be in not loaded state when post data is partial") } } - + func testSaveCommentWithPostThenQueryPostAndAccessComments() async throws { let post = LazyParentPost4V2(title: "title") - + let request = GraphQLRequest.create(post) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ @@ -426,7 +433,7 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases XCTFail("Should be not loaded with post data") } } - + func testSaveMultipleCommentWithPostThenQueryCommentsAndAccessPost() async throws { let post = LazyParentPost4V2(title: "title") let request = GraphQLRequest.list(LazyChildComment4V2.self) @@ -465,7 +472,7 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases } switch comment._post.modelProvider.getState() { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { + guard let identifiers else { XCTFail("Missing identifiers") return } @@ -473,7 +480,7 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases case .loaded: XCTFail("Should be in not loaded state") } - + graphQLData = [ "\(request.decodePath!)": [ "items": [ @@ -511,7 +518,7 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases XCTAssertEqual(loadedPost.id, post.id) } } - + func testSaveMultipleCommentWithPostThenQueryPostAndAccessComments() async throws { let request = GraphQLRequest.list(LazyParentPost4V2.self) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) @@ -531,7 +538,8 @@ class GraphQLResponseDecoderLazyPostComment4V2Tests: XCTestCase, SharedTestCases let result = try decoder.decodeToResponseType(graphQLData) XCTAssertEqual(result.count, 1) guard let post = result.first, - let comments = post.comments else { + let comments = post.comments + else { XCTFail("Failed to decode to one post, with containing comments") return } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoderPostComment4V2Tests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoderPostComment4V2Tests.swift index 88ed40292d..1d4b2a816e 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoderPostComment4V2Tests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoderPostComment4V2Tests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSPluginsCore import XCTest @testable import Amplify -import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSAPIPlugin @@ -16,7 +16,7 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost let decoder = JSONDecoder() let encoder = JSONEncoder() - + override func setUp() async throws { await Amplify.reset() ModelRegistry.register(modelType: ParentPost4V2.self) @@ -27,7 +27,7 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost decoder.dateDecodingStrategy = ModelDateFormatting.decodingStrategy encoder.dateEncodingStrategy = ModelDateFormatting.encodingStrategy } - + func testSaveCommentThenQueryComment() async throws { let comment = ChildComment4V2(content: "content") // Create request @@ -52,13 +52,14 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost """ XCTAssertEqual(request.document, documentString) guard let variables = request.variables, - let input = variables["input"] as? [String: Any] else { + let input = variables["input"] as? [String: Any] + else { XCTFail("Missing request.variables input") return } XCTAssertEqual(input["id"] as? String, comment.id) XCTAssertEqual(input["content"] as? String, comment.content) - + // Get request let getRequest = GraphQLRequest.get(ChildComment4V2.self, byId: comment.id) documentString = """ @@ -81,12 +82,13 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost """ XCTAssertEqual(getRequest.document, documentString) guard let variables = getRequest.variables, - let id = variables["id"] as? String else { + let id = variables["id"] as? String + else { XCTFail("Missing request.variables id") return } XCTAssertEqual(id, comment.id) - + // Decode data let decoder = GraphQLResponseDecoder(request: getRequest.toOperationRequest(operationType: .mutation)) let graphQLData: [String: JSONValue] = [ @@ -108,10 +110,10 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost XCTAssertEqual(savedComment.content, "content") XCTAssertNil(savedComment.post) } - + func testSavePostThenQueryPost() async throws { let post = ParentPost4V2(title: "title") - + // Create request let request = GraphQLRequest.create(post) var documentString = """ @@ -127,13 +129,14 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost """ XCTAssertEqual(request.document, documentString) guard let variables = request.variables, - let input = variables["input"] as? [String: Any] else { + let input = variables["input"] as? [String: Any] + else { XCTFail("Missing request.variables input") return } XCTAssertEqual(input["id"] as? String, post.id) XCTAssertEqual(input["title"] as? String, post.title) - + // Get request let getRequest = GraphQLRequest.get(ParentPost4V2.self, byId: post.id) documentString = """ @@ -149,12 +152,13 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost """ XCTAssertEqual(getRequest.document, documentString) guard let variables = getRequest.variables, - let id = variables["id"] as? String else { + let id = variables["id"] as? String + else { XCTFail("Missing request.variables id") return } XCTAssertEqual(id, post.id) - + // Decode data let decoder = GraphQLResponseDecoder(request: getRequest.toOperationRequest(operationType: .mutation)) let graphQLData: [String: JSONValue] = [ @@ -185,7 +189,7 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost XCTFail("Should be not loaded with post data") } } - + func testSaveMultipleThenQueryComments() async throws { let request = GraphQLRequest.list(ChildComment4V2.self) let documentString = """ @@ -211,14 +215,15 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost """ XCTAssertEqual(request.document, documentString) guard let variables = request.variables, - let limit = variables["limit"] as? Int else { + let limit = variables["limit"] as? Int + else { XCTFail("Missing request.variables input") return } - XCTAssertEqual(limit, 1000) + XCTAssertEqual(limit, 1_000) let decoder = GraphQLResponseDecoder>( request: request.toOperationRequest(operationType: .query)) - + let graphQLData: [String: JSONValue] = [ "\(request.decodePath!)": [ "items": [ @@ -253,7 +258,7 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost XCTAssertNotNil(comment2) XCTAssertTrue(queriedList.hasNextPage()) } - + func testSaveMultipleThenQueryPosts() async throws { let request = GraphQLRequest.list(ParentPost4V2.self) let documentString = """ @@ -272,13 +277,14 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost """ XCTAssertEqual(request.document, documentString) guard let variables = request.variables, - let limit = variables["limit"] as? Int else { + let limit = variables["limit"] as? Int + else { XCTFail("Missing request.variables input") return } - XCTAssertEqual(limit, 1000) + XCTAssertEqual(limit, 1_000) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) - + let graphQLData: [String: JSONValue] = [ "\(request.decodePath!)": [ "items": [ @@ -304,21 +310,22 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost XCTAssertNotNil(post1) XCTAssertNotNil(post2) } - + func testSaveCommentWithPostThenQueryCommentAndAccessPost() async throws { let post = ParentPost4V2(title: "title") let comment = ChildComment4V2(content: "content", post: post) - + let request = GraphQLRequest.create(comment) guard let variables = request.variables, - let input = variables["input"] as? [String: Any] else { + let input = variables["input"] as? [String: Any] + else { XCTFail("Missing request.variables input") return } XCTAssertEqual(input["id"] as? String, comment.id) XCTAssertEqual(input["content"] as? String, comment.content) XCTAssertEqual(input["postID"] as? String, post.id) - + let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) var graphQLData: [String: JSONValue] = [ "\(request.decodePath!)": [ @@ -342,10 +349,10 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost XCTAssertEqual(commentWithEagerLoadedPost.content, "content") XCTAssertEqual(commentWithEagerLoadedPost.post?.id, post.id) } - + func testSaveCommentWithPostThenQueryPostAndAccessComments() async throws { let post = ParentPost4V2(title: "title") - + let request = GraphQLRequest.create(post) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ @@ -373,7 +380,7 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost XCTFail("Should be not loaded with post data") } } - + func testSaveMultipleCommentWithPostThenQueryCommentsAndAccessPost() async throws { let post = ParentPost4V2(title: "title") let request = GraphQLRequest.list(ChildComment4V2.self) @@ -405,7 +412,7 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost } XCTAssertEqual(comment.post?.id, post.id) } - + func testSaveMultipleCommentWithPostThenQueryPostAndAccessComments() async throws { let request = GraphQLRequest.list(ParentPost4V2.self) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) @@ -425,7 +432,8 @@ class GraphQLResponseDecoderPostComment4V2Tests: XCTestCase, SharedTestCasesPost let result = try decoder.decodeToResponseType(graphQLData) XCTAssertEqual(result.count, 1) guard let post = result.first, - let comments = post.comments else { + let comments = post.comments + else { XCTFail("Failed to decode to one post, with containing comments") return } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoderTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoderTests.swift index 6d9144880b..8b8184cdf6 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoderTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Decode/GraphQLResponseDecoderTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSPluginsCore import XCTest @testable import Amplify -import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSAPIPlugin @@ -61,9 +61,11 @@ class GraphQLResponseDecoderTests: XCTestCase { } func testDecodeToGraphQLResponseWhenDataOnly() throws { - let request = GraphQLRequest(document: "", - responseType: String.self, - decodePath: "getSimpleModel") + let request = GraphQLRequest( + document: "", + responseType: String.self, + decodePath: "getSimpleModel" + ) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ "data": [ @@ -85,9 +87,11 @@ class GraphQLResponseDecoderTests: XCTestCase { } func testDecodeToGraphQLResponseWhenErrorsOnly() throws { - let request = GraphQLRequest(document: "", - responseType: String.self, - decodePath: "getSimpleModel") + let request = GraphQLRequest( + document: "", + responseType: String.self, + decodePath: "getSimpleModel" + ) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ "errors": [ @@ -101,16 +105,19 @@ class GraphQLResponseDecoderTests: XCTestCase { let result = try decoder.decodeToGraphQLResponse() guard case let .failure(response) = result, - case .error = response else { + case .error = response + else { XCTFail("Could not get failure response") return } } func testDecodeToGraphQLResponseWhenDataAndErrors() throws { - let request = GraphQLRequest(document: "", - responseType: String.self, - decodePath: "getSimpleModel") + let request = GraphQLRequest( + document: "", + responseType: String.self, + decodePath: "getSimpleModel" + ) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ "data": [ @@ -129,16 +136,19 @@ class GraphQLResponseDecoderTests: XCTestCase { let result = try decoder.decodeToGraphQLResponse() guard case let .failure(response) = result, - case .partial = response else { + case .partial = response + else { XCTFail("Could not get failure response") return } } func testDecodeToGraphQLResponseWhenInvalidResponse() throws { - let request = GraphQLRequest(document: "", - responseType: String.self, - decodePath: "getSimpleModel") + let request = GraphQLRequest( + document: "", + responseType: String.self, + decodePath: "getSimpleModel" + ) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ "invalidDataKey": [ @@ -168,9 +178,11 @@ class GraphQLResponseDecoderTests: XCTestCase { } func testDecodeToGraphQLResponseWhenPartialAndDataIsNull() throws { - let request = GraphQLRequest(document: "", - responseType: String.self, - decodePath: "getSimpleModel") + let request = GraphQLRequest( + document: "", + responseType: String.self, + decodePath: "getSimpleModel" + ) let decoder = GraphQLResponseDecoder(request: request.toOperationRequest(operationType: .query)) let graphQLData: [String: JSONValue] = [ "data": [ @@ -187,7 +199,8 @@ class GraphQLResponseDecoderTests: XCTestCase { let result = try decoder.decodeToGraphQLResponse() guard case let .failure(response) = result, - case .error = response else { + case .error = response + else { XCTFail("Could not get failure response") return } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Internal/AWSAppSyncGrpahQLResponseTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Internal/AWSAppSyncGrpahQLResponseTests.swift index 74631e44de..b12ca0ca4d 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Internal/AWSAppSyncGrpahQLResponseTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Internal/AWSAppSyncGrpahQLResponseTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest @testable import AWSAPIPlugin class AWSAppSyncGrpahQLResponseTests: XCTestCase { diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/Array+Error+TypeCastTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/Array+Error+TypeCastTests.swift index d1d6861a74..c94cc9db13 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/Array+Error+TypeCastTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/Array+Error+TypeCastTests.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import XCTest @testable @_spi(AmplifyAPI) import AWSAPIPlugin diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/GraphQLRequestToListQueryTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/GraphQLRequestToListQueryTests.swift index 783ceb0c0c..27b72d97ee 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/GraphQLRequestToListQueryTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/GraphQLRequestToListQueryTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AmplifyTestCommon import AWSPluginsCore +import XCTest @testable import Amplify @testable import AWSAPIPlugin @@ -24,12 +24,14 @@ class GraphQLRequestToListQueryTests: XCTestCase { func testFirstPageRequestRequest() { let predicate = Comment4.keys.post == "postId123" - let request = GraphQLRequest.listQuery(responseType: JSONValue.self, - modelSchema: Comment4.schema, - filter: predicate.graphQLFilter(for: Comment4.schema), - limit: 1_000, - apiName: "apiName", - authMode: .awsIAM) + let request = GraphQLRequest.listQuery( + responseType: JSONValue.self, + modelSchema: Comment4.schema, + filter: predicate.graphQLFilter(for: Comment4.schema), + limit: 1_000, + apiName: "apiName", + authMode: .awsIAM + ) XCTAssertNotNil(request) let expectedDocument = """ query ListComment4s($filter: ModelComment4FilterInput, $limit: Int) { @@ -59,8 +61,10 @@ class GraphQLRequestToListQueryTests: XCTestCase { XCTAssertNotNil(variables["limit"]) XCTAssertEqual(variables["limit"] as? Int, 1_000) guard let filter = variables["filter"] as? GraphQLFilter, - let filterJSON = try? JSONSerialization.data(withJSONObject: filter, - options: .prettyPrinted) else { + let filterJSON = try? JSONSerialization.data( + withJSONObject: filter, + options: .prettyPrinted + ) else { XCTFail("variables should contain a valid filter JSON") return } @@ -75,11 +79,13 @@ class GraphQLRequestToListQueryTests: XCTestCase { } func testMextPageRequest() { - let request = GraphQLRequest.listQuery(responseType: List.self, - modelSchema: Comment4.schema, - nextToken: "nextToken", - apiName: "apiName", - authMode: .amazonCognitoUserPools) + let request = GraphQLRequest.listQuery( + responseType: List.self, + modelSchema: Comment4.schema, + nextToken: "nextToken", + apiName: "apiName", + authMode: .amazonCognitoUserPools + ) XCTAssertNotNil(request) let expectedDocument = """ query ListComment4s($limit: Int, $nextToken: String) { @@ -118,13 +124,15 @@ class GraphQLRequestToListQueryTests: XCTestCase { "eq": "postId123" ] ] - let request = GraphQLRequest.listQuery(responseType: List.self, - modelSchema: Comment4.schema, - filter: previousFilter, - limit: 1_000, - nextToken: "nextToken", - apiName: "apiName", - authMode: .function) + let request = GraphQLRequest.listQuery( + responseType: List.self, + modelSchema: Comment4.schema, + filter: previousFilter, + limit: 1_000, + nextToken: "nextToken", + apiName: "apiName", + authMode: .function + ) XCTAssertNotNil(request) let expectedDocument = """ query ListComment4s($filter: ModelComment4FilterInput, $limit: Int, $nextToken: String) { @@ -157,8 +165,10 @@ class GraphQLRequestToListQueryTests: XCTestCase { XCTAssertEqual(variables["nextToken"] as? String, "nextToken") guard let filter = variables["filter"] as? GraphQLFilter, JSONSerialization.isValidJSONObject(filter), - let filterJSON = try? JSONSerialization.data(withJSONObject: filter, - options: .prettyPrinted) else { + let filterJSON = try? JSONSerialization.data( + withJSONObject: filter, + options: .prettyPrinted + ) else { XCTFail("variables should contain a valid filter JSON") return } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/RESTRequestUtilsTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/RESTRequestUtilsTests.swift index c2c751ca06..42b7f28f07 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/RESTRequestUtilsTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/RESTRequestUtilsTests.swift @@ -23,7 +23,7 @@ class RESTRequestUtilsTests: XCTestCase { } } - guard let expected = expected else { + guard let expected else { return XCTAssertTrue( queryParams.isEmpty, "Test \(testCase): Unexpected query items found \(queryParams)" @@ -81,7 +81,7 @@ class RESTRequestUtilsTests: XCTestCase { func testConstructURLRequestFailsWithInvalidQueryParams() throws { let baseURL = URL(string: "https://aws.amazon.com")! - let validUTF16Bytes: [UInt8] = [0xD8, 0x34, 0xDD, 0x1E] // Surrogate pair for '𝄞' + let validUTF16Bytes: [UInt8] = [0xd8, 0x34, 0xdd, 0x1e] // Surrogate pair for '𝄞' let paramValue = String( bytes: validUTF16Bytes, encoding: String.Encoding.utf16BigEndian diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/Result+AsyncTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/Result+AsyncTests.swift index 5ae473b899..6632f69988 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/Result+AsyncTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Support/Utils/Result+AsyncTests.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import XCTest @testable import AWSAPIPlugin @@ -18,7 +17,7 @@ class ResultAsyncTests: XCTestCase { let result = Result.success(0) let plus1Result = await result.flatMapAsync { - .success(await plus1($0)) + await .success(plus1($0)) } switch plus1Result { @@ -38,7 +37,7 @@ class ResultAsyncTests: XCTestCase { let expectedError = TestError() let result = Result<[Int], Error>.failure(expectedError) let count = await result.flatMapAsync { - .success(await arrayCount($0)) + await .success(arrayCount($0)) } switch count { @@ -51,4 +50,4 @@ class ResultAsyncTests: XCTestCase { } } -fileprivate class TestError: Error { } +private class TestError: Error { } diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+ClientBehavior.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+ClientBehavior.swift index c2e168e217..343b51094e 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+ClientBehavior.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+ClientBehavior.swift @@ -10,8 +10,8 @@ import AWSPinpoint import Foundation @_spi(InternalAWSPinpoint) import InternalAWSPinpoint -extension AWSPinpointAnalyticsPlugin { - public func identifyUser(userId: String, userProfile: AnalyticsUserProfile?) { +public extension AWSPinpointAnalyticsPlugin { + func identifyUser(userId: String, userProfile: AnalyticsUserProfile?) { if !isEnabled { log.warn("Cannot identify user. Analytics is disabled. Call Amplify.Analytics.enable() to enable") return @@ -20,12 +20,14 @@ extension AWSPinpointAnalyticsPlugin { Task { var currentEndpointProfile = await pinpoint.currentEndpointProfile() currentEndpointProfile.addUserId(userId) - if let userProfile = userProfile { + if let userProfile { currentEndpointProfile.addUserProfile(userProfile) } do { - try await pinpoint.updateEndpoint(with: currentEndpointProfile, - source: .analytics) + try await pinpoint.updateEndpoint( + with: currentEndpointProfile, + source: .analytics + ) Amplify.Hub.dispatchIdentifyUser(userId, userProfile: userProfile) } catch { Amplify.Hub.dispatchIdentifyUser(AnalyticsErrorHelper.getDefaultError(error)) @@ -33,7 +35,7 @@ extension AWSPinpointAnalyticsPlugin { } } - public func record(event: AnalyticsEvent) { + func record(event: AnalyticsEvent) { if !isEnabled { log.warn("Cannot record events. Analytics is disabled. Call Amplify.Analytics.enable() to enable") return @@ -55,12 +57,12 @@ extension AWSPinpointAnalyticsPlugin { } } - public func record(eventWithName eventName: String) { + func record(eventWithName eventName: String) { let event = BasicAnalyticsEvent(name: eventName) record(event: event) } - public func registerGlobalProperties(_ properties: [String: AnalyticsPropertyValue]) { + func registerGlobalProperties(_ properties: [String: AnalyticsPropertyValue]) { // TODO: check if there is a limit on total number of properties properties.forEach { key, _ in guard key.count >= 1, key.count <= 50 else { @@ -75,13 +77,13 @@ extension AWSPinpointAnalyticsPlugin { } } - public func unregisterGlobalProperties(_ keys: Set?) { + func unregisterGlobalProperties(_ keys: Set?) { Task { await unregisterGlobalProperties(keys) } } - public func flushEvents() { + func flushEvents() { if !isEnabled { log.warn("Cannot flushEvents. Analytics is disabled. Call Amplify.Analytics.enable() to enable") return @@ -105,18 +107,18 @@ extension AWSPinpointAnalyticsPlugin { } } - public func enable() { + func enable() { isEnabled = true } - public func disable() { + func disable() { isEnabled = false } /// Retrieve the escape hatch to perform actions directly on PinpointClient. /// /// - Returns: PinpointClientProtocol instance - public func getEscapeHatch() -> PinpointClientProtocol { + func getEscapeHatch() -> PinpointClientProtocol { pinpoint.pinpointClient } @@ -128,7 +130,7 @@ extension AWSPinpointAnalyticsPlugin { } private func unregisterGlobalProperties(_ keys: Set?) async { - guard let keys = keys else { + guard let keys else { for (key, value) in globalProperties { await pinpoint.removeGlobalProperty(value, forKey: key) } diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+Configure.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+Configure.swift index 2acad0b80b..33a9cd9850 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+Configure.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+Configure.swift @@ -11,7 +11,7 @@ import Foundation @_spi(InternalAWSPinpoint) import InternalAWSPinpoint import Network -extension AWSPinpointAnalyticsPlugin { +public extension AWSPinpointAnalyticsPlugin { /// Configures AWSPinpointAnalyticsPlugin with the specified configuration. /// /// This method will be invoked as part of the Amplify configuration flow. @@ -19,7 +19,7 @@ extension AWSPinpointAnalyticsPlugin { /// - Parameter configuration: The configuration specified for this plugin /// - Throws: /// - PluginError.pluginConfigurationError: If one of the configuration values is invalid or empty - public func configure(using configuration: Any?) throws { + func configure(using configuration: Any?) throws { let pluginConfiguration: AWSPinpointAnalyticsPluginConfiguration if let config = configuration as? AmplifyOutputsData { print(config) @@ -45,7 +45,7 @@ extension AWSPinpointAnalyticsPlugin { } /// Configure AWSPinpointAnalyticsPlugin programatically using AWSPinpointAnalyticsPluginConfiguration - public func configure(using configuration: AWSPinpointAnalyticsPluginConfiguration) throws { + func configure(using configuration: AWSPinpointAnalyticsPluginConfiguration) throws { let pinpoint = try AWSPinpointFactory.sharedPinpoint( appId: configuration.appId, region: configuration.region @@ -82,10 +82,12 @@ extension AWSPinpointAnalyticsPlugin { // MARK: Internal /// Internal configure method to set the properties of the plugin - func configure(pinpoint: AWSPinpointBehavior, - networkMonitor: NetworkMonitor, - globalProperties: AtomicDictionary = [:], - isEnabled: Bool = true) { + internal func configure( + pinpoint: AWSPinpointBehavior, + networkMonitor: NetworkMonitor, + globalProperties: AtomicDictionary = [:], + isEnabled: Bool = true + ) { self.pinpoint = pinpoint self.networkMonitor = networkMonitor self.globalProperties = globalProperties diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+Options.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+Options.swift index 9849e6e9f5..ac44e7e82f 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+Options.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+Options.swift @@ -7,8 +7,8 @@ import Foundation -extension AWSPinpointAnalyticsPlugin { - public struct Options { +public extension AWSPinpointAnalyticsPlugin { + struct Options { static let defaultAutoFlushEventsInterval: TimeInterval = 60 static let defaultTrackAppSession = true @@ -16,14 +16,18 @@ extension AWSPinpointAnalyticsPlugin { public let trackAppSessions: Bool #if os(macOS) - public init(autoFlushEventsInterval: TimeInterval = 60, - trackAppSessions: Bool = true) { + public init( + autoFlushEventsInterval: TimeInterval = 60, + trackAppSessions: Bool = true + ) { self.autoFlushEventsInterval = autoFlushEventsInterval self.trackAppSessions = trackAppSessions } #else - public init(autoFlushEventsInterval: TimeInterval = 60, - trackAppSessions: Bool = true) { + public init( + autoFlushEventsInterval: TimeInterval = 60, + trackAppSessions: Bool = true + ) { self.autoFlushEventsInterval = autoFlushEventsInterval self.trackAppSessions = trackAppSessions } diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+Reset.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+Reset.swift index c6e43f86da..3c2c0dc32f 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+Reset.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/AWSPinpointAnalyticsPlugin+Reset.swift @@ -9,9 +9,9 @@ import Amplify import Foundation @_spi(InternalAWSPinpoint) import InternalAWSPinpoint -extension AWSPinpointAnalyticsPlugin { +public extension AWSPinpointAnalyticsPlugin { /// Resets the state of the plugin - public func reset() async { + func reset() async { if pinpoint != nil { pinpoint = nil } diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Configuration/AWSPinpointAnalyticsPluginConfiguration.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Configuration/AWSPinpointAnalyticsPluginConfiguration.swift index 44456d7c60..1d625d7518 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Configuration/AWSPinpointAnalyticsPluginConfiguration.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Configuration/AWSPinpointAnalyticsPluginConfiguration.swift @@ -6,8 +6,8 @@ // @_spi(InternalAmplifyConfiguration) import Amplify -import AWSPinpoint import AWSClientRuntime +import AWSPinpoint import Foundation @_spi(InternalAWSPinpoint) import InternalAWSPinpoint @@ -58,9 +58,11 @@ public struct AWSPinpointAnalyticsPluginConfiguration { if let options { configOptions = options } else { - configOptions = .init( - autoFlushEventsInterval: try Self.getAutoFlushEventsInterval(configObject), - trackAppSessions: try Self.getTrackAppSessions(configObject)) + configOptions = try .init( + autoFlushEventsInterval: Self.getAutoFlushEventsInterval(configObject), + trackAppSessions: Self.getTrackAppSessions(configObject) + ) + } let autoSessionTrackingInterval = try Self.getAutoSessionTrackingInterval(configObject) @@ -71,14 +73,18 @@ public struct AWSPinpointAnalyticsPluginConfiguration { Self.logger.warn("Having different regions for Analytics and Targeting operations is not supported. The Analytics region will be used.") } - self.init(appId: pluginConfiguration.appId, - region: pluginConfiguration.region, - autoSessionTrackingInterval: autoSessionTrackingInterval, - options: configOptions) + self.init( + appId: pluginConfiguration.appId, + region: pluginConfiguration.region, + autoSessionTrackingInterval: autoSessionTrackingInterval, + options: configOptions + ) } - init(_ configuration: AmplifyOutputsData, - options: AWSPinpointAnalyticsPlugin.Options) throws { + init( + _ configuration: AmplifyOutputsData, + options: AWSPinpointAnalyticsPlugin.Options + ) throws { guard let analyticsConfig = configuration.analytics else { throw PluginError.pluginConfigurationError( AnalyticsPluginErrorConstant.missingAnalyticsCategoryConfiguration.errorDescription, @@ -93,16 +99,20 @@ public struct AWSPinpointAnalyticsPluginConfiguration { ) } - self.init(appId: pinpointAnalyticsConfig.appId, - region: pinpointAnalyticsConfig.awsRegion, - autoSessionTrackingInterval: Self.defaultAutoSessionTrackingInterval, - options: options) + self.init( + appId: pinpointAnalyticsConfig.appId, + region: pinpointAnalyticsConfig.awsRegion, + autoSessionTrackingInterval: Self.defaultAutoSessionTrackingInterval, + options: options + ) } - init(appId: String, - region: String, - autoSessionTrackingInterval: TimeInterval, - options: AWSPinpointAnalyticsPlugin.Options) { + init( + appId: String, + region: String, + autoSessionTrackingInterval: TimeInterval, + options: AWSPinpointAnalyticsPlugin.Options + ) { self.appId = appId self.region = region self.autoSessionTrackingInterval = autoSessionTrackingInterval @@ -148,7 +158,7 @@ public struct AWSPinpointAnalyticsPluginConfiguration { private static func getAutoSessionTrackingInterval(_ configuration: [String: JSONValue]) throws -> TimeInterval { guard let autoSessionTrackingInterval = configuration[autoSessionTrackingIntervalKey] else { - return Self.defaultAutoSessionTrackingInterval + return defaultAutoSessionTrackingInterval } guard case let .number(autoSessionTrackingIntervalValue) = autoSessionTrackingInterval else { diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Constants/AnalyticsErrorConstants.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Constants/AnalyticsErrorConstants.swift index 2ea40f5eb7..49cc32f2ba 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Constants/AnalyticsErrorConstants.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Constants/AnalyticsErrorConstants.swift @@ -10,7 +10,7 @@ import Foundation typealias AnalyticsPluginErrorString = (errorDescription: ErrorDescription, recoverySuggestion: RecoverySuggestion) -struct AnalyticsPluginErrorConstant { +enum AnalyticsPluginErrorConstant { static let decodeConfigurationError: AnalyticsPluginErrorString = ( "Unable to decode configuration", "Make sure the plugin configuration is JSONValue" diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Extensions/AWSPinpointAnalyticsPlugin+HubCategory.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Extensions/AWSPinpointAnalyticsPlugin+HubCategory.swift index a51cb40aee..286274402c 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Extensions/AWSPinpointAnalyticsPlugin+HubCategory.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Extensions/AWSPinpointAnalyticsPlugin+HubCategory.swift @@ -11,8 +11,10 @@ import Foundation extension HubCategory { func dispatchIdentifyUser(_ identityId: String, userProfile: AnalyticsUserProfile?) { - let payload = HubPayload(eventName: HubPayload.EventName.Analytics.identifyUser, - data: (identityId, userProfile)) + let payload = HubPayload( + eventName: HubPayload.EventName.Analytics.identifyUser, + data: (identityId, userProfile) + ) dispatch(to: .analytics, payload: payload) } diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Extensions/PinpointEvent+AnalyticsEvent.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Extensions/PinpointEvent+AnalyticsEvent.swift index bc51eec63c..f42e5cd596 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Extensions/PinpointEvent+AnalyticsEvent.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Extensions/PinpointEvent+AnalyticsEvent.swift @@ -9,8 +9,8 @@ import Amplify import Foundation @_spi(InternalAWSPinpoint) import InternalAWSPinpoint -extension PinpointEvent { - public func asAnalyticsEvent() -> AnalyticsEvent { +public extension PinpointEvent { + func asAnalyticsEvent() -> AnalyticsEvent { var properties: AnalyticsProperties = [:] for attribute in attributes { @@ -21,12 +21,14 @@ extension PinpointEvent { properties[metric.key] = metric.value } - return BasicAnalyticsEvent(name: eventType, - properties: properties) + return BasicAnalyticsEvent( + name: eventType, + properties: properties + ) } } -extension Array where Element == PinpointEvent { +extension [PinpointEvent] { func asAnalyticsEventArray() -> [AnalyticsEvent] { map { $0.asAnalyticsEvent() } } diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AWSPinpoint+AnalyticsErrorConvertible.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AWSPinpoint+AnalyticsErrorConvertible.swift index 42c5464f9e..d042e981cb 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AWSPinpoint+AnalyticsErrorConvertible.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AWSPinpoint+AnalyticsErrorConvertible.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPinpoint import ClientRuntime +import Foundation extension AWSPinpoint.BadRequestException: AnalyticsErrorConvertible { var analyticsError: AnalyticsError { diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorConvertible.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorConvertible.swift index e21c889309..d422e9a13e 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorConvertible.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorConvertible.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AnalyticsErrorConvertible { var analyticsError: AnalyticsError { get } diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorHelper.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorHelper.swift index da6a74fe7b..93167a2d8a 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorHelper.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorHelper.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AwsCommonRuntimeKit +import Foundation enum AnalyticsErrorHelper { static func getDefaultError(_ error: Error) -> AnalyticsError { diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/CommonRunTimeError+AnalyticsErrorConvertible.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/CommonRunTimeError+AnalyticsErrorConvertible.swift index b65918f472..07784736d3 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/CommonRunTimeError+AnalyticsErrorConvertible.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/CommonRunTimeError+AnalyticsErrorConvertible.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -@_spi(InternalAWSPinpoint) import InternalAWSPinpoint import AwsCommonRuntimeKit +import Foundation +@_spi(InternalAWSPinpoint) import InternalAWSPinpoint extension CommonRunTimeError: AnalyticsErrorConvertible { var analyticsError: AnalyticsError { diff --git a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginAmplifyVersionableTests.swift b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginAmplifyVersionableTests.swift index e9922169db..cdbb482f27 100644 --- a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginAmplifyVersionableTests.swift +++ b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginAmplifyVersionableTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPinpointAnalyticsPlugin +import XCTest // swiftlint:disable:next type_name class AWSPinpointAnalyticsPluginAmplifyVersionableTests: XCTestCase { diff --git a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginClientBehaviorTests.swift b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginClientBehaviorTests.swift index 92c4636fd3..d78ec37ffb 100644 --- a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginClientBehaviorTests.swift +++ b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginClientBehaviorTests.swift @@ -7,10 +7,10 @@ import Amplify import AWSPinpoint -@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint -@testable import AWSPinpointAnalyticsPlugin -@testable import AmplifyTestCommon import XCTest +@testable import AmplifyTestCommon +@testable import AWSPinpointAnalyticsPlugin +@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint // swiftlint:disable:next type_name class AWSPinpointAnalyticsPluginClientBehaviorTests: AWSPinpointAnalyticsPluginTestBase { @@ -18,16 +18,20 @@ class AWSPinpointAnalyticsPluginClientBehaviorTests: AWSPinpointAnalyticsPluginT let testIdentityId = "identityId" let testEmail = "testEmail" let testPlan = "testPlan" - let testProperties: [String: AnalyticsPropertyValue] = ["keyString": "value", - "keyInt": 123, - "keyDouble": 1.2, - "keyBool": true] - let testLocation = AnalyticsUserProfile.Location(latitude: 12, - longitude: 34, - postalCode: "98122", - city: "Seattle", - region: "WA", - country: "USA") + let testProperties: [String: AnalyticsPropertyValue] = [ + "keyString": "value", + "keyInt": 123, + "keyDouble": 1.2, + "keyBool": true + ] + let testLocation = AnalyticsUserProfile.Location( + latitude: 12, + longitude: 34, + postalCode: "98122", + city: "Seattle", + region: "WA", + country: "USA" + ) // MARK: IdentifyUser API @@ -52,13 +56,17 @@ class AWSPinpointAnalyticsPluginClientBehaviorTests: AWSPinpointAnalyticsPluginT } } - let userProfile = AnalyticsUserProfile(name: testName, - email: testEmail, - plan: testPlan, - location: testLocation, - properties: testProperties) - var expectedEndpointProfile = PinpointEndpointProfile(applicationId: "appId", - endpointId: "endpointId") + let userProfile = AnalyticsUserProfile( + name: testName, + email: testEmail, + plan: testPlan, + location: testLocation, + properties: testProperties + ) + var expectedEndpointProfile = PinpointEndpointProfile( + applicationId: "appId", + endpointId: "endpointId" + ) expectedEndpointProfile.addUserId(testIdentityId) expectedEndpointProfile.addUserProfile(userProfile) @@ -86,8 +94,10 @@ class AWSPinpointAnalyticsPluginClientBehaviorTests: AWSPinpointAnalyticsPluginT /// Then: AWSPinpoint.currentEndpoint and updateEndpoint methods are called /// and Hub Analytics.identifyUser event is dispatched with an error func testIdentifyUserDispatchesErrorForPinpointError() async throws { - mockPinpoint.updateEndpointProfileResult = .failure(NSError(domain: "domain", - code: 1)) + mockPinpoint.updateEndpointProfileResult = .failure(NSError( + domain: "domain", + code: 1 + )) let analyticsEventReceived = expectation(description: "Analytics event was received on the hub plugin") _ = plugin.listen(to: .analytics, isIncluded: nil) { payload in @@ -103,13 +113,17 @@ class AWSPinpointAnalyticsPluginClientBehaviorTests: AWSPinpointAnalyticsPluginT } } - let userProfile = AnalyticsUserProfile(name: testName, - email: testEmail, - plan: testPlan, - location: testLocation, - properties: testProperties) - var expectedEndpointProfile = PinpointEndpointProfile(applicationId: "appId", - endpointId: "endpointId") + let userProfile = AnalyticsUserProfile( + name: testName, + email: testEmail, + plan: testPlan, + location: testLocation, + properties: testProperties + ) + var expectedEndpointProfile = PinpointEndpointProfile( + applicationId: "appId", + endpointId: "endpointId" + ) expectedEndpointProfile.addUserId(testIdentityId) expectedEndpointProfile.addUserProfile(userProfile) @@ -170,9 +184,11 @@ class AWSPinpointAnalyticsPluginClientBehaviorTests: AWSPinpointAnalyticsPluginT /// Then: AWSPinpoint.createEvent and record methods are called /// and Hub Analytics.record event is dispatched with a error func testRecordEventDispatchesErrorForPinpointError() async { - mockPinpoint.recordResult = .failure(NSError(domain: "domain", - code: 1, - userInfo: nil)) + mockPinpoint.recordResult = .failure(NSError( + domain: "domain", + code: 1, + userInfo: nil + )) let expectedPinpointEvent = PinpointEvent(eventType: testName, session: PinpointSession(appId: "", uniqueId: "")) mockPinpoint.createEventResult = expectedPinpointEvent expectedPinpointEvent.addProperties(testProperties) @@ -246,9 +262,11 @@ class AWSPinpointAnalyticsPluginClientBehaviorTests: AWSPinpointAnalyticsPluginT /// Then: AWSPinpoint.createEvent and record methods are called /// and Hub Analytics.record event is dispatched with a error func testRecordEventWithNameDispatchesErrorForPinpointError() async { - mockPinpoint.recordResult = .failure(NSError(domain: "domain", - code: 1, - userInfo: nil)) + mockPinpoint.recordResult = .failure(NSError( + domain: "domain", + code: 1, + userInfo: nil + )) let expectedPinpointEvent = PinpointEvent(eventType: testName, session: PinpointSession(appId: "", uniqueId: "")) mockPinpoint.createEventResult = expectedPinpointEvent @@ -281,9 +299,9 @@ class AWSPinpointAnalyticsPluginClientBehaviorTests: AWSPinpointAnalyticsPluginT func testRegisterGlobalProperties() async { mockPinpoint.addGlobalPropertyExpectation = expectation(description: "Add global property called") mockPinpoint.addGlobalPropertyExpectation?.expectedFulfillmentCount = testProperties.count - + analyticsPlugin.registerGlobalProperties(testProperties) - + await fulfillment(of: [mockPinpoint.addGlobalPropertyExpectation!], timeout: 1) XCTAssertEqual(analyticsPlugin.globalProperties.count, testProperties.count) XCTAssertTrue(mockPinpoint.addGlobalMetricCalled > 0) @@ -310,7 +328,7 @@ class AWSPinpointAnalyticsPluginClientBehaviorTests: AWSPinpointAnalyticsPluginT func testUnregisterGlobalProperties() async { mockPinpoint.removeGlobalPropertyExpectation = expectation(description: "Remove global property called") mockPinpoint.removeGlobalPropertyExpectation?.expectedFulfillmentCount = testProperties.count - + analyticsPlugin.globalProperties = AtomicDictionary(initialValue: testProperties) analyticsPlugin.unregisterGlobalProperties(Set(testProperties.keys)) @@ -343,8 +361,10 @@ class AWSPinpointAnalyticsPluginClientBehaviorTests: AWSPinpointAnalyticsPluginT /// Then: AWSPinpoint.submitEvents is invoked /// and Hub Analytics.flushEvents event is dispatched with submitted events func testFlushEvents_isOnline() async { - let result = [PinpointEvent(eventType: "1", session: PinpointSession(appId: "", uniqueId: "")), - PinpointEvent(eventType: "2", session: PinpointSession(appId: "", uniqueId: ""))] + let result = [ + PinpointEvent(eventType: "1", session: PinpointSession(appId: "", uniqueId: "")), + PinpointEvent(eventType: "2", session: PinpointSession(appId: "", uniqueId: "")) + ] mockNetworkMonitor.isOnline = true mockPinpoint.submitEventsResult = .success(result) let methodWasInvokedOnPlugin = expectation(description: "method was invoked on plugin") @@ -365,7 +385,7 @@ class AWSPinpointAnalyticsPluginClientBehaviorTests: AWSPinpointAnalyticsPluginT await fulfillment(of: [methodWasInvokedOnPlugin], timeout: 1) mockPinpoint.verifySubmitEvents() } - + /// Given: The device does not have internet access /// When: AnalyticsPlugin.flushEvents is invoked /// Then: AWSPinpoint.submitEvents is invoked @@ -407,9 +427,11 @@ class AWSPinpointAnalyticsPluginClientBehaviorTests: AWSPinpointAnalyticsPluginT /// Then: AWSPinpoint.submitEvents is invoked /// and Hub Analytics.flushEvents event is dispatched with error func testFlushEventsDispatchesErrorForPinpointError() async { - mockPinpoint.submitEventsResult = .failure(NSError(domain: "domain", - code: 1, - userInfo: nil)) + mockPinpoint.submitEventsResult = .failure(NSError( + domain: "domain", + code: 1, + userInfo: nil + )) let methodWasInvokedOnPlugin = expectation(description: "method was invoked on plugin") _ = plugin.listen(to: .analytics, isIncluded: nil) { payload in diff --git a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginConfigureTests.swift b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginConfigureTests.swift index 83de1f08d4..5e0e8e5a13 100644 --- a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginConfigureTests.swift +++ b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginConfigureTests.swift @@ -5,19 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // +import XCTest @testable @_spi(InternalAmplifyConfiguration) import Amplify @testable import AmplifyTestCommon -@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint @testable import AWSPinpointAnalyticsPlugin -import XCTest +@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint class AWSPinpointAnalyticsPluginConfigureTests: AWSPinpointAnalyticsPluginTestBase { - + override func setUp() async throws { AWSPinpointFactory.credentialIdentityResolver = MockCredentialsProvider() try await super.setUp() } - + // MARK: Plugin Key test func testPluginKey() { @@ -95,7 +95,8 @@ class AWSPinpointAnalyticsPluginConfigureTests: AWSPinpointAnalyticsPluginTestBa let analyticsPlugin = AWSPinpointAnalyticsPlugin( options: .init( autoFlushEventsInterval: 50, - trackAppSessions: true)) + trackAppSessions: true + )) try analyticsPlugin.configure(using: analyticsPluginConfig) XCTAssertNotNil(analyticsPlugin.pinpoint) @@ -115,7 +116,8 @@ class AWSPinpointAnalyticsPluginConfigureTests: AWSPinpointAnalyticsPluginTestBa XCTFail("Analytics configuration should not succeed") } catch { guard let pluginError = error as? PluginError, - case .pluginConfigurationError = pluginError else { + case .pluginConfigurationError = pluginError + else { XCTFail("Should throw invalidConfiguration exception. But received \(error) ") return } @@ -126,8 +128,10 @@ class AWSPinpointAnalyticsPluginConfigureTests: AWSPinpointAnalyticsPluginTestBa func testConfigure_WithAmplifyOutputs() { let config = AmplifyOutputsData.init(analytics: .init( - amazonPinpoint: .init(awsRegion: testRegion, - appId: testAppId))) + amazonPinpoint: .init( + awsRegion: testRegion, + appId: testAppId + ))) do { let analyticsPlugin = AWSPinpointAnalyticsPlugin() @@ -148,13 +152,16 @@ class AWSPinpointAnalyticsPluginConfigureTests: AWSPinpointAnalyticsPluginTestBa func testConfigure_WithAmplifyOutputsAndOptions() { let config = AmplifyOutputsData.init(analytics: .init( - amazonPinpoint: .init(awsRegion: testRegion, - appId: testAppId))) + amazonPinpoint: .init( + awsRegion: testRegion, + appId: testAppId + ))) do { let analyticsPlugin = AWSPinpointAnalyticsPlugin(options: .init( autoFlushEventsInterval: 100, - trackAppSessions: false)) + trackAppSessions: false + )) try analyticsPlugin.configure(using: config) XCTAssertNotNil(analyticsPlugin.pinpoint) diff --git a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginResetTests.swift b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginResetTests.swift index a5338f8e5e..b2e8be43be 100644 --- a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginResetTests.swift +++ b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginResetTests.swift @@ -7,8 +7,8 @@ import Amplify @_spi(InternalAWSPinpoint) import InternalAWSPinpoint -@testable import AWSPinpointAnalyticsPlugin import XCTest +@testable import AWSPinpointAnalyticsPlugin class AWSPinpointAnalyticsPluginResetTests: AWSPinpointAnalyticsPluginTestBase { func testReset() async { diff --git a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginTestBase.swift b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginTestBase.swift index 6e637db34a..bfefb36938 100644 --- a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginTestBase.swift +++ b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/AWSPinpointAnalyticsPluginTestBase.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import XCTest @testable import Amplify @testable import AmplifyTestCommon -@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint @testable import AWSPinpointAnalyticsPlugin -import XCTest +@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint class AWSPinpointAnalyticsPluginTestBase: XCTestCase { var analyticsPlugin: AWSPinpointAnalyticsPlugin! @@ -24,7 +24,8 @@ class AWSPinpointAnalyticsPluginTestBase: XCTestCase { var plugin: HubCategoryPlugin { guard let plugin = try? Amplify.Hub.getPlugin(for: "awsHubPlugin"), - plugin.key == "awsHubPlugin" else { + plugin.key == "awsHubPlugin" + else { fatalError("Could not access awsHubPlugin") } return plugin @@ -36,8 +37,10 @@ class AWSPinpointAnalyticsPluginTestBase: XCTestCase { mockPinpoint = MockAWSPinpoint() mockNetworkMonitor = MockNetworkMonitor() - analyticsPlugin.configure(pinpoint: mockPinpoint, - networkMonitor: mockNetworkMonitor) + analyticsPlugin.configure( + pinpoint: mockPinpoint, + networkMonitor: mockNetworkMonitor + ) await Amplify.reset() let config = AmplifyConfiguration() diff --git a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Configuration/AWSPinpointAnalyticsPluginAmplifyOutputsConfigurationTests.swift b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Configuration/AWSPinpointAnalyticsPluginAmplifyOutputsConfigurationTests.swift index e4aeffa943..129a735cbd 100644 --- a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Configuration/AWSPinpointAnalyticsPluginAmplifyOutputsConfigurationTests.swift +++ b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Configuration/AWSPinpointAnalyticsPluginAmplifyOutputsConfigurationTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable @_spi(InternalAmplifyConfiguration) import Amplify import XCTest -@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint +@testable @_spi(InternalAmplifyConfiguration) import Amplify @testable import AWSPinpointAnalyticsPlugin +@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint // swiftlint:disable:next type_name class AWSPinpointAnalyticsPluginAmplifyOutputsConfigurationTests: XCTestCase { @@ -34,20 +34,29 @@ class AWSPinpointAnalyticsPluginAmplifyOutputsConfigurationTests: XCTestCase { XCTAssertNotNil(result) XCTAssertEqual(result.appId, testAppId) XCTAssertEqual(result.region, testRegion) - XCTAssertEqual(result.options.autoFlushEventsInterval, - AWSPinpointAnalyticsPlugin.Options.defaultAutoFlushEventsInterval) - XCTAssertEqual(result.options.trackAppSessions, - AWSPinpointAnalyticsPlugin.Options.defaultTrackAppSession) - XCTAssertEqual(result.autoSessionTrackingInterval, - AWSPinpointAnalyticsPluginConfiguration.defaultAutoSessionTrackingInterval) + XCTAssertEqual( + result.options.autoFlushEventsInterval, + AWSPinpointAnalyticsPlugin.Options.defaultAutoFlushEventsInterval + ) + XCTAssertEqual( + result.options.trackAppSessions, + AWSPinpointAnalyticsPlugin.Options.defaultTrackAppSession + ) + XCTAssertEqual( + result.autoSessionTrackingInterval, + AWSPinpointAnalyticsPluginConfiguration.defaultAutoSessionTrackingInterval + ) } func testConfiguration_OptionsOverride() throws { let config = AmplifyOutputsData(analytics: .init(amazonPinpoint: .init(awsRegion: testRegion, appId: appId))) let result = try AWSPinpointAnalyticsPluginConfiguration( config, - options: .init(autoFlushEventsInterval: 100, - trackAppSessions: false)) + options: .init( + autoFlushEventsInterval: 100, + trackAppSessions: false + ) + ) XCTAssertNotNil(result) XCTAssertEqual(result.appId, testAppId) XCTAssertEqual(result.region, testRegion) @@ -65,8 +74,10 @@ class AWSPinpointAnalyticsPluginAmplifyOutputsConfigurationTests: XCTestCase { XCTFail("Expected to catch PluginError.pluginConfigurationError.") return } - XCTAssertEqual(errorDescription, - AnalyticsPluginErrorConstant.missingAnalyticsCategoryConfiguration.errorDescription) + XCTAssertEqual( + errorDescription, + AnalyticsPluginErrorConstant.missingAnalyticsCategoryConfiguration.errorDescription + ) } } @@ -79,8 +90,10 @@ class AWSPinpointAnalyticsPluginAmplifyOutputsConfigurationTests: XCTestCase { XCTFail("Expected to catch PluginError.pluginConfigurationError.") return } - XCTAssertEqual(errorDescription, - AnalyticsPluginErrorConstant.missingAmazonPinpointConfiguration.errorDescription) + XCTAssertEqual( + errorDescription, + AnalyticsPluginErrorConstant.missingAmazonPinpointConfiguration.errorDescription + ) } } } diff --git a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Configuration/AWSPinpointAnalyticsPluginConfigurationTests.swift b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Configuration/AWSPinpointAnalyticsPluginConfigurationTests.swift index f7b8f7216f..2407a7fea3 100644 --- a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Configuration/AWSPinpointAnalyticsPluginConfigurationTests.swift +++ b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Configuration/AWSPinpointAnalyticsPluginConfigurationTests.swift @@ -7,8 +7,8 @@ import Amplify import XCTest -@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint @testable import AWSPinpointAnalyticsPlugin +@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint // swiftlint:disable:next type_name class AWSPinpointAnalyticsPluginConfigurationTests: XCTestCase { @@ -42,17 +42,23 @@ class AWSPinpointAnalyticsPluginConfigurationTests: XCTestCase { XCTAssertNotNil(config) XCTAssertEqual(config.appId, testAppId) XCTAssertEqual(config.region, testRegion) - XCTAssertEqual(config.options.autoFlushEventsInterval, - AWSPinpointAnalyticsPlugin.Options.defaultAutoFlushEventsInterval) - XCTAssertEqual(config.options.trackAppSessions, - AWSPinpointAnalyticsPlugin.Options.defaultTrackAppSession) - XCTAssertEqual(config.autoSessionTrackingInterval, - AWSPinpointAnalyticsPluginConfiguration.defaultAutoSessionTrackingInterval) + XCTAssertEqual( + config.options.autoFlushEventsInterval, + AWSPinpointAnalyticsPlugin.Options.defaultAutoFlushEventsInterval + ) + XCTAssertEqual( + config.options.trackAppSessions, + AWSPinpointAnalyticsPlugin.Options.defaultTrackAppSession + ) + XCTAssertEqual( + config.autoSessionTrackingInterval, + AWSPinpointAnalyticsPluginConfiguration.defaultAutoSessionTrackingInterval + ) } catch { XCTFail("Failed to instantiate analytics plugin configuration") } } - + func testConfigureSuccess_withoutTargetingConfiguration() throws { let analyticsPluginConfig = JSONValue( dictionaryLiteral: @@ -64,12 +70,18 @@ class AWSPinpointAnalyticsPluginConfigurationTests: XCTestCase { XCTAssertNotNil(config) XCTAssertEqual(config.appId, testAppId) XCTAssertEqual(config.region, testRegion) - XCTAssertEqual(config.options.autoFlushEventsInterval, - AWSPinpointAnalyticsPlugin.Options.defaultAutoFlushEventsInterval) - XCTAssertEqual(config.options.trackAppSessions, - AWSPinpointAnalyticsPlugin.Options.defaultTrackAppSession) - XCTAssertEqual(config.autoSessionTrackingInterval, - AWSPinpointAnalyticsPluginConfiguration.defaultAutoSessionTrackingInterval) + XCTAssertEqual( + config.options.autoFlushEventsInterval, + AWSPinpointAnalyticsPlugin.Options.defaultAutoFlushEventsInterval + ) + XCTAssertEqual( + config.options.trackAppSessions, + AWSPinpointAnalyticsPlugin.Options.defaultTrackAppSession + ) + XCTAssertEqual( + config.autoSessionTrackingInterval, + AWSPinpointAnalyticsPluginConfiguration.defaultAutoSessionTrackingInterval + ) } catch { XCTFail("Failed to instantiate analytics plugin configuration") } @@ -88,10 +100,14 @@ class AWSPinpointAnalyticsPluginConfigurationTests: XCTestCase { XCTAssertEqual(config.appId, testAppId) XCTAssertEqual(config.region, testRegion) XCTAssertEqual(config.options.autoFlushEventsInterval, testAutoFlushInterval) - XCTAssertEqual(config.options.trackAppSessions, - AWSPinpointAnalyticsPlugin.Options.defaultTrackAppSession) - XCTAssertEqual(config.autoSessionTrackingInterval, - AWSPinpointAnalyticsPluginConfiguration.defaultAutoSessionTrackingInterval) + XCTAssertEqual( + config.options.trackAppSessions, + AWSPinpointAnalyticsPlugin.Options.defaultTrackAppSession + ) + XCTAssertEqual( + config.autoSessionTrackingInterval, + AWSPinpointAnalyticsPluginConfiguration.defaultAutoSessionTrackingInterval + ) } catch { XCTFail("Failed to instantiate analytics plugin configuration") } @@ -110,8 +126,10 @@ class AWSPinpointAnalyticsPluginConfigurationTests: XCTestCase { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - AnalyticsPluginErrorConstant.invalidAutoFlushEventsInterval.errorDescription) + XCTAssertEqual( + errorDescription, + AnalyticsPluginErrorConstant.invalidAutoFlushEventsInterval.errorDescription + ) } } @@ -127,11 +145,15 @@ class AWSPinpointAnalyticsPluginConfigurationTests: XCTestCase { XCTAssertNotNil(config) XCTAssertEqual(config.appId, testAppId) XCTAssertEqual(config.region, testRegion) - XCTAssertEqual(config.options.autoFlushEventsInterval, - AWSPinpointAnalyticsPlugin.Options.defaultAutoFlushEventsInterval) + XCTAssertEqual( + config.options.autoFlushEventsInterval, + AWSPinpointAnalyticsPlugin.Options.defaultAutoFlushEventsInterval + ) XCTAssertEqual(config.options.trackAppSessions, testTrackAppSession) - XCTAssertEqual(config.autoSessionTrackingInterval, - AWSPinpointAnalyticsPluginConfiguration.defaultAutoSessionTrackingInterval) + XCTAssertEqual( + config.autoSessionTrackingInterval, + AWSPinpointAnalyticsPluginConfiguration.defaultAutoSessionTrackingInterval + ) } catch { XCTFail("Failed to instantiate analytics plugin configuration") } @@ -149,8 +171,10 @@ class AWSPinpointAnalyticsPluginConfigurationTests: XCTestCase { XCTAssertNotNil(config) XCTAssertEqual(config.appId, testAppId) XCTAssertEqual(config.region, testRegion) - XCTAssertEqual(config.options.autoFlushEventsInterval, - AWSPinpointAnalyticsPlugin.Options.defaultAutoFlushEventsInterval) + XCTAssertEqual( + config.options.autoFlushEventsInterval, + AWSPinpointAnalyticsPlugin.Options.defaultAutoFlushEventsInterval + ) XCTAssertEqual(config.options.trackAppSessions, AWSPinpointAnalyticsPlugin.Options.defaultTrackAppSession) XCTAssertEqual(config.autoSessionTrackingInterval, testAutoSessionTrackingInterval) } catch { @@ -171,8 +195,10 @@ class AWSPinpointAnalyticsPluginConfigurationTests: XCTestCase { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - AnalyticsPluginErrorConstant.invalidAutoSessionTrackingInterval.errorDescription) + XCTAssertEqual( + errorDescription, + AnalyticsPluginErrorConstant.invalidAutoSessionTrackingInterval.errorDescription + ) } } @@ -184,13 +210,15 @@ class AWSPinpointAnalyticsPluginConfigurationTests: XCTestCase { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - AnalyticsPluginErrorConstant.configurationObjectExpected.errorDescription) + XCTAssertEqual( + errorDescription, + AnalyticsPluginErrorConstant.configurationObjectExpected.errorDescription + ) } } func testConfigureThrowsErrorForMissingPinpointAnalyticsConfiguration() { - + let analyticsPluginConfig = JSONValue( dictionaryLiteral: (AWSPinpointAnalyticsPluginConfiguration.regionConfigKey, region) @@ -201,8 +229,10 @@ class AWSPinpointAnalyticsPluginConfigurationTests: XCTestCase { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - AnalyticsPluginErrorConstant.missingPinpointAnalyicsConfiguration.errorDescription) + XCTAssertEqual( + errorDescription, + AnalyticsPluginErrorConstant.missingPinpointAnalyicsConfiguration.errorDescription + ) } } @@ -218,8 +248,10 @@ class AWSPinpointAnalyticsPluginConfigurationTests: XCTestCase { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - AWSPinpointErrorConstants.pinpointConfigurationExpected.errorDescription) + XCTAssertEqual( + errorDescription, + AWSPinpointErrorConstants.pinpointConfigurationExpected.errorDescription + ) } } diff --git a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockAWSPinpoint+Analytics.swift b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockAWSPinpoint+Analytics.swift index 9466403f55..8de6ddffea 100644 --- a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockAWSPinpoint+Analytics.swift +++ b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockAWSPinpoint+Analytics.swift @@ -7,13 +7,13 @@ import Amplify import AWSPinpoint -@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint -@testable import AWSPinpointAnalyticsPlugin import Foundation import StoreKit +@testable import AWSPinpointAnalyticsPlugin +@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint extension MockAWSPinpoint { - public func addGlobalProperty(_ value: AnalyticsPropertyValue, forKey: String) { + func addGlobalProperty(_ value: AnalyticsPropertyValue, forKey: String) { if let value = value as? String { addGlobalAttribute(value, forKey: forKey) } else if let value = value as? Int { @@ -26,7 +26,7 @@ extension MockAWSPinpoint { addGlobalPropertyExpectation?.fulfill() } - public func removeGlobalProperty(_ value: AnalyticsPropertyValue, forKey: String) { + func removeGlobalProperty(_ value: AnalyticsPropertyValue, forKey: String) { if value is String || value is Bool { removeGlobalAttribute(forKey: forKey) } else if value is Int || value is Double { @@ -35,14 +35,14 @@ extension MockAWSPinpoint { removeGlobalPropertyExpectation?.fulfill() } - public func addGlobalAttribute(_ theValue: String, forKey theKey: String) { + func addGlobalAttribute(_ theValue: String, forKey theKey: String) { addGlobalAttributeCalled += 1 addGlobalAttributeValue = theValue addGlobalAttributeKey = theKey } - public func addGlobalAttribute(_ theValue: String, forKey theKey: String, forEventType theEventType: String) { + func addGlobalAttribute(_ theValue: String, forKey theKey: String, forEventType theEventType: String) { addGlobalAttributeCalled += 1 addGlobalAttributeValue = theValue @@ -50,14 +50,14 @@ extension MockAWSPinpoint { addGlobalAttributeEventType = theEventType } - public func addGlobalMetric(_ theValue: Double, forKey theKey: String) { + func addGlobalMetric(_ theValue: Double, forKey theKey: String) { addGlobalMetricCalled += 1 addGlobalMetricValue = theValue addGlobalMetricKey = theKey } - public func addGlobalMetric(_ theValue: Double, forKey theKey: String, forEventType theEventType: String) { + func addGlobalMetric(_ theValue: Double, forKey theKey: String, forEventType theEventType: String) { addGlobalMetricCalled += 1 addGlobalMetricValue = theValue @@ -65,30 +65,30 @@ extension MockAWSPinpoint { addGlobalMetricEventType = theEventType } - public func removeGlobalAttribute(forKey theKey: String) { + func removeGlobalAttribute(forKey theKey: String) { removeGlobalAttributeCalled += 1 removeGlobalAttributeKey = theKey } - public func removeGlobalAttribute(forKey theKey: String, forEventType theEventType: String) { + func removeGlobalAttribute(forKey theKey: String, forEventType theEventType: String) { removeGlobalAttributeCalled += 1 removeGlobalAttributeKey = theKey removeGlobalAttributeEventType = theEventType } - public func removeGlobalMetric(forKey theKey: String) { + func removeGlobalMetric(forKey theKey: String) { removeGlobalMetricCalled += 1 removeGlobalMetricKey = theKey } - public func removeGlobalMetric(forKey theKey: String, forEventType theEventType: String) { + func removeGlobalMetric(forKey theKey: String, forEventType theEventType: String) { removeGlobalMetricCalled += 1 removeGlobalMetricKey = theKey removeglobalMetricEventType = theEventType } - public func record(_ theEvent: PinpointEvent) async throws { + func record(_ theEvent: PinpointEvent) async throws { recordCalled += 1 recordEvent = theEvent @@ -97,15 +97,17 @@ extension MockAWSPinpoint { } } - public func createEvent(withEventType theEventType: String) -> PinpointEvent { + func createEvent(withEventType theEventType: String) -> PinpointEvent { createEventCalled += 1 createEventEventType = theEventType return createEventResult ?? createEmptyEvent() } - public func createAppleMonetizationEvent(with transaction: SKPaymentTransaction, - with product: SKProduct) -> PinpointEvent { + func createAppleMonetizationEvent( + with transaction: SKPaymentTransaction, + with product: SKProduct + ) -> PinpointEvent { createAppleMonetizationEventCalled += 1 createAppleMonetizationEventTransaction = transaction createAppleMonetizationEventProduct = product @@ -113,10 +115,12 @@ extension MockAWSPinpoint { return createAppleMonetizationEventResult ?? createEmptyEvent() } - public func createVirtualMonetizationEvent(withProductId theProductId: String, - withItemPrice theItemPrice: Double, - withQuantity theQuantity: Int, - withCurrency theCurrency: String) -> PinpointEvent { + func createVirtualMonetizationEvent( + withProductId theProductId: String, + withItemPrice theItemPrice: Double, + withQuantity theQuantity: Int, + withCurrency theCurrency: String + ) -> PinpointEvent { createVirtualMonetizationEventCalled += 1 createVirtualMonetizationEventProductId = theProductId createVirtualMonetizationEventItemPrice = theItemPrice @@ -126,11 +130,11 @@ extension MockAWSPinpoint { return createVirtualMonetizationEventResult ?? createEmptyEvent() } - public func submitEvents() async throws { + func submitEvents() async throws { submitEventsCalled += 1 } - public func submitEvents() async throws -> [PinpointEvent] { + func submitEvents() async throws -> [PinpointEvent] { submitEventsCalled += 1 switch submitEventsResult { case .success(let result): @@ -143,20 +147,24 @@ extension MockAWSPinpoint { } private func createEmptyEvent() -> PinpointEvent { - return PinpointEvent(eventType: "", - session: PinpointSession(appId: "", uniqueId: "")) + return PinpointEvent( + eventType: "", + session: PinpointSession(appId: "", uniqueId: "") + ) } - - public func setAutomaticSubmitEventsInterval(_ interval: TimeInterval, - onSubmit: AnalyticsClientBehaviour.SubmitResult?) { - + + func setAutomaticSubmitEventsInterval( + _ interval: TimeInterval, + onSubmit: AnalyticsClientBehaviour.SubmitResult? + ) { + } - - public func startTrackingSessions(backgroundTimeout: TimeInterval) { - + + func startTrackingSessions(backgroundTimeout: TimeInterval) { + } - func setRemoteGlobalAttributes(_ attributes: [String : String]) async { + func setRemoteGlobalAttributes(_ attributes: [String: String]) async { } } diff --git a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockAWSPinpoint+Targeting.swift b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockAWSPinpoint+Targeting.swift index 429d2ffd8d..3dd090cf08 100644 --- a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockAWSPinpoint+Targeting.swift +++ b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockAWSPinpoint+Targeting.swift @@ -6,18 +6,18 @@ // import AWSPinpoint -@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint -@testable import AWSPinpointAnalyticsPlugin import Foundation +@testable import AWSPinpointAnalyticsPlugin +@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint extension MockAWSPinpoint { - public func currentEndpointProfile() -> PinpointEndpointProfile { + func currentEndpointProfile() -> PinpointEndpointProfile { currentEndpointProfileCalled += 1 return PinpointEndpointProfile(applicationId: applicationId, endpointId: endpointId) } - public func updateEndpointProfile() async throws { + func updateEndpointProfile() async throws { updateEndpointProfileCalled += 1 if case let .failure(error) = updateEndpointProfileResult { @@ -25,8 +25,10 @@ extension MockAWSPinpoint { } } - public func updateEndpoint(with endpointProfile: PinpointEndpointProfile, - source: AWSPinpointSource) async throws { + func updateEndpoint( + with endpointProfile: PinpointEndpointProfile, + source: AWSPinpointSource + ) async throws { updateEndpointProfileCalled += 1 updateEndpointProfileValue = endpointProfile @@ -35,27 +37,27 @@ extension MockAWSPinpoint { } } - public func addAttributes(_ attributes: [String], forKey key: String) { + func addAttributes(_ attributes: [String], forKey key: String) { addAttributeCalled += 1 addAttributeValue = attributes addAttributeKey = key } - public func removeAttributes(forKey key: String) { + func removeAttributes(forKey key: String) { removeAttributeCalled += 1 removeAttributeKey = key } - public func addMetric(_ metric: Double, forKey key: String) { + func addMetric(_ metric: Double, forKey key: String) { addMetricCalled += 1 addMetricValue = metric addMetricKey = key } - public func removeMetric(forKey theKey: String) { + func removeMetric(forKey theKey: String) { removeMetricCalled += 1 removeMetricKey = theKey diff --git a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockAWSPinpoint.swift b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockAWSPinpoint.swift index 9c445fb449..1e80ceca3d 100644 --- a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockAWSPinpoint.swift +++ b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockAWSPinpoint.swift @@ -10,8 +10,8 @@ import Foundation import StoreKit import XCTest -@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint @testable import AWSPinpointAnalyticsPlugin +@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint class MockAWSPinpoint: AWSPinpointBehavior { let applicationId = "applicationId" @@ -81,7 +81,7 @@ class MockAWSPinpoint: AWSPinpointBehavior { var createAppleMonetizationEventResult: PinpointEvent? var createVirtualMonetizationEventResult: PinpointEvent? var submitEventsResult: Result<[PinpointEvent], Error>? - + var addGlobalPropertyExpectation: XCTestExpectation? var removeGlobalPropertyExpectation: XCTestExpectation? @@ -216,17 +216,21 @@ extension MockAWSPinpoint { XCTAssertEqual(createEventEventType, theEventType) } - public func verifyCreateAppleMonetizationEvent(with transaction: SKPaymentTransaction, - with product: SKProduct) { + public func verifyCreateAppleMonetizationEvent( + with transaction: SKPaymentTransaction, + with product: SKProduct + ) { XCTAssertEqual(createAppleMonetizationEventCalled, 1) XCTAssertEqual(createAppleMonetizationEventTransaction, transaction) XCTAssertEqual(createAppleMonetizationEventProduct, product) } - public func verifyCreateVirtualMonetizationEvent(withProductId theProductId: String, - withItemPrice theItemPrice: Double, - withQuantity theQuantity: Int, - withCurrency theCurrency: String) { + public func verifyCreateVirtualMonetizationEvent( + withProductId theProductId: String, + withItemPrice theItemPrice: Double, + withQuantity theQuantity: Int, + withCurrency theCurrency: String + ) { XCTAssertEqual(createVirtualMonetizationEventCalled, 1) XCTAssertEqual(createVirtualMonetizationEventProductId, theProductId) XCTAssertEqual(createVirtualMonetizationEventItemPrice, theItemPrice) diff --git a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockNetworkMonitor.swift b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockNetworkMonitor.swift index bcd1099b71..9298fcdd46 100644 --- a/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockNetworkMonitor.swift +++ b/AmplifyPlugins/Analytics/Tests/AWSPinpointAnalyticsPluginUnitTests/Mocks/MockNetworkMonitor.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSPinpointAnalyticsPlugin import Foundation +@testable import AWSPinpointAnalyticsPlugin class MockNetworkMonitor: NetworkMonitor { var isOnline = true diff --git a/AmplifyPlugins/Analytics/Tests/AnalyticsHostApp/AWSPinpointAnalyticsPluginIntegrationTests/AWSPinpointAnalyticsPluginIntegrationTests.swift b/AmplifyPlugins/Analytics/Tests/AnalyticsHostApp/AWSPinpointAnalyticsPluginIntegrationTests/AWSPinpointAnalyticsPluginIntegrationTests.swift index 92051447d1..5ddeea4ef0 100644 --- a/AmplifyPlugins/Analytics/Tests/AnalyticsHostApp/AWSPinpointAnalyticsPluginIntegrationTests/AWSPinpointAnalyticsPluginIntegrationTests.swift +++ b/AmplifyPlugins/Analytics/Tests/AnalyticsHostApp/AWSPinpointAnalyticsPluginIntegrationTests/AWSPinpointAnalyticsPluginIntegrationTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPinpoint +import XCTest -@testable import Amplify -@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint -@testable import AWSPinpointAnalyticsPlugin import AWSCognitoAuthPlugin import Network +@testable import Amplify +@testable import AWSPinpointAnalyticsPlugin +@_spi(InternalAWSPinpoint) @testable import InternalAWSPinpoint // swiftlint:disable:next type_name class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { @@ -20,7 +20,7 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { static let amplifyConfiguration = "testconfiguration/AWSPinpointAnalyticsPluginIntegrationTests-amplifyconfiguration" static let amplifyOutputs = "testconfiguration/AWSPinpointAnalyticsPluginIntegrationTests-amplify_outputs" static let analyticsPluginKey = "awsPinpointAnalyticsPlugin" - + var useGen2Configuration: Bool { ProcessInfo.processInfo.arguments.contains("GEN2") } @@ -65,27 +65,33 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { } } - let location = AnalyticsUserProfile.Location(latitude: 47.606209, - longitude: -122.332069, - postalCode: "98122", - city: "Seattle", - region: "WA", - country: "USA") - let properties = ["userPropertyStringKey": "userProperyStringValue", - "userPropertyIntKey": 123, - "userPropertyDoubleKey": 12.34, - "userPropertyBoolKey": true] as [String: AnalyticsPropertyValue] - let userProfile = AnalyticsUserProfile(name: "name", - email: "email", - plan: "plan", - location: location, - properties: properties) + let location = AnalyticsUserProfile.Location( + latitude: 47.606209, + longitude: -122.332069, + postalCode: "98122", + city: "Seattle", + region: "WA", + country: "USA" + ) + let properties = [ + "userPropertyStringKey": "userProperyStringValue", + "userPropertyIntKey": 123, + "userPropertyDoubleKey": 12.34, + "userPropertyBoolKey": true + ] as [String: AnalyticsPropertyValue] + let userProfile = AnalyticsUserProfile( + name: "name", + email: "email", + plan: "plan", + location: location, + properties: properties + ) Amplify.Analytics.identifyUser(userId: userId, userProfile: userProfile) await fulfillment( - of: [identifyUserEvent], - timeout: TestCommonConstants.networkTimeout - ) + of: [identifyUserEvent], + timeout: TestCommonConstants.networkTimeout + ) // Remove userId from the current endpoint let endpointClient = endpointClient() @@ -123,7 +129,7 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { } } networkMonitor.start(queue: DispatchQueue(label: "AWSPinpointAnalyticsPluginIntergrationTests.NetworkMonitor")) - + let flushEventsInvoked = expectation(description: "Flush events invoked") _ = Amplify.Hub.listen(to: .analytics, isIncluded: nil) { payload in if payload.eventName == HubPayload.EventName.Analytics.flushEvents { @@ -137,25 +143,29 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { } } - let globalProperties = ["globalPropertyStringKey": "eventProperyStringValue", - "globalPropertyIntKey": 123, - "globalPropertyDoubleKey": 12.34, - "globalPropertyBoolKey": true] as [String: AnalyticsPropertyValue] + let globalProperties = [ + "globalPropertyStringKey": "eventProperyStringValue", + "globalPropertyIntKey": 123, + "globalPropertyDoubleKey": 12.34, + "globalPropertyBoolKey": true + ] as [String: AnalyticsPropertyValue] Amplify.Analytics.registerGlobalProperties(globalProperties) - let properties = ["eventPropertyStringKey": "eventProperyStringValue", - "eventPropertyIntKey": 123, - "eventPropertyDoubleKey": 12.34, - "eventPropertyBoolKey": true] as [String: AnalyticsPropertyValue] + let properties = [ + "eventPropertyStringKey": "eventProperyStringValue", + "eventPropertyIntKey": 123, + "eventPropertyDoubleKey": 12.34, + "eventPropertyBoolKey": true + ] as [String: AnalyticsPropertyValue] let event = BasicAnalyticsEvent(name: "eventName", properties: properties) Amplify.Analytics.record(event: event) - + await fulfillment(of: [onlineExpectation], timeout: TestCommonConstants.networkTimeout) Amplify.Analytics.flushEvents() await fulfillment(of: [flushEventsInvoked], timeout: TestCommonConstants.networkTimeout) } - + /// Given: Analytics plugin /// When: An analytics event is recorded and flushed after the plugin is enabled /// Then: Flush Hub event is received @@ -168,7 +178,7 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { } } networkMonitor.start(queue: DispatchQueue(label: "AWSPinpointAnalyticsPluginIntergrationTests.NetworkMonitor")) - + let flushEventsInvoked = expectation(description: "Flush events invoked") _ = Amplify.Hub.listen(to: .analytics, isIncluded: nil) { payload in if payload.eventName == HubPayload.EventName.Analytics.flushEvents { @@ -181,29 +191,33 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { flushEventsInvoked.fulfill() } } - + Amplify.Analytics.disable() Amplify.Analytics.enable() - let globalProperties = ["globalPropertyStringKey": "eventProperyStringValue", - "globalPropertyIntKey": 123, - "globalPropertyDoubleKey": 12.34, - "globalPropertyBoolKey": true] as [String: AnalyticsPropertyValue] + let globalProperties = [ + "globalPropertyStringKey": "eventProperyStringValue", + "globalPropertyIntKey": 123, + "globalPropertyDoubleKey": 12.34, + "globalPropertyBoolKey": true + ] as [String: AnalyticsPropertyValue] Amplify.Analytics.registerGlobalProperties(globalProperties) - let properties = ["eventPropertyStringKey": "eventProperyStringValue", - "eventPropertyIntKey": 123, - "eventPropertyDoubleKey": 12.34, - "eventPropertyBoolKey": true] as [String: AnalyticsPropertyValue] + let properties = [ + "eventPropertyStringKey": "eventProperyStringValue", + "eventPropertyIntKey": 123, + "eventPropertyDoubleKey": 12.34, + "eventPropertyBoolKey": true + ] as [String: AnalyticsPropertyValue] let event = BasicAnalyticsEvent(name: "eventName", properties: properties) Amplify.Analytics.record(event: event) - + await fulfillment(of: [onlineExpectation], timeout: TestCommonConstants.networkTimeout) Amplify.Analytics.flushEvents() await fulfillment(of: [flushEventsInvoked], timeout: TestCommonConstants.networkTimeout) } - + /// Given: Analytics plugin /// When: An analytics event is recorded and flushed after the plugin is disabled /// Then: Flush Hub event is not received @@ -216,7 +230,7 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { } } networkMonitor.start(queue: DispatchQueue(label: "AWSPinpointAnalyticsPluginIntergrationTests.NetworkMonitor")) - + let flushEventsInvoked = expectation(description: "Flush events invoked") _ = Amplify.Hub.listen(to: .analytics, isIncluded: nil) { payload in if payload.eventName == HubPayload.EventName.Analytics.flushEvents { @@ -224,27 +238,31 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { } } flushEventsInvoked.isInverted = true - + Amplify.Analytics.disable() - - let globalProperties = ["globalPropertyStringKey": "eventProperyStringValue", - "globalPropertyIntKey": 123, - "globalPropertyDoubleKey": 12.34, - "globalPropertyBoolKey": true] as [String: AnalyticsPropertyValue] + + let globalProperties = [ + "globalPropertyStringKey": "eventProperyStringValue", + "globalPropertyIntKey": 123, + "globalPropertyDoubleKey": 12.34, + "globalPropertyBoolKey": true + ] as [String: AnalyticsPropertyValue] Amplify.Analytics.registerGlobalProperties(globalProperties) - let properties = ["eventPropertyStringKey": "eventProperyStringValue", - "eventPropertyIntKey": 123, - "eventPropertyDoubleKey": 12.34, - "eventPropertyBoolKey": true] as [String: AnalyticsPropertyValue] + let properties = [ + "eventPropertyStringKey": "eventProperyStringValue", + "eventPropertyIntKey": 123, + "eventPropertyDoubleKey": 12.34, + "eventPropertyBoolKey": true + ] as [String: AnalyticsPropertyValue] let event = BasicAnalyticsEvent(name: "eventName", properties: properties) Amplify.Analytics.record(event: event) - + await fulfillment(of: [onlineExpectation], timeout: TestCommonConstants.networkTimeout) Amplify.Analytics.flushEvents() await fulfillment(of: [flushEventsInvoked], timeout: TestCommonConstants.networkTimeout) } - + /// Given: Analytics plugin /// When: An analytics event is recorded and flushed with global properties registered /// Then: Flush Hub event is received with global properties @@ -258,7 +276,7 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { } } networkMonitor.start(queue: DispatchQueue(label: "AWSPinpointAnalyticsPluginIntergrationTests.NetworkMonitor")) - + let flushEventsInvoked = expectation(description: "Flush events invoked") _ = Amplify.Hub.listen(to: .analytics, isIncluded: nil) { payload in if payload.eventName == HubPayload.EventName.Analytics.flushEvents { @@ -280,19 +298,23 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { flushEventsInvoked.fulfill() } } - - let globalProperties = ["globalPropertyStringKey": "GlobalProperyStringValue", - "globalPropertyIntKey": 321, - "globalPropertyDoubleKey": 43.21, - "globalPropertyBoolKey": true] as [String: AnalyticsPropertyValue] + + let globalProperties = [ + "globalPropertyStringKey": "GlobalProperyStringValue", + "globalPropertyIntKey": 321, + "globalPropertyDoubleKey": 43.21, + "globalPropertyBoolKey": true + ] as [String: AnalyticsPropertyValue] Amplify.Analytics.registerGlobalProperties(globalProperties) - let properties = ["eventPropertyStringKey": "eventProperyStringValue", - "eventPropertyIntKey": 123, - "eventPropertyDoubleKey": 12.34, - "eventPropertyBoolKey": true] as [String: AnalyticsPropertyValue] + let properties = [ + "eventPropertyStringKey": "eventProperyStringValue", + "eventPropertyIntKey": 123, + "eventPropertyDoubleKey": 12.34, + "eventPropertyBoolKey": true + ] as [String: AnalyticsPropertyValue] let event = BasicAnalyticsEvent(name: "eventName", properties: properties) Amplify.Analytics.record(event: event) - + await fulfillment(of: [onlineExpectation], timeout: TestCommonConstants.networkTimeout) Amplify.Analytics.flushEvents() @@ -312,7 +334,7 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { } } networkMonitor.start(queue: DispatchQueue(label: "AWSPinpointAnalyticsPluginIntergrationTests.NetworkMonitor")) - + let flushEventsInvoked = expectation(description: "Flush events invoked") _ = Amplify.Hub.listen(to: .analytics, isIncluded: nil) { payload in if payload.eventName == HubPayload.EventName.Analytics.flushEvents { @@ -334,20 +356,24 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { flushEventsInvoked.fulfill() } } - - let globalProperties = ["globalPropertyStringKey": "GlobalProperyStringValue", - "globalPropertyIntKey": 321, - "globalPropertyDoubleKey": 43.21, - "globalPropertyBoolKey": true] as [String: AnalyticsPropertyValue] + + let globalProperties = [ + "globalPropertyStringKey": "GlobalProperyStringValue", + "globalPropertyIntKey": 321, + "globalPropertyDoubleKey": 43.21, + "globalPropertyBoolKey": true + ] as [String: AnalyticsPropertyValue] Amplify.Analytics.registerGlobalProperties(globalProperties) Amplify.Analytics.unregisterGlobalProperties() - let properties = ["eventPropertyStringKey": "eventProperyStringValue", - "eventPropertyIntKey": 123, - "eventPropertyDoubleKey": 12.34, - "eventPropertyBoolKey": true] as [String: AnalyticsPropertyValue] + let properties = [ + "eventPropertyStringKey": "eventProperyStringValue", + "eventPropertyIntKey": 123, + "eventPropertyDoubleKey": 12.34, + "eventPropertyBoolKey": true + ] as [String: AnalyticsPropertyValue] let event = BasicAnalyticsEvent(name: "eventName", properties: properties) Amplify.Analytics.record(event: event) - + await fulfillment(of: [onlineExpectation], timeout: TestCommonConstants.networkTimeout) Amplify.Analytics.flushEvents() @@ -363,8 +389,8 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { } let awsPinpoint = pinpointAnalyticsPlugin.getEscapeHatch() XCTAssertNotNil(awsPinpoint) - } - + } + private func plugin() -> AWSPinpointAnalyticsPlugin { guard let plugin = try? Amplify.Analytics.getPlugin(for: "awsPinpointAnalyticsPlugin"), let analyticsPlugin = plugin as? AWSPinpointAnalyticsPlugin else { diff --git a/AmplifyPlugins/Analytics/Tests/AnalyticsHostApp/AnalyticsStressTests/AnalyticsStressTests.swift b/AmplifyPlugins/Analytics/Tests/AnalyticsHostApp/AnalyticsStressTests/AnalyticsStressTests.swift index 308dcfd1fb..736a2117b9 100644 --- a/AmplifyPlugins/Analytics/Tests/AnalyticsHostApp/AnalyticsStressTests/AnalyticsStressTests.swift +++ b/AmplifyPlugins/Analytics/Tests/AnalyticsHostApp/AnalyticsStressTests/AnalyticsStressTests.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPinpoint +import XCTest -@testable import Amplify -@testable import AWSPinpointAnalyticsPlugin import AWSCognitoAuthPlugin import Network +@testable import Amplify +@testable import AWSPinpointAnalyticsPlugin final class AnalyticsStressTests: XCTestCase { static let amplifyConfiguration = "testconfiguration/AWSAmplifyStressTests-amplifyconfiguration" static let analyticsPluginKey = "awsPinpointAnalyticsPlugin" let concurrencyLimit = 50 - + override func setUp() { do { let config = try TestConfigHelper.retrieveAmplifyConfiguration(forResource: Self.amplifyConfiguration) @@ -35,7 +35,7 @@ final class AnalyticsStressTests: XCTestCase { } // MARK: - Stress Tests - + /// - Given: Analytics plugin configured with valid configuration /// - When: 50 different events with 5 attributes are recorded simultaneously /// - Then: Operations are successful @@ -48,17 +48,19 @@ final class AnalyticsStressTests: XCTestCase { } } networkMonitor.start(queue: DispatchQueue(label: "AWSPinpointAnalyticsPluginIntergrationTests.NetworkMonitor")) - + await fulfillment(of: [onlineExpectation], timeout: TestCommonConstants.networkTimeout) - + let recordExpectation = expectation(description: "Records are successfully recorded") recordExpectation.expectedFulfillmentCount = concurrencyLimit - for eventNumber in 0...concurrencyLimit { - let properties = ["eventPropertyStringKey1": "eventProperyStringValue1", - "eventPropertyStringKey2": "eventProperyStringValue2", - "eventPropertyStringKey3": "eventProperyStringValue3", - "eventPropertyStringKey4": "eventProperyStringValue4", - "eventPropertyStringKey5": "eventProperyStringValue5"] as [String: AnalyticsPropertyValue] + for eventNumber in 0 ... concurrencyLimit { + let properties = [ + "eventPropertyStringKey1": "eventProperyStringValue1", + "eventPropertyStringKey2": "eventProperyStringValue2", + "eventPropertyStringKey3": "eventProperyStringValue3", + "eventPropertyStringKey4": "eventProperyStringValue4", + "eventPropertyStringKey5": "eventProperyStringValue5" + ] as [String: AnalyticsPropertyValue] let event = BasicAnalyticsEvent(name: "eventName" + String(eventNumber), properties: properties) Amplify.Analytics.record(event: event) recordExpectation.fulfill() @@ -66,7 +68,7 @@ final class AnalyticsStressTests: XCTestCase { await fulfillment(of: [recordExpectation], timeout: TestCommonConstants.networkTimeout) } - + /// - Given: Analytics plugin configured with valid configuration /// - When: 50 different events with 20 attributes are recorded simultaneously /// - Then: Operations are successful @@ -79,34 +81,36 @@ final class AnalyticsStressTests: XCTestCase { } } networkMonitor.start(queue: DispatchQueue(label: "AWSPinpointAnalyticsPluginIntergrationTests.NetworkMonitor")) - + await fulfillment(of: [onlineExpectation], timeout: TestCommonConstants.networkTimeout) - + let recordExpectation = expectation(description: "Records are successfully recorded") recordExpectation.expectedFulfillmentCount = concurrencyLimit - for eventNumber in 0...concurrencyLimit { + for eventNumber in 0 ... concurrencyLimit { Task { - let properties = ["eventPropertyStringKey1": "eventProperyStringValue1", - "eventPropertyStringKey2": "eventProperyStringValue2", - "eventPropertyStringKey3": "eventProperyStringValue3", - "eventPropertyStringKey4": "eventProperyStringValue4", - "eventPropertyStringKey5": "eventProperyStringValue5", - "eventPropertyIntKey1": 123, - "eventPropertyIntKey2": 123, - "eventPropertyIntKey3": 123, - "eventPropertyIntKey4": 123, - "eventPropertyIntKey5": 123, - "eventPropertyDoubleKey1": 12.34, - "eventPropertyDoubleKey2": 12.34, - "eventPropertyDoubleKey3": 12.34, - "eventPropertyDoubleKey4": 12.34, - "eventPropertyDoubleKey5": 12.34, - "eventPropertyBoolKey1": true, - "eventPropertyBoolKey2": true, - "eventPropertyBoolKey3": true, - "eventPropertyBoolKey4": true, - "eventPropertyBoolKey5": true] as [String: AnalyticsPropertyValue] + let properties = [ + "eventPropertyStringKey1": "eventProperyStringValue1", + "eventPropertyStringKey2": "eventProperyStringValue2", + "eventPropertyStringKey3": "eventProperyStringValue3", + "eventPropertyStringKey4": "eventProperyStringValue4", + "eventPropertyStringKey5": "eventProperyStringValue5", + "eventPropertyIntKey1": 123, + "eventPropertyIntKey2": 123, + "eventPropertyIntKey3": 123, + "eventPropertyIntKey4": 123, + "eventPropertyIntKey5": 123, + "eventPropertyDoubleKey1": 12.34, + "eventPropertyDoubleKey2": 12.34, + "eventPropertyDoubleKey3": 12.34, + "eventPropertyDoubleKey4": 12.34, + "eventPropertyDoubleKey5": 12.34, + "eventPropertyBoolKey1": true, + "eventPropertyBoolKey2": true, + "eventPropertyBoolKey3": true, + "eventPropertyBoolKey4": true, + "eventPropertyBoolKey5": true + ] as [String: AnalyticsPropertyValue] let event = BasicAnalyticsEvent(name: "eventName" + String(eventNumber), properties: properties) Amplify.Analytics.record(event: event) recordExpectation.fulfill() diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFAppInfo.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFAppInfo.swift index cdf1f9b8d0..f68d08e7c3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFAppInfo.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFAppInfo.swift @@ -14,7 +14,7 @@ struct ASFAppInfo: ASFAppInfoBehavior { } var targetSDK: String { - var targetSDK: String = "" + var targetSDK = "" #if os(iOS) || os(watchOS) || os(tvOS) targetSDK = "\(__IPHONE_OS_VERSION_MIN_REQUIRED)" #elseif os(macOS) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFDeviceInfo.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFDeviceInfo.swift index ddb5d61259..e48933a824 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFDeviceInfo.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFDeviceInfo.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation @MainActor struct ASFDeviceInfo: ASFDeviceBehavior { @@ -28,9 +28,13 @@ struct ASFDeviceInfo: ASFDeviceBehavior { var type: String { var systemInfo = utsname() uname(&systemInfo) - return String(bytes: Data(bytes: &systemInfo.machine, - count: Int(_SYS_NAMELEN)), - encoding: .utf8) ?? DeviceInfo.current.hostName + return String( + bytes: Data( + bytes: &systemInfo.machine, + count: Int(_SYS_NAMELEN) + ), + encoding: .utf8 + ) ?? DeviceInfo.current.hostName } var platform: String { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/AdvancedSecurityBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/AdvancedSecurityBehavior.swift index c5c688972b..c499d5b35c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/AdvancedSecurityBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/AdvancedSecurityBehavior.swift @@ -9,10 +9,12 @@ import Foundation protocol AdvancedSecurityBehavior { - func userContextData(for username: String, - deviceInfo: ASFDeviceBehavior, - appInfo: ASFAppInfoBehavior, - configuration: UserPoolConfigurationData) throws -> String + func userContextData( + for username: String, + deviceInfo: ASFDeviceBehavior, + appInfo: ASFAppInfoBehavior, + configuration: UserPoolConfigurationData + ) throws -> String } protocol ASFDeviceBehavior: Sendable { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF+KeyChain.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF+KeyChain.swift index 8949aee102..89bd152bd8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF+KeyChain.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF+KeyChain.swift @@ -11,7 +11,8 @@ extension CognitoUserPoolASF { static func asfDeviceID( for username: String, - credentialStoreClient: CredentialStoreStateBehavior) async throws -> String { + credentialStoreClient: CredentialStoreStateBehavior + ) async throws -> String { let deviceMetaDataType = CredentialStoreDataType.deviceMetadata(username: username) let data = try? await credentialStoreClient.fetchData(type: deviceMetaDataType) if case .deviceMetadata(let metadata, _) = data, @@ -29,10 +30,12 @@ extension CognitoUserPoolASF { return uuid } - static func encodedContext(username: String, - asfDeviceId: String, - asfClient: AdvancedSecurityBehavior, - userPoolConfiguration: UserPoolConfigurationData) async -> String? { + static func encodedContext( + username: String, + asfDeviceId: String, + asfClient: AdvancedSecurityBehavior, + userPoolConfiguration: UserPoolConfigurationData + ) async -> String? { let deviceInfo: ASFDeviceBehavior = await ASFDeviceInfo(id: asfDeviceId) let appInfo: ASFAppInfoBehavior = ASFAppInfo() @@ -41,7 +44,8 @@ extension CognitoUserPoolASF { for: username, deviceInfo: deviceInfo, appInfo: appInfo, - configuration: userPoolConfiguration) + configuration: userPoolConfiguration + ) } catch { // Ignore the error and add nil as context data return nil diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift index 4d9568f270..a6cc64bc7e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CryptoKit +import Foundation struct CognitoUserPoolASF: AdvancedSecurityBehavior { @@ -27,23 +27,31 @@ struct CognitoUserPoolASF: AdvancedSecurityBehavior { static let phoneTypeKey = "PhoneType" static let asfVersion = "IOS20171114" - func userContextData(for username: String = "unknown", - deviceInfo: ASFDeviceBehavior, - appInfo: ASFAppInfoBehavior, - configuration: UserPoolConfigurationData) throws -> String { + func userContextData( + for username: String = "unknown", + deviceInfo: ASFDeviceBehavior, + appInfo: ASFAppInfoBehavior, + configuration: UserPoolConfigurationData + ) throws -> String { let contextData = prepareUserContextData(deviceInfo: deviceInfo, appInfo: appInfo) - let payload = try prepareJsonPayload(username: username, - contextData: contextData, - userPoolId: configuration.poolId) - let signature = try calculateSecretHash(contextJson: payload, - clientId: configuration.clientId) + let payload = try prepareJsonPayload( + username: username, + contextData: contextData, + userPoolId: configuration.poolId + ) + let signature = try calculateSecretHash( + contextJson: payload, + clientId: configuration.clientId + ) let result = try prepareJsonResult(payload: payload, signature: signature) return result } - func prepareUserContextData(deviceInfo: ASFDeviceBehavior, - appInfo: ASFAppInfoBehavior) -> [String: String] { + func prepareUserContextData( + deviceInfo: ASFDeviceBehavior, + appInfo: ASFAppInfoBehavior + ) -> [String: String] { var build = "release" #if DEBUG build = "debug" @@ -73,10 +81,12 @@ struct CognitoUserPoolASF: AdvancedSecurityBehavior { return contextData } - func prepareJsonPayload(username: String, - contextData: [String: String], - userPoolId: String) throws -> String { - let timestamp = String(format: "%lli", floor(Date().timeIntervalSince1970 * 1000)) + func prepareJsonPayload( + username: String, + contextData: [String: String], + userPoolId: String + ) throws -> String { + let timestamp = String(format: "%lli", floor(Date().timeIntervalSince1970 * 1_000)) let payload = [ "contextData": contextData, "username": username, @@ -92,8 +102,8 @@ struct CognitoUserPoolASF: AdvancedSecurityBehavior { func timeZoneOffet(seconds: Int = TimeZone.current.secondsFromGMT()) -> String { - let hours = seconds/3600 - let minutes = abs(seconds/60) % 60 + let hours = seconds / 3_600 + let minutes = abs(seconds / 60) % 60 return String(format: "%+.2d:%.2d", hours, minutes) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+AppSyncSigner.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+AppSyncSigner.swift index 51f3e66db4..931e56a85e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+AppSyncSigner.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+AppSyncSigner.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify // Amplify.Auth -import AWSPluginsCore // AuthAWSCredentialsProvider import AwsCommonRuntimeKit // CommonRuntimeKit.initialize() +import AWSPluginsCore // AuthAWSCredentialsProvider import AWSSDKHTTPAuth // AWSSigV4Signer +import Foundation import Smithy // URIQueryItem import SmithyHTTPAPI import SmithyHTTPAuth @@ -29,19 +29,22 @@ extension AWSCognitoAuthPlugin { /// - Returns: A closure that takes in a requestand returns a signed request. public static func createAppSyncSigner(region: String) -> ((URLRequest) async throws -> URLRequest) { return { request in - try await signAppSyncRequest(request, - region: region) + try await signAppSyncRequest( + request, + + region: region + ) } } - private static var signer = { - return AWSSigV4Signer() - }() + private static var signer = AWSSigV4Signer() - static func signAppSyncRequest(_ urlRequest: URLRequest, - region: Swift.String, - signingName: Swift.String = "appsync", - date: Date = Date()) async throws -> URLRequest { + static func signAppSyncRequest( + _ urlRequest: URLRequest, + region: Swift.String, + signingName: Swift.String = "appsync", + date: Date = Date() + ) async throws -> URLRequest { CommonRuntimeKit.initialize() // Convert URLRequest to SDK's HTTPRequest @@ -62,20 +65,24 @@ extension AWSCognitoAuthPlugin { } // Prepare signing - let flags = SigningFlags(useDoubleURIEncode: true, - shouldNormalizeURIPath: true, - omitSessionToken: false) + let flags = SigningFlags( + useDoubleURIEncode: true, + shouldNormalizeURIPath: true, + omitSessionToken: false + ) let signedBodyHeader: AWSSignedBodyHeader = .none let signedBodyValue: AWSSignedBodyValue = .empty - let signingConfig = AWSSigningConfig(credentials: credentials, - signedBodyHeader: signedBodyHeader, - signedBodyValue: signedBodyValue, - flags: flags, - date: date, - service: signingName, - region: region, - signatureType: .requestHeaders, - signingAlgorithm: .sigv4) + let signingConfig = AWSSigningConfig( + credentials: credentials, + signedBodyHeader: signedBodyHeader, + signedBodyValue: signedBodyValue, + flags: flags, + date: date, + service: signingName, + region: region, + signatureType: .requestHeaders, + signingAlgorithm: .sigv4 + ) // Sign request guard let httpRequest = await signer.sigV4SignedRequest( diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift index 482d266575..324f76a9f6 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift @@ -7,15 +7,15 @@ import Foundation @_spi(InternalAmplifyConfiguration) import Amplify +import AWSClientRuntime import AWSCognitoIdentity import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSClientRuntime @_spi(PluginHTTPClientEngine) import InternalAmplifyCredentials @_spi(InternalHttpEngineProxy) import AWSPluginsCore -import SmithyRetriesAPI import SmithyRetries +import SmithyRetriesAPI extension AWSCognitoAuthPlugin { @@ -35,13 +35,16 @@ extension AWSCognitoAuthPlugin { } else { throw PluginError.pluginConfigurationError( AuthPluginErrorConstants.decodeConfigurationError.errorDescription, - AuthPluginErrorConstants.decodeConfigurationError.recoverySuggestion) + AuthPluginErrorConstants.decodeConfigurationError.recoverySuggestion + ) } let credentialStoreResolver = CredentialStoreState.Resolver().eraseToAnyResolver() let credentialEnvironment = credentialStoreEnvironment(authConfiguration: authConfiguration) - let credentialStoreMachine = StateMachine(resolver: credentialStoreResolver, - environment: credentialEnvironment) + let credentialStoreMachine = StateMachine( + resolver: credentialStoreResolver, + environment: credentialEnvironment + ) let credentialsClient = CredentialStoreOperationClient( credentialStoreStateMachine: credentialStoreMachine) @@ -56,23 +59,28 @@ extension AWSCognitoAuthPlugin { let hubEventHandler = AuthHubEventHandler() let analyticsHandler = try UserPoolAnalytics( authConfiguration.getUserPoolConfiguration(), - credentialStoreEnvironment: credentialEnvironment.credentialStoreEnvironment) - - configure(authConfiguration: authConfiguration, - authEnvironment: authEnvironment, - authStateMachine: authStateMachine, - credentialStoreStateMachine: credentialStoreMachine, - hubEventHandler: hubEventHandler, - analyticsHandler: analyticsHandler) + credentialStoreEnvironment: credentialEnvironment.credentialStoreEnvironment + ) + + configure( + authConfiguration: authConfiguration, + authEnvironment: authEnvironment, + authStateMachine: authStateMachine, + credentialStoreStateMachine: credentialStoreMachine, + hubEventHandler: hubEventHandler, + analyticsHandler: analyticsHandler + ) } - func configure(authConfiguration: AuthConfiguration, - authEnvironment: AuthEnvironment, - authStateMachine: AuthStateMachine, - credentialStoreStateMachine: CredentialStoreStateMachine, - hubEventHandler: AuthHubEventBehavior, - analyticsHandler: UserPoolAnalyticsBehavior, - queue: OperationQueue = OperationQueue()) { + func configure( + authConfiguration: AuthConfiguration, + authEnvironment: AuthEnvironment, + authStateMachine: AuthStateMachine, + credentialStoreStateMachine: CredentialStoreStateMachine, + hubEventHandler: AuthHubEventBehavior, + analyticsHandler: UserPoolAnalyticsBehavior, + queue: OperationQueue = OperationQueue() + ) { self.authConfiguration = authConfiguration self.queue = queue @@ -80,11 +88,11 @@ extension AWSCognitoAuthPlugin { self.authEnvironment = authEnvironment self.authStateMachine = authStateMachine self.credentialStoreStateMachine = credentialStoreStateMachine - self.internalConfigure() - self.listenToStateMachineChanges() + internalConfigure() + listenToStateMachineChanges() self.hubEventHandler = hubEventHandler self.analyticsHandler = analyticsHandler - self.taskQueue = TaskQueue() + taskQueue = TaskQueue() } // MARK: - Configure Helpers @@ -97,7 +105,7 @@ extension AWSCognitoAuthPlugin { endpointResolver: userPoolConfig.endpoint?.resolver ) - if var httpClientEngineProxy = httpClientEngineProxy { + if var httpClientEngineProxy { httpClientEngineProxy.target = baseClientEngine(for: configuration) configuration.httpClientEngine = UserAgentSettingClientEngine( target: httpClientEngineProxy @@ -210,7 +218,8 @@ extension AWSCognitoAuthPlugin { authenticationEnvironment: authenticationEnvironment, authorizationEnvironment: nil, credentialsClient: credentialsClient, - logger: log) + logger: log + ) case .identityPools(let identityPoolConfigurationData): let authorizationEnvironment = authorizationEnvironment( @@ -222,10 +231,13 @@ extension AWSCognitoAuthPlugin { authenticationEnvironment: nil, authorizationEnvironment: authorizationEnvironment, credentialsClient: credentialsClient, - logger: log) + logger: log + ) - case .userPoolsAndIdentityPools(let userPoolConfigurationData, - let identityPoolConfigurationData): + case .userPoolsAndIdentityPools( + let userPoolConfigurationData, + let identityPoolConfigurationData + ): let authenticationEnvironment = authenticationEnvironment( userPoolConfigData: userPoolConfigurationData) let authorizationEnvironment = authorizationEnvironment( @@ -237,39 +249,49 @@ extension AWSCognitoAuthPlugin { authenticationEnvironment: authenticationEnvironment, authorizationEnvironment: authorizationEnvironment, credentialsClient: credentialsClient, - logger: log) + logger: log + ) } } private func authenticationEnvironment(userPoolConfigData: UserPoolConfigurationData) -> AuthenticationEnvironment { - let srpAuthEnvironment = BasicSRPAuthEnvironment(userPoolConfiguration: userPoolConfigData, - cognitoUserPoolFactory: makeUserPool) + let srpAuthEnvironment = BasicSRPAuthEnvironment( + userPoolConfiguration: userPoolConfigData, + cognitoUserPoolFactory: makeUserPool + ) let srpSignInEnvironment = BasicSRPSignInEnvironment(srpAuthEnvironment: srpAuthEnvironment) let userPoolEnvironment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfigData, cognitoUserPoolFactory: makeUserPool, cognitoUserPoolASFFactory: makeCognitoASF, - cognitoUserPoolAnalyticsHandlerFactory: makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: makeUserPoolAnalytics + ) let hostedUIEnvironment = hostedUIEnvironment(userPoolConfigData) - return BasicAuthenticationEnvironment(srpSignInEnvironment: srpSignInEnvironment, - userPoolEnvironment: userPoolEnvironment, - hostedUIEnvironment: hostedUIEnvironment) + return BasicAuthenticationEnvironment( + srpSignInEnvironment: srpSignInEnvironment, + userPoolEnvironment: userPoolEnvironment, + hostedUIEnvironment: hostedUIEnvironment + ) } private func hostedUIEnvironment(_ configuration: UserPoolConfigurationData) -> HostedUIEnvironment? { guard let hostedUIConfig = configuration.hostedUIConfig else { return nil } - return BasicHostedUIEnvironment(configuration: hostedUIConfig, - hostedUISessionFactory: makeHostedUISession, - urlSessionFactory: makeURLSession, - randomStringFactory: makeRandomString) + return BasicHostedUIEnvironment( + configuration: hostedUIConfig, + hostedUISessionFactory: makeHostedUISession, + urlSessionFactory: makeURLSession, + randomStringFactory: makeRandomString + ) } private func authorizationEnvironment(identityPoolConfigData: IdentityPoolConfigurationData) -> AuthorizationEnvironment { - BasicAuthorizationEnvironment(identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: makeIdentityClient) + BasicAuthorizationEnvironment( + identityPoolConfiguration: identityPoolConfigData, + cognitoIdentityFactory: makeIdentityClient + ) } private func credentialStoreEnvironment(authConfiguration: AuthConfiguration) -> CredentialEnvironment { @@ -287,8 +309,9 @@ extension AWSCognitoAuthPlugin { let operation = AuthConfigureOperation( request: request, authStateMachine: authStateMachine, - credentialStoreStateMachine: credentialStoreStateMachine) - self.queue.addOperation(operation) + credentialStoreStateMachine: credentialStoreStateMachine + ) + queue.addOperation(operation) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+EscapeHatch.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+EscapeHatch.swift index 37bbb02b0c..4876c75bde 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+EscapeHatch.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+EscapeHatch.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoIdentity import AWSCognitoIdentityProvider +import Foundation public extension AWSCognitoAuthPlugin { @@ -37,13 +37,15 @@ public extension AWSCognitoAuthPlugin { let identityPoolClient = identityPoolClient as? CognitoIdentityClient { - service = .userPoolAndIdentityPool(userPoolClient, - identityPoolClient) + service = .userPoolAndIdentityPool( + userPoolClient, + identityPoolClient + ) } case .none: service = nil } - guard let service = service else { + guard let service else { fatalError(""" Could not find any escape hatch, invoke Amplify configuration before accessing the escape hatch. diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginExtension.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginExtension.swift index e617062e5c..8d7a214b41 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginExtension.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginExtension.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -@_spi(InternalAmplifyPluginExtension) import InternalAmplifyCredentials -import Foundation import ClientRuntime +import Foundation +@_spi(InternalAmplifyPluginExtension) import InternalAmplifyCredentials -extension AWSCognitoAuthPlugin { +public extension AWSCognitoAuthPlugin { @_spi(InternalAmplifyPluginExtension) - public func add(pluginExtension: AWSPluginExtension) { + func add(pluginExtension: AWSPluginExtension) { if let customHttpEngine = pluginExtension as? HttpClientEngineProxy { - self.httpClientEngineProxy = customHttpEngine + httpClientEngineProxy = customHttpEngine } } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginSpecificAPI.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginSpecificAPI.swift index 6155f93d27..cc31fd7e2c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginSpecificAPI.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginSpecificAPI.swift @@ -36,7 +36,8 @@ public extension AWSCognitoAuthPlugin { func fetchMFAPreference() async throws -> UserMFAPreference { let task = FetchMFAPreferenceTask( authStateMachine: authStateMachine, - userPoolFactory: authEnvironment.cognitoUserPoolFactory) + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) return try await task.value } @@ -48,7 +49,8 @@ public extension AWSCognitoAuthPlugin { smsPreference: sms, totpPreference: totp, authStateMachine: authStateMachine, - userPoolFactory: authEnvironment.cognitoUserPoolFactory) + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) return try await task.value } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin.swift index f32209ba9c..858b848202 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation public final class AWSCognitoAuthPlugin: AWSCognitoAuthPluginBehavior { @@ -36,7 +36,7 @@ public final class AWSCognitoAuthPlugin: AWSCognitoAuthPluginBehavior { let networkPreferences: AWSCognitoNetworkPreferences? @_spi(InternalAmplifyConfiguration) - internal(set) public var jsonConfiguration: JSONValue? + public internal(set) var jsonConfiguration: JSONValue? /// The unique key of the plugin within the auth category. public var key: PluginKey { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPluginBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPluginBehavior.swift index ffc07ce349..be382f8a52 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPluginBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPluginBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AWSCognitoAuthPluginBehavior: AuthCategoryPlugin { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Authentication/SignInComplete.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Authentication/SignInComplete.swift index e56295b478..2e4bc9508e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Authentication/SignInComplete.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Authentication/SignInComplete.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify import Foundation diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthConfiguration.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthConfiguration.swift index 4d1388d7ef..e2264e3c29 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthConfiguration.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthConfiguration.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation struct InitializeAuthConfiguration: Action { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthenticationConfiguration.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthenticationConfiguration.swift index 4b5574ddc6..a5f47425f5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthenticationConfiguration.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthenticationConfiguration.swift @@ -14,8 +14,10 @@ struct InitializeAuthenticationConfiguration: Action { let configuration: AuthConfiguration let storedCredentials: AmplifyCredentials - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) let event = AuthenticationEvent(eventType: .configure(configuration, storedCredentials)) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthorizationConfiguration.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthorizationConfiguration.swift index 4fd3208bc9..20aacc9ac6 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthorizationConfiguration.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthorizationConfiguration.swift @@ -13,16 +13,17 @@ struct InitializeAuthorizationConfiguration: Action { let storedCredentials: AmplifyCredentials - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { // ATM this is a no-op action logVerbose("\(#fileID) Starting execution", environment: environment) - var event: AuthorizationEvent - switch storedCredentials { + var event = switch storedCredentials { case .noCredentials: - event = AuthorizationEvent(eventType: .configure) + AuthorizationEvent(eventType: .configure) default: - event = AuthorizationEvent(eventType: .cachedCredentialsAvailable(storedCredentials)) + AuthorizationEvent(eventType: .cachedCredentialsAvailable(storedCredentials)) } logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/ValidateCredentialsAndConfiguration.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/ValidateCredentialsAndConfiguration.swift index 9d4f8085df..4b1af4c2ae 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/ValidateCredentialsAndConfiguration.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/ValidateCredentialsAndConfiguration.swift @@ -21,11 +21,15 @@ struct ValidateCredentialsAndConfiguration: Action { var event: StateMachineEvent switch authConfiguration { case .identityPools: - event = AuthEvent(eventType: .configureAuthorization(authConfiguration, - cachedCredentials)) + event = AuthEvent(eventType: .configureAuthorization( + authConfiguration, + cachedCredentials + )) default: - event = AuthEvent(eventType: .configureAuthentication(authConfiguration, - cachedCredentials)) + event = AuthEvent(eventType: .configureAuthentication( + authConfiguration, + cachedCredentials + )) } logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/ClearCredentialStore.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/ClearCredentialStore.swift index 3be32348bf..9890df37af 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/ClearCredentialStore.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/ClearCredentialStore.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation struct ClearCredentialStore: Action { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/LoadCredentialStore.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/LoadCredentialStore.swift index 40fad5f103..cac9300138 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/LoadCredentialStore.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/LoadCredentialStore.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation struct LoadCredentialStore: Action { @@ -27,8 +27,10 @@ struct LoadCredentialStore: Action { return } - logVerbose("\(#fileID) Retreiving credential \(credentialStoreType)", - environment: environment) + logVerbose( + "\(#fileID) Retreiving credential \(credentialStoreType)", + environment: environment + ) let credentialStoreEnvironment = credentialEnvironment.credentialStoreEnvironment let amplifyCredentialStore = credentialStoreEnvironment.amplifyCredentialStoreFactory() diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/MigrateLegacyCredentialStore.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/MigrateLegacyCredentialStore.swift index 6017f71215..311f8e22c5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/MigrateLegacyCredentialStore.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/MigrateLegacyCredentialStore.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation @_spi(KeychainStore) import AWSPluginsCore // swiftlint:disable identifier_name @@ -57,25 +57,34 @@ struct MigrateLegacyCredentialStore: Action { var identityId: String? var awsCredentials: AuthAWSCognitoCredentials? - migrateDeviceDetails(from: credentialStoreEnvironment, - with: authConfiguration) - let userPoolTokens = try? getUserPoolTokens(from: credentialStoreEnvironment, - with: authConfiguration) + migrateDeviceDetails( + from: credentialStoreEnvironment, + with: authConfiguration + ) + let userPoolTokens = try? getUserPoolTokens( + from: credentialStoreEnvironment, + with: authConfiguration + ) // IdentityId and AWSCredentials should exist together - if let (storedIdentityId, - storedAWSCredentials) = try? getIdentityIdAndAWSCredentials( - from: credentialStoreEnvironment, - with: authConfiguration) { + if let ( + storedIdentityId, + storedAWSCredentials + ) = try? getIdentityIdAndAWSCredentials( + from: credentialStoreEnvironment, + with: authConfiguration + ) { identityId = storedIdentityId awsCredentials = storedAWSCredentials } let loginsMap = getCachedLoginMaps(from: credentialStoreEnvironment) - let signInMethod = (try? getSignInMethod(from: credentialStoreEnvironment, - with: authConfiguration)) ?? .apiBased(.userSRP) + let signInMethod = (try? getSignInMethod( + from: credentialStoreEnvironment, + with: authConfiguration + )) ?? .apiBased(.userSRP) do { - if let identityId = identityId, - let awsCredentials = awsCredentials, + if let identityId, + let awsCredentials, userPoolTokens == nil { if !loginsMap.isEmpty, @@ -86,37 +95,42 @@ struct MigrateLegacyCredentialStore: Action { let credentials = AmplifyCredentials.identityPoolWithFederation( federatedToken: .init(token: providerToken, provider: provider), identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) try amplifyCredentialStore.saveCredential(credentials) } else { logVerbose("\(#fileID) Guest user", environment: environment) let credentials = AmplifyCredentials.identityPoolOnly( identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) try amplifyCredentialStore.saveCredential(credentials) } - } else if let identityId = identityId, - let awsCredentials = awsCredentials, - let userPoolTokens = userPoolTokens { + } else if let identityId, + let awsCredentials, + let userPoolTokens { logVerbose("\(#fileID) User pool with identity pool", environment: environment) let signedInData = SignedInData( signedInDate: Date.distantPast, signInMethod: signInMethod, - cognitoUserPoolTokens: userPoolTokens) + cognitoUserPoolTokens: userPoolTokens + ) let credentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: signedInData, identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) try amplifyCredentialStore.saveCredential(credentials) - } else if let userPoolTokens = userPoolTokens { + } else if let userPoolTokens { logVerbose("\(#fileID) Only user pool", environment: environment) let signedInData = SignedInData( signedInDate: Date.distantPast, signInMethod: signInMethod, - cognitoUserPoolTokens: userPoolTokens) + cognitoUserPoolTokens: userPoolTokens + ) let credentials = AmplifyCredentials.userPoolOnly(signedInData: signedInData) try amplifyCredentialStore.saveCredential(credentials) } @@ -139,7 +153,8 @@ struct MigrateLegacyCredentialStore: Action { private func migrateDeviceDetails( from credentialStoreEnvironment: CredentialStoreEnvironment, - with authConfiguration: AuthConfiguration) { + with authConfiguration: AuthConfiguration + ) { guard let bundleIdentifier = Bundle.main.bundleIdentifier, let userPoolConfig = authConfiguration.getUserPoolConfiguration() else { @@ -187,23 +202,26 @@ struct MigrateLegacyCredentialStore: Action { ) let amplifyCredentialStore = credentialStoreEnvironment.amplifyCredentialStoreFactory() - if let deviceId = deviceId, - let deviceSecret = deviceSecret, - let deviceGroup = deviceGroup { - let deviceMetaData = DeviceMetadata.metadata(.init(deviceKey: deviceId, - deviceGroupKey: deviceGroup, - deviceSecret: deviceSecret)) + if let deviceId, + let deviceSecret, + let deviceGroup { + let deviceMetaData = DeviceMetadata.metadata(.init( + deviceKey: deviceId, + deviceGroupKey: deviceGroup, + deviceSecret: deviceSecret + )) try? amplifyCredentialStore.saveDevice(deviceMetaData, for: currentUsername) } - if let asfDeviceId = asfDeviceId { + if let asfDeviceId { try? amplifyCredentialStore.saveASFDevice(asfDeviceId, for: currentUsername) } } private func getUserPoolTokens( from credentialStoreEnvironment: CredentialStoreEnvironment, - with authConfiguration: AuthConfiguration) throws -> AWSCognitoUserPoolTokens { + with authConfiguration: AuthConfiguration + ) throws -> AWSCognitoUserPoolTokens { guard let bundleIdentifier = Bundle.main.bundleIdentifier, let userPoolConfig = authConfiguration.getUserPoolConfiguration() @@ -251,10 +269,12 @@ struct MigrateLegacyCredentialStore: Action { // If the token expiration can't be converted to a date, chose a date in the past let pastDate = Date.init(timeIntervalSince1970: 0) let tokenExpiration = dateFormatter().date(from: tokenExpirationString) ?? pastDate - return AWSCognitoUserPoolTokens(idToken: idToken, - accessToken: accessToken, - refreshToken: refreshToken, - expiration: tokenExpiration) + return AWSCognitoUserPoolTokens( + idToken: idToken, + accessToken: accessToken, + refreshToken: refreshToken, + expiration: tokenExpiration + ) } private func getCachedLoginMaps( @@ -276,7 +296,8 @@ struct MigrateLegacyCredentialStore: Action { private func getSignInMethod( from credentialStoreEnvironment: CredentialStoreEnvironment, - with authConfiguration: AuthConfiguration) throws -> SignInMethod { + with authConfiguration: AuthConfiguration + ) throws -> SignInMethod { let serviceKey = "\(String.init(describing: Bundle.main.bundleIdentifier)).AWSMobileClient" let legacyKeychainStore = credentialStoreEnvironment.legacyKeychainStoreFactory(serviceKey) @@ -287,32 +308,41 @@ struct MigrateLegacyCredentialStore: Action { case "hostedUI": let userPoolConfig = authConfiguration.getUserPoolConfiguration() let scopes = userPoolConfig?.hostedUIConfig?.oauth.scopes - let provider = HostedUIProviderInfo(authProvider: nil, - idpIdentifier: nil) - return .hostedUI(.init(scopes: scopes ?? [], - providerInfo: provider, - presentationAnchor: nil, - preferPrivateSession: false)) + let provider = HostedUIProviderInfo( + authProvider: nil, + idpIdentifier: nil + ) + return .hostedUI(.init( + scopes: scopes ?? [], + providerInfo: provider, + presentationAnchor: nil, + preferPrivateSession: false + )) default: return .apiBased(.userSRP) } } - private func userPoolNamespace(userPoolConfig: UserPoolConfigurationData, - for key: String) -> String { + private func userPoolNamespace( + userPoolConfig: UserPoolConfigurationData, + for key: String + ) -> String { return "\(userPoolConfig.clientId).\(key)" } - private func userPoolNamespace(withUser userName: String, - userPoolConfig: UserPoolConfigurationData, - for key: String) -> String { + private func userPoolNamespace( + withUser userName: String, + userPoolConfig: UserPoolConfigurationData, + for key: String + ) -> String { return "\(userPoolConfig.poolId).\(userName).\(key)" } private func getIdentityIdAndAWSCredentials( from credentialStoreEnvironment: CredentialStoreEnvironment, - with authConfiguration: AuthConfiguration) throws + with authConfiguration: AuthConfiguration + ) throws -> (identityId: String, awsCredentials: AuthAWSCognitoCredentials) { guard let bundleIdentifier = Bundle.main.bundleIdentifier, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/StoreCredentials.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/StoreCredentials.swift index 2b8f856743..dcc28465e3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/StoreCredentials.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/StoreCredentials.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation struct StoreCredentials: Action { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/DeleteUser.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/DeleteUser.swift index c51bc24770..87bdb58834 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/DeleteUser.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/DeleteUser.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct DeleteUser: Action { @@ -50,11 +50,12 @@ struct DeleteUser: Action { } catch let error as AuthErrorConvertible { event = DeleteUserEvent(eventType: .throwError(error.authError)) logVerbose("\(#fileID) Delete User failed \(error)", environment: environment) - } catch let error { + } catch { let authError = AuthError.service( "Delete user failed with service error", AmplifyErrorMessages.reportBugToAWS(), - error) + error + ) event = DeleteUserEvent(eventType: .throwError(authError)) logVerbose("\(#fileID) Delete user failed \(error)", environment: environment) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/InformUserDeletedAndSignedOut.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/InformUserDeletedAndSignedOut.swift index a604270478..2bb868a626 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/InformUserDeletedAndSignedOut.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/InformUserDeletedAndSignedOut.swift @@ -19,12 +19,11 @@ struct InformUserDeletedAndSignedOut: Action { logVerbose("\(#fileID) Starting execution", environment: environment) - let event: DeleteUserEvent - switch result { + let event = switch result { case .success(let signedOutData): - event = DeleteUserEvent(eventType: .userSignedOutAndDeleted(signedOutData)) + DeleteUserEvent(eventType: .userSignedOutAndDeleted(signedOutData)) case .failure(let error): - event = DeleteUserEvent(eventType: .throwError(error)) + DeleteUserEvent(eventType: .throwError(error)) } logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Federation/InitializeFederationToIdentityPool.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Federation/InitializeFederationToIdentityPool.swift index 1624c9083c..425d1d7c41 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Federation/InitializeFederationToIdentityPool.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Federation/InitializeFederationToIdentityPool.swift @@ -19,11 +19,12 @@ struct InitializeFederationToIdentityPool: Action { let authProviderLoginsMap = AuthProviderLoginsMap(federatedToken: federatedToken) let event: FetchAuthSessionEvent - if let developerProvidedIdentityId = developerProvidedIdentityId { + if let developerProvidedIdentityId { event = FetchAuthSessionEvent.init( eventType: .fetchAWSCredentials( developerProvidedIdentityId, - authProviderLoginsMap)) + authProviderLoginsMap + )) } else { event = FetchAuthSessionEvent.init( eventType: .fetchAuthenticatedIdentityID(authProviderLoginsMap)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/AWSCredentials/FetchAuthAWSCredentials.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/AWSCredentials/FetchAuthAWSCredentials.swift index 898806c1e4..d9927aed9d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/AWSCredentials/FetchAuthAWSCredentials.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/AWSCredentials/FetchAuthAWSCredentials.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import AWSCognitoIdentity -import Foundation import Amplify +import AWSCognitoIdentity import ClientRuntime +import Foundation struct FetchAuthAWSCredentials: Action { @@ -32,8 +32,10 @@ struct FetchAuthAWSCredentials: Action { return } - let getCredentialsInput = GetCredentialsForIdentityInput(identityId: identityID, - logins: loginsMap) + let getCredentialsInput = GetCredentialsForIdentityInput( + identityId: identityID, + logins: loginsMap + ) do { let response = try await client.getCredentialsForIdentity(input: getCredentialsInput) @@ -54,10 +56,12 @@ struct FetchAuthAWSCredentials: Action { logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) return } - let awsCognitoCredentials = AuthAWSCognitoCredentials(accessKeyId: accessKey, - secretAccessKey: secretKey, - sessionToken: sessionKey, - expiration: expiration) + let awsCognitoCredentials = AuthAWSCognitoCredentials( + accessKeyId: accessKey, + secretAccessKey: secretKey, + sessionToken: sessionKey, + expiration: expiration + ) let event = FetchAuthSessionEvent( eventType: .fetchedAWSCredentials(identityId, awsCognitoCredentials)) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/FetchIdentity/FetchAuthIdentityId.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/FetchIdentity/FetchAuthIdentityId.swift index 97ffabda08..bf21a6cd88 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/FetchIdentity/FetchAuthIdentityId.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/FetchIdentity/FetchAuthIdentityId.swift @@ -6,8 +6,8 @@ // import AWSCognitoIdentity -import Foundation import ClientRuntime +import Foundation struct FetchAuthIdentityId: Action { @@ -19,8 +19,10 @@ struct FetchAuthIdentityId: Action { self.loginsMap = loginsMap } - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) @@ -37,7 +39,8 @@ struct FetchAuthIdentityId: Action { let getIdInput = GetIdInput( identityPoolId: authZEnvironment.identityPoolConfiguration.poolId, - logins: loginsMap) + logins: loginsMap + ) do { let response = try await client.getId(input: getIdInput) @@ -52,14 +55,15 @@ struct FetchAuthIdentityId: Action { await dispatcher.send(event) } catch { - let event: FetchAuthSessionEvent - if isNotAuthorizedError(error) { - event = FetchAuthSessionEvent(eventType: .throwError(.notAuthorized)) + let event = if isNotAuthorizedError(error) { + FetchAuthSessionEvent(eventType: .throwError(.notAuthorized)) } else { - event = FetchAuthSessionEvent(eventType: .throwError(.service(error))) + FetchAuthSessionEvent(eventType: .throwError(.service(error))) } - logVerbose("\(#fileID) Sending event \(event.type)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(event.type)", + environment: environment + ) await dispatcher.send(event) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift index bca1e5e6d0..a4a1bead9e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift @@ -6,9 +6,9 @@ // import Amplify -import Foundation -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider +import Foundation struct InformSessionError: Action { @@ -19,17 +19,16 @@ struct InformSessionError: Action { func execute(withDispatcher dispatcher: EventDispatcher, environment: Environment) async { logVerbose("\(#fileID) Starting execution", environment: environment) - var event: AuthorizationEvent - switch error { + var event: AuthorizationEvent = switch error { case .service(let serviceError): if isNotAuthorizedError(serviceError) { - event = .init(eventType: .throwError( + .init(eventType: .throwError( .sessionExpired(error: serviceError))) } else { - event = .init(eventType: .receivedSessionError(error)) + .init(eventType: .receivedSessionError(error)) } default: - event = .init(eventType: .receivedSessionError(error)) + .init(eventType: .receivedSessionError(error)) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchAuthSessionWithUserPool.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchAuthSessionWithUserPool.swift index 09ecfed4b2..83b57a5ff8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchAuthSessionWithUserPool.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchAuthSessionWithUserPool.swift @@ -27,9 +27,11 @@ struct InitializeFetchAuthSessionWithUserPool: Action { case .userPoolsAndIdentityPools(let userPoolData, _): let region = userPoolData.region let poolId = userPoolData.poolId - let loginsMapProvider = CognitoUserPoolLoginsMap(idToken: tokens.idToken, - region: region, - poolId: poolId) + let loginsMapProvider = CognitoUserPoolLoginsMap( + idToken: tokens.idToken, + region: region, + poolId: poolId + ) event = .init(eventType: .fetchAuthenticatedIdentityID(loginsMapProvider)) default: event = .init(eventType: .throwError(.noUserPool)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchUnAuthSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchUnAuthSession.swift index 619e2586ff..e9e34495f2 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchUnAuthSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchUnAuthSession.swift @@ -17,13 +17,12 @@ struct InitializeFetchUnAuthSession: Action { logVerbose("\(#fileID) Starting execution", environment: environment) let configuration = (environment as? AuthEnvironment)?.configuration - let event: FetchAuthSessionEvent - switch configuration { + let event: FetchAuthSessionEvent = switch configuration { case .userPools: // If only user pool is configured then we do not have any unauthsession - event = .init(eventType: .throwError(.noIdentityPool)) + .init(eventType: .throwError(.noIdentityPool)) default: - event = .init(eventType: .fetchUnAuthIdentityID) + .init(eventType: .fetchUnAuthIdentityID) } logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Persistence/ConfigureAuthentication.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Persistence/ConfigureAuthentication.swift index df971f223f..3f9fdda072 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Persistence/ConfigureAuthentication.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Persistence/ConfigureAuthentication.swift @@ -32,8 +32,10 @@ struct ConfigureAuthentication: Action { logVerbose("\(#fileID) Sending event \(authenticationEvent.type)", environment: environment) await dispatcher.send(authenticationEvent) - let authStateEvent = AuthEvent(eventType: .authenticationConfigured(configuration, - storedCredentials)) + let authStateEvent = AuthEvent(eventType: .authenticationConfigured( + configuration, + storedCredentials + )) logVerbose("\(#fileID) Sending event \(authStateEvent.type)", environment: environment) await dispatcher.send(authStateEvent) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InitializeRefreshSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InitializeRefreshSession.swift index 43c36c2cb9..10dba6ba59 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InitializeRefreshSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InitializeRefreshSession.swift @@ -40,16 +40,20 @@ struct InitializeRefreshSession: Action { return } let tokens = signedInData.cognitoUserPoolTokens - let provider = CognitoUserPoolLoginsMap(idToken: tokens.idToken, - region: config.region, - poolId: config.poolId) + let provider = CognitoUserPoolLoginsMap( + idToken: tokens.idToken, + region: config.region, + poolId: config.poolId + ) if isForceRefresh || tokens.doesExpire(in: AmplifyCredentials.expiryBufferInSeconds) { event = .init(eventType: .refreshCognitoUserPoolWithIdentityId(signedInData, identityID)) } else { - event = .init(eventType: .refreshAWSCredentialsWithUserPool(identityID, - signedInData, - provider)) + event = .init(eventType: .refreshAWSCredentialsWithUserPool( + identityID, + signedInData, + provider + )) } case .noCredentials: event = .init(eventType: .throwError(.noCredentialsToRefresh)) @@ -74,7 +78,7 @@ extension InitializeRefreshSession: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { [ "identifier": identifier, - "isForceRefresh": isForceRefresh ? "true": "false", + "isForceRefresh": isForceRefresh ? "true" : "false", "existingCredentials": existingCredentials.debugDescription ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshUserPoolTokens.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshUserPoolTokens.swift index a5d180b876..382b7b0fca 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshUserPoolTokens.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshUserPoolTokens.swift @@ -6,10 +6,10 @@ // import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider -import Foundation +import AWSPluginsCore import ClientRuntime +import Foundation struct RefreshUserPoolTokens: Action { @@ -35,11 +35,13 @@ struct RefreshUserPoolTokens: Action { let deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: existingSignedIndata.username, - with: environment) + with: environment + ) let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: existingSignedIndata.username, - credentialStoreClient: authEnv.credentialsClient) + credentialStoreClient: authEnv.credentialsClient + ) let input = await InitiateAuthInput.refreshAuthInput( username: existingSignedIndata.username, @@ -47,7 +49,8 @@ struct RefreshUserPoolTokens: Action { clientMetadata: [:], asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: environment) + environment: environment + ) logVerbose("\(#fileID) Starting initiate auth refresh token", environment: environment) @@ -75,14 +78,16 @@ struct RefreshUserPoolTokens: Action { let signedInData = SignedInData( signedInDate: existingSignedIndata.signedInDate, signInMethod: existingSignedIndata.signInMethod, - cognitoUserPoolTokens: userPoolTokens) + cognitoUserPoolTokens: userPoolTokens + ) let event: RefreshSessionEvent if ((environment as? AuthEnvironment)?.identityPoolConfigData) != nil { let provider = CognitoUserPoolLoginsMap( idToken: idToken, region: config.region, - poolId: config.poolId) + poolId: config.poolId + ) event = .init(eventType: .refreshIdentityInfo(signedInData, provider)) } else { event = .init(eventType: .refreshedCognitoUserPool(signedInData)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/ConfirmDevice.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/ConfirmDevice.swift index 22da95affb..04232dc18f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/ConfirmDevice.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/ConfirmDevice.swift @@ -34,7 +34,8 @@ struct ConfirmDevice: Action { let passwordVerifier = srpClient.generateDevicePasswordVerifier( deviceGroupKey: deviceMetadata.deviceGroupKey, deviceKey: deviceMetadata.deviceKey, - password: deviceMetadata.deviceSecret) + password: deviceMetadata.deviceSecret + ) let deviceName = await DeviceInfo.current.name @@ -42,26 +43,34 @@ struct ConfirmDevice: Action { let base64EncodedSalt = passwordVerifier.salt.base64EncodedString() let verifier = CognitoIdentityProviderClientTypes.DeviceSecretVerifierConfigType( passwordVerifier: base64EncodedVerifier, - salt: base64EncodedSalt) + salt: base64EncodedSalt + ) let input = ConfirmDeviceInput( accessToken: signedInData.cognitoUserPoolTokens.accessToken, deviceKey: deviceMetadata.deviceKey, deviceName: deviceName, - deviceSecretVerifierConfig: verifier) + deviceSecretVerifierConfig: verifier + ) let response = try await client.confirmDevice(input: input) - logVerbose("Successfully completed device confirmation with result \(response)", - environment: environment) + logVerbose( + "Successfully completed device confirmation with result \(response)", + environment: environment + ) // Save the device metadata to keychain let credentialStoreClient = (environment as? AuthEnvironment)?.credentialsClient _ = try await credentialStoreClient?.storeData( data: .deviceMetadata(signedInData.deviceMetadata, signedInData.username)) - logVerbose("Successfully stored the device metadata in the keychain ", - environment: environment) + logVerbose( + "Successfully stored the device metadata in the keychain ", + environment: environment + ) } catch { - logError("Failed to confirm the device \(error)", - environment: environment) + logError( + "Failed to confirm the device \(error)", + environment: environment + ) } let event = SignInEvent(eventType: .finalizeSignIn(signedInData)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/CustomSignIn/InitiateCustomAuth.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/CustomSignIn/InitiateCustomAuth.swift index ff1c572f06..239aec3d95 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/CustomSignIn/InitiateCustomAuth.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/CustomSignIn/InitiateCustomAuth.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct InitiateCustomAuth: Action { let identifier = "InitiateCustomAuth" @@ -16,32 +16,40 @@ struct InitiateCustomAuth: Action { let clientMetadata: [String: String] let deviceMetadata: DeviceMetadata - init(username: String, - clientMetadata: [String: String], - deviceMetadata: DeviceMetadata) { + init( + username: String, + clientMetadata: [String: String], + deviceMetadata: DeviceMetadata + ) { self.username = username self.clientMetadata = clientMetadata self.deviceMetadata = deviceMetadata } - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) do { let userPoolEnv = try environment.userPoolEnvironment() let authEnv = try environment.authEnvironment() let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: authEnv.credentialsClient) + credentialStoreClient: authEnv.credentialsClient + ) let request = await InitiateAuthInput.customAuth( username: username, clientMetadata: clientMetadata, asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: userPoolEnv) + environment: userPoolEnv + ) - let responseEvent = try await sendRequest(request: request, - environment: userPoolEnv) + let responseEvent = try await sendRequest( + request: request, + environment: userPoolEnv + ) logVerbose("\(#fileID) Sending event \(responseEvent)", environment: environment) await dispatcher.send(responseEvent) @@ -60,16 +68,20 @@ struct InitiateCustomAuth: Action { } - private func sendRequest(request: InitiateAuthInput, - environment: UserPoolEnvironment) async throws -> StateMachineEvent { + private func sendRequest( + request: InitiateAuthInput, + environment: UserPoolEnvironment + ) async throws -> StateMachineEvent { let cognitoClient = try environment.cognitoUserPoolFactory() logVerbose("\(#fileID) Starting execution", environment: environment) let response = try await cognitoClient.initiateAuth(input: request) - return try UserPoolSignInHelper.parseResponse(response, - for: username, - signInMethod: .apiBased(.customWithoutSRP)) + return try UserPoolSignInHelper.parseResponse( + response, + for: username, + signInMethod: .apiBased(.customWithoutSRP) + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/InitiateAuthDeviceSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/InitiateAuthDeviceSRP.swift index fde6beec31..182989f480 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/InitiateAuthDeviceSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/InitiateAuthDeviceSRP.swift @@ -6,9 +6,9 @@ // import Amplify -import Foundation -import CryptoKit import AWSCognitoIdentityProvider +import CryptoKit +import Foundation struct InitiateAuthDeviceSRP: Action { let identifier = "InitiateAuthDeviceSRP" @@ -16,8 +16,10 @@ struct InitiateAuthDeviceSRP: Action { let username: String let authResponse: SignInResponseBehavior - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) do { @@ -31,11 +33,13 @@ struct InitiateAuthDeviceSRP: Action { // Get device metadata let deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) + with: environment + ) let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: environment.authEnvironment().credentialsClient) + credentialStoreClient: environment.authEnvironment().credentialsClient + ) let srpStateData = SRPStateData( username: username, @@ -43,7 +47,8 @@ struct InitiateAuthDeviceSRP: Action { NHexValue: nHexValue, gHexValue: gHexValue, srpKeyPair: srpKeyPair, - clientTimestamp: Date()) + clientTimestamp: Date() + ) let request = await RespondToAuthChallengeInput.deviceSRP( username: username, @@ -51,7 +56,8 @@ struct InitiateAuthDeviceSRP: Action { deviceMetadata: deviceMetadata, asfDeviceId: asfDeviceId, session: authResponse.session, - publicHexValue: srpKeyPair.publicKeyHexValue) + publicHexValue: srpKeyPair.publicKeyHexValue + ) let client = try userPoolEnv.cognitoUserPoolFactory() @@ -84,7 +90,8 @@ struct InitiateAuthDeviceSRP: Action { func parseResponse( _ response: SignInResponseBehavior, - with stateData: SRPStateData) -> StateMachineEvent { + with stateData: SRPStateData + ) -> StateMachineEvent { guard case .devicePasswordVerifier = response.challengeName else { let message = """ Unsupported challenge response during DeviceSRPAuth diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/StartDeviceSRPFlow.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/StartDeviceSRPFlow.swift index b797c0b24b..bdbe90675e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/StartDeviceSRPFlow.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/StartDeviceSRPFlow.swift @@ -17,7 +17,8 @@ struct StartDeviceSRPFlow: Action { func execute(withDispatcher dispatcher: EventDispatcher, environment: Environment) async { logVerbose("\(#fileID) Start execution", environment: environment) let event = SignInEvent(id: UUID().uuidString, eventType: .respondDeviceSRPChallenge( - username, authResponse)) + username, authResponse + )) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift index d1846ff20d..c7099a0673 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift @@ -5,26 +5,29 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CryptoKit +import Foundation extension VerifyDevicePasswordSRP { // swiftlint:disable:next function_parameter_count identifier_name - func signature(deviceGroupKey: String, - deviceKey: String, - deviceSecret: String, - saltHex: String, - secretBlock: Data, - serverPublicBHexString: String, - srpClient: SRPClientBehavior) throws -> String { + func signature( + deviceGroupKey: String, + deviceKey: String, + deviceSecret: String, + saltHex: String, + secretBlock: Data, + serverPublicBHexString: String, + srpClient: SRPClientBehavior + ) throws -> String { let sharedSecret = try sharedSecret( username: "\(deviceGroupKey)\(deviceKey)", password: deviceSecret, saltHex: saltHex, serverPublicBHexString: serverPublicBHexString, - srpClient: srpClient) + srpClient: srpClient + ) do { let dateStr = stateData.clientTimestamp.utcString @@ -32,11 +35,13 @@ extension VerifyDevicePasswordSRP { // swiftlint:disable:next identifier_name let u = try clientClass.calculateUHexValue( clientPublicKeyHexValue: stateData.srpKeyPair.publicKeyHexValue, - serverPublicKeyHexValue: serverPublicBHexString) + serverPublicKeyHexValue: serverPublicBHexString + ) // HKDF let authenticationKey = try clientClass.generateAuthenticationKey( sharedSecretHexValue: sharedSecret, - uHexValue: u) + uHexValue: u + ) // Signature let signature = generateSignature( @@ -44,7 +49,8 @@ extension VerifyDevicePasswordSRP { authenticationKey: authenticationKey, deviceKey: deviceKey, deviceGroupKey: deviceGroupKey, - serviceSecretBlock: secretBlock) + serviceSecretBlock: secretBlock + ) return signature.base64EncodedString() } catch let error as SRPError { @@ -57,11 +63,13 @@ extension VerifyDevicePasswordSRP { } } - func sharedSecret(username: String, - password: String, - saltHex: String, - serverPublicBHexString: String, - srpClient: SRPClientBehavior) throws -> String { + func sharedSecret( + username: String, + password: String, + saltHex: String, + serverPublicBHexString: String, + srpClient: SRPClientBehavior + ) throws -> String { do { let srpKeyPair = stateData.srpKeyPair return try srpClient.calculateSharedSecret( @@ -70,7 +78,8 @@ extension VerifyDevicePasswordSRP { saltHexValue: saltHex, clientPrivateKeyHexValue: srpKeyPair.privateKeyHexValue, clientPublicKeyHexValue: srpKeyPair.publicKeyHexValue, - serverPublicKeyHexValue: serverPublicBHexString) + serverPublicKeyHexValue: serverPublicBHexString + ) } catch let error as SRPError { let authError = SignInError.calculation(error) throw authError @@ -81,11 +90,13 @@ extension VerifyDevicePasswordSRP { } } - func generateSignature(srpTimeStamp: String, - authenticationKey: Data, - deviceKey: String, - deviceGroupKey: String, - serviceSecretBlock: Data) -> Data { + func generateSignature( + srpTimeStamp: String, + authenticationKey: Data, + deviceKey: String, + deviceGroupKey: String, + serviceSecretBlock: Data + ) -> Data { let key = SymmetricKey(data: authenticationKey) var hmac = HMAC.init(key: key) hmac.update(data: Data(deviceGroupKey.utf8)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP.swift index 4bfa1397de..58eff84d00 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct VerifyDevicePasswordSRP: Action { let identifier = "VerifyDevicePasswordSRP" @@ -15,8 +15,10 @@ struct VerifyDevicePasswordSRP: Action { let stateData: SRPStateData let authResponse: SignInResponseBehavior - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) do { @@ -35,11 +37,13 @@ struct VerifyDevicePasswordSRP: Action { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: environment.authEnvironment().credentialsClient) + credentialStoreClient: environment.authEnvironment().credentialsClient + ) let deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) + with: environment + ) guard case .metadata(let deviceData) = deviceMetadata else { @@ -57,7 +61,8 @@ struct VerifyDevicePasswordSRP: Action { saltHex: saltHex, secretBlock: secretBlock, serverPublicBHexString: serverPublicB, - srpClient: srpClient) + srpClient: srpClient + ) let request = await RespondToAuthChallengeInput.devicePasswordVerifier( username: username, @@ -67,15 +72,19 @@ struct VerifyDevicePasswordSRP: Action { signature: signature, deviceMetadata: deviceMetadata, asfDeviceId: asfDeviceId, - environment: userPoolEnv) + environment: userPoolEnv + ) let responseEvent = try await UserPoolSignInHelper.sendRespondToAuth( request: request, for: username, signInMethod: .apiBased(.userSRP), - environment: userPoolEnv) - logVerbose("\(#fileID) Sending event \(responseEvent)", - environment: environment) + environment: userPoolEnv + ) + logVerbose( + "\(#fileID) Sending event \(responseEvent)", + environment: environment + ) await dispatcher.send(responseEvent) } catch let error as SignInError { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/FetchHostedUISignInToken.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/FetchHostedUISignInToken.swift index 870a41f72a..59990d9a04 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/FetchHostedUISignInToken.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/FetchHostedUISignInToken.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import CryptoKit +import Foundation struct FetchHostedUISignInToken: Action { @@ -32,16 +32,17 @@ struct FetchHostedUISignInToken: Action { do { let request = try HostedUIRequestHelper.createTokenRequest( configuration: hostedUIConfig, - result: result) + result: result + ) let data = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in let task = hostedUIEnvironment.urlSessionFactory().dataTask(with: request) { data, _, error in - if let error = error { + if let error { continuation.resume(with: .failure(SignInError.service(error: error))) - } else if let data = data { + } else if let data { continuation.resume(with: .success(data)) } else { continuation.resume(with: .failure(SignInError.hostedUI(.tokenParsing))) @@ -71,7 +72,8 @@ struct FetchHostedUISignInToken: Action { func handleData(_ data: Data) async throws -> SignedInData { guard let json = try JSONSerialization.jsonObject( with: data, - options: []) as? [String: Any] else { + options: [] + ) as? [String: Any] else { throw HostedUIError.tokenParsing } @@ -86,11 +88,13 @@ struct FetchHostedUISignInToken: Action { idToken: idToken, accessToken: accessToken, refreshToken: refreshToken, - expiresIn: json["expires_in"] as? Int) + expiresIn: json["expires_in"] as? Int + ) let signedInData = SignedInData( signedInDate: Date(), signInMethod: .hostedUI(result.options), - cognitoUserPoolTokens: userPoolTokens) + cognitoUserPoolTokens: userPoolTokens + ) return signedInData } else { throw HostedUIError.tokenParsing diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/InitializeHostedUISignIn.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/InitializeHostedUISignIn.swift index ca0de00abe..9ba084b2ef 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/InitializeHostedUISignIn.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/InitializeHostedUISignIn.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import CryptoKit +import Foundation struct InitializeHostedUISignIn: Action { @@ -19,7 +19,8 @@ struct InitializeHostedUISignIn: Action { logVerbose("\(#fileID) Starting execution", environment: environment) guard let environment = environment as? AuthEnvironment, - let hostedUIEnvironment = environment.hostedUIEnvironment else { + let hostedUIEnvironment = environment.hostedUIEnvironment + else { let message = AuthPluginErrorConstants.configurationError let error = AuthenticationError.configuration(message: message) let event = AuthenticationEvent(eventType: .error(error)) @@ -32,13 +33,16 @@ struct InitializeHostedUISignIn: Action { presentationAnchor: options.presentationAnchor, environment: environment, hostedUIEnvironment: hostedUIEnvironment, - dispatcher: dispatcher) + dispatcher: dispatcher + ) } - func initializeHostedUI(presentationAnchor: AuthUIPresentationAnchor?, - environment: AuthEnvironment, - hostedUIEnvironment: HostedUIEnvironment, - dispatcher: EventDispatcher) async { + func initializeHostedUI( + presentationAnchor: AuthUIPresentationAnchor?, + environment: AuthEnvironment, + hostedUIEnvironment: HostedUIEnvironment, + dispatcher: EventDispatcher + ) async { let username = "unknown" let hostedUIConfig = hostedUIEnvironment.configuration let randomGenerator = hostedUIEnvironment.randomStringFactory() @@ -53,23 +57,29 @@ struct InitializeHostedUISignIn: Action { do { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: environment.credentialsClient) + credentialStoreClient: environment.credentialsClient + ) let encodedData = await CognitoUserPoolASF.encodedContext( username: username, asfDeviceId: asfDeviceId, asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: environment.userPoolConfiguration) + userPoolConfiguration: environment.userPoolConfiguration + ) - let url = try HostedUIRequestHelper.createSignInURL(state: state, - proofKey: proofKey, - userContextData: encodedData, - configuration: hostedUIConfig, - options: options) - let signInData = HostedUISigningInState(signInURL: url, - state: state, - codeChallenge: proofKey, - presentationAnchor: presentationAnchor, - options: options) + let url = try HostedUIRequestHelper.createSignInURL( + state: state, + proofKey: proofKey, + userContextData: encodedData, + configuration: hostedUIConfig, + options: options + ) + let signInData = HostedUISigningInState( + signInURL: url, + state: state, + codeChallenge: proofKey, + presentationAnchor: presentationAnchor, + options: options + ) let event = HostedUIEvent(eventType: .showHostedUI(signInData)) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/ShowHostedUISignIn.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/ShowHostedUISignIn.swift index 559a91f2f4..a997a2b148 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/ShowHostedUISignIn.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/ShowHostedUISignIn.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AuthenticationServices +import Foundation class ShowHostedUISignIn: NSObject, Action { @@ -43,7 +43,7 @@ class ShowHostedUISignIn: NSObject, Action { } let url = signingInData.signInURL - self.logVerbose("\(#fileID) Showing url \(url.absoluteString)", environment: environment) + logVerbose("\(#fileID) Showing url \(url.absoluteString)", environment: environment) do { let sessionAdapter = hostedUIEnvironment.hostedUISessionFactory() @@ -51,24 +51,27 @@ class ShowHostedUISignIn: NSObject, Action { url: url, callbackScheme: callbackURLScheme, inPrivate: signingInData.options.preferPrivateSession, - presentationAnchor: signingInData.presentationAnchor) + presentationAnchor: signingInData.presentationAnchor + ) guard let code = queryItems.first(where: { $0.name == "code" })?.value, let state = queryItems.first(where: { $0.name == "state" })?.value, - self.signingInData.state == state else { + signingInData.state == state else { let event = HostedUIEvent(eventType: .throwError(.hostedUI(.codeValidation))) - self.logVerbose("\(#fileID) Sending event \(event)", environment: environment) + logVerbose("\(#fileID) Sending event \(event)", environment: environment) await dispatcher.send(event) return } - let result = HostedUIResult(code: code, - state: state, - codeVerifier: self.signingInData.codeChallenge, - options: self.signingInData.options) + let result = HostedUIResult( + code: code, + state: state, + codeVerifier: signingInData.codeChallenge, + options: signingInData.options + ) let event = HostedUIEvent(eventType: .fetchToken(result)) - self.logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) + logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } catch let error as HostedUIError { self.logVerbose("\(#fileID) Received error \(error)", environment: environment) @@ -76,9 +79,9 @@ class ShowHostedUISignIn: NSObject, Action { self.logVerbose("\(#fileID) Sending event \(event)", environment: environment) await dispatcher.send(event) } catch { - self.logVerbose("\(#fileID) Received error \(error)", environment: environment) + logVerbose("\(#fileID) Received error \(error)", environment: environment) let event = HostedUIEvent(eventType: .throwError(.service(error: error))) - self.logVerbose("\(#fileID) Sending event \(event)", environment: environment) + logVerbose("\(#fileID) Sending event \(event)", environment: environment) await dispatcher.send(event) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/IntializeSignInFlow.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/IntializeSignInFlow.swift index 8ea604a1ff..dc1741b4a7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/IntializeSignInFlow.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/IntializeSignInFlow.swift @@ -25,7 +25,8 @@ struct InitializeSignInFlow: Action { func createSignInEvent(from environment: Environment) async -> SignInEvent { guard let authEnvironment = environment as? AuthEnvironment, - authEnvironment.configuration.getUserPoolConfiguration() != nil else { + authEnvironment.configuration.getUserPoolConfiguration() != nil + else { let message = AuthPluginErrorConstants.configurationError let event = SignInEvent(eventType: .throwAuthError(.configuration(message: message))) return event @@ -35,23 +36,25 @@ struct InitializeSignInFlow: Action { if let username = signInEventData.username { deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) + with: environment + ) } - let event: SignInEvent - switch signInEventData.signInMethod { + let event: SignInEvent = switch signInEventData.signInMethod { case .apiBased(let authflowType): - event = signInEvent(for: authflowType, with: deviceMetadata) + signInEvent(for: authflowType, with: deviceMetadata) case .hostedUI(let hostedUIOptions): - event = .init(eventType: .initiateHostedUISignIn(hostedUIOptions)) + .init(eventType: .initiateHostedUISignIn(hostedUIOptions)) } return event } - func signInEvent(for authflow: AuthFlowType, - with deviceMetadata: DeviceMetadata) -> SignInEvent { + func signInEvent( + for authflow: AuthFlowType, + with deviceMetadata: DeviceMetadata + ) -> SignInEvent { switch authflow { case .userSRP: return .init(eventType: .initiateSignInWithSRP(signInEventData, deviceMetadata)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/MigrateAuth/InitiateMigrateAuth.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/MigrateAuth/InitiateMigrateAuth.swift index 34cf4ece9d..3ecca4b345 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/MigrateAuth/InitiateMigrateAuth.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/MigrateAuth/InitiateMigrateAuth.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct InitiateMigrateAuth: Action { let identifier = "InitiateMigrateAuth" @@ -17,35 +17,43 @@ struct InitiateMigrateAuth: Action { let clientMetadata: [String: String] let deviceMetadata: DeviceMetadata - init(username: String, - password: String, - clientMetadata: [String: String], - deviceMetadata: DeviceMetadata) { + init( + username: String, + password: String, + clientMetadata: [String: String], + deviceMetadata: DeviceMetadata + ) { self.username = username self.password = password self.clientMetadata = clientMetadata self.deviceMetadata = deviceMetadata } - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) do { let userPoolEnv = try environment.userPoolEnvironment() let authEnv = try environment.authEnvironment() let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: authEnv.credentialsClient) + credentialStoreClient: authEnv.credentialsClient + ) let request = await InitiateAuthInput.migrateAuth( username: username, password: password, clientMetadata: clientMetadata, asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: userPoolEnv) + environment: userPoolEnv + ) - let responseEvent = try await sendRequest(request: request, - environment: userPoolEnv) + let responseEvent = try await sendRequest( + request: request, + environment: userPoolEnv + ) logVerbose("\(#fileID) Sending event \(responseEvent)", environment: environment) await dispatcher.send(responseEvent) @@ -64,16 +72,20 @@ struct InitiateMigrateAuth: Action { } - private func sendRequest(request: InitiateAuthInput, - environment: UserPoolEnvironment) async throws -> StateMachineEvent { + private func sendRequest( + request: InitiateAuthInput, + environment: UserPoolEnvironment + ) async throws -> StateMachineEvent { let cognitoClient = try environment.cognitoUserPoolFactory() logVerbose("\(#fileID) Starting execution", environment: environment) let response = try await cognitoClient.initiateAuth(input: request) - return try UserPoolSignInHelper.parseResponse(response, - for: username, - signInMethod: .apiBased(.userPassword)) + return try UserPoolSignInHelper.parseResponse( + response, + for: username, + signInMethod: .apiBased(.userPassword) + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/CancelSignIn.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/CancelSignIn.swift index eb5832ac4a..cf4be25834 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/CancelSignIn.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/CancelSignIn.swift @@ -11,8 +11,10 @@ import Foundation struct CancelSignIn: Action { let identifier = "CancelSignIn" - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) let event = AuthenticationEvent(eventType: .cancelSignIn) logVerbose("\(#fileID) Sending event \(event)", environment: environment) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/InitiateAuthSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/InitiateAuthSRP.swift index b1645d0ee1..47556a1758 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/InitiateAuthSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/InitiateAuthSRP.swift @@ -6,9 +6,9 @@ // import Amplify -import Foundation -import CryptoKit import AWSCognitoIdentityProvider +import CryptoKit +import Foundation struct InitiateAuthSRP: Action { let identifier = "InitiateAuthSRP" @@ -19,11 +19,13 @@ struct InitiateAuthSRP: Action { let deviceMetadata: DeviceMetadata let clientMetadata: [String: String] - init(username: String, - password: String, - authFlowType: AuthFlowType = .userSRP, - deviceMetadata: DeviceMetadata = .noData, - clientMetadata: [String: String] = [:]) { + init( + username: String, + password: String, + authFlowType: AuthFlowType = .userSRP, + deviceMetadata: DeviceMetadata = .noData, + clientMetadata: [String: String] = [:] + ) { self.username = username self.password = password self.authFlowType = authFlowType @@ -31,8 +33,10 @@ struct InitiateAuthSRP: Action { self.clientMetadata = clientMetadata } - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) do { let authEnv = try environment.authEnvironment() @@ -50,11 +54,13 @@ struct InitiateAuthSRP: Action { NHexValue: nHexValue, gHexValue: gHexValue, srpKeyPair: srpKeyPair, - clientTimestamp: Date()) + clientTimestamp: Date() + ) let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: authEnv.credentialsClient) + credentialStoreClient: authEnv.credentialsClient + ) let request = await InitiateAuthInput.srpInput( username: username, @@ -63,11 +69,14 @@ struct InitiateAuthSRP: Action { clientMetadata: clientMetadata, asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: userPoolEnv) + environment: userPoolEnv + ) - let responseEvent = try await sendRequest(request: request, - environment: userPoolEnv, - srpStateData: srpStateData) + let responseEvent = try await sendRequest( + request: request, + environment: userPoolEnv, + srpStateData: srpStateData + ) logVerbose("\(#fileID) Sending event \(responseEvent)", environment: srpEnv) await dispatcher.send(responseEvent) @@ -86,9 +95,11 @@ struct InitiateAuthSRP: Action { } - private func sendRequest(request: InitiateAuthInput, - environment: UserPoolEnvironment, - srpStateData: SRPStateData) async throws -> SignInEvent { + private func sendRequest( + request: InitiateAuthInput, + environment: UserPoolEnvironment, + srpStateData: SRPStateData + ) async throws -> SignInEvent { let cognitoClient = try environment.cognitoUserPoolFactory() logVerbose("\(#fileID) Starting execution", environment: environment) @@ -101,7 +112,8 @@ struct InitiateAuthSRP: Action { challenge: .customChallenge, username: username, session: response.session, - parameters: parameters) + parameters: parameters + ) return SignInEvent(eventType: .receivedChallenge(respondToAuthChallenge)) } return SignInEvent(eventType: .respondPasswordVerifier(srpStateData, response, clientMetadata)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/SRPSignInHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/SRPSignInHelper.swift index 3b113da329..c5b239fcfd 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/SRPSignInHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/SRPSignInHelper.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CryptoKit +import Foundation -struct SRPSignInHelper { +enum SRPSignInHelper { static func srpClient(_ environment: SRPAuthEnvironment) throws -> SRPClientBehavior { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/ThrowSignInError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/ThrowSignInError.swift index 80222157e2..a3bfe98f60 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/ThrowSignInError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/ThrowSignInError.swift @@ -13,8 +13,10 @@ struct ThrowSignInError: Action { let error: Error - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) let event = AuthenticationEvent( diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift index cab2fbc412..f6a9eafe61 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift @@ -5,25 +5,28 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CryptoKit +import Foundation extension VerifyPasswordSRP { // swiftlint:disable:next function_parameter_count - func signature(userIdForSRP: String, - saltHex: String, - secretBlock: Data, - serverPublicBHexString: String, - srpClient: SRPClientBehavior, - poolId: String) throws -> String { + func signature( + userIdForSRP: String, + saltHex: String, + secretBlock: Data, + serverPublicBHexString: String, + srpClient: SRPClientBehavior, + poolId: String + ) throws -> String { let sharedSecret = try sharedSecret( userIdForSRP: userIdForSRP, saltHex: saltHex, serverPublicBHexString: serverPublicBHexString, srpClient: srpClient, - poolId: poolId) + poolId: poolId + ) do { let strippedPoolId = strippedPoolId(poolId) @@ -32,11 +35,13 @@ extension VerifyPasswordSRP { // swiftlint:disable:next identifier_name let u = try clientClass.calculateUHexValue( clientPublicKeyHexValue: stateData.srpKeyPair.publicKeyHexValue, - serverPublicKeyHexValue: serverPublicBHexString) + serverPublicKeyHexValue: serverPublicBHexString + ) // HKDF let authenticationkey = try clientClass.generateAuthenticationKey( sharedSecretHexValue: sharedSecret, - uHexValue: u) + uHexValue: u + ) // Signature let signature = generateSignature( @@ -44,7 +49,8 @@ extension VerifyPasswordSRP { authenticationKey: authenticationkey, srpUserName: userIdForSRP, poolName: strippedPoolId, - serviceSecretBlock: secretBlock) + serviceSecretBlock: secretBlock + ) return signature.base64EncodedString() } catch let error as SRPError { @@ -57,11 +63,13 @@ extension VerifyPasswordSRP { } } - func sharedSecret(userIdForSRP: String, - saltHex: String, - serverPublicBHexString: String, - srpClient: SRPClientBehavior, - poolId: String) throws -> String { + func sharedSecret( + userIdForSRP: String, + saltHex: String, + serverPublicBHexString: String, + srpClient: SRPClientBehavior, + poolId: String + ) throws -> String { let strippedPoolId = strippedPoolId(poolId) let usernameForS = "\(strippedPoolId)\(userIdForSRP)" do { @@ -72,7 +80,8 @@ extension VerifyPasswordSRP { saltHexValue: saltHex, clientPrivateKeyHexValue: srpKeyPair.privateKeyHexValue, clientPublicKeyHexValue: srpKeyPair.publicKeyHexValue, - serverPublicKeyHexValue: serverPublicBHexString) + serverPublicKeyHexValue: serverPublicBHexString + ) } catch let error as SRPError { let authError = SignInError.calculation(error) throw authError @@ -88,11 +97,13 @@ extension VerifyPasswordSRP { return String(poolId[poolId.index(index, offsetBy: 1)...]) } - func generateSignature(srpTimeStamp: String, - authenticationKey: Data, - srpUserName: String, - poolName: String, - serviceSecretBlock: Data) -> Data { + func generateSignature( + srpTimeStamp: String, + authenticationKey: Data, + srpUserName: String, + poolName: String, + serviceSecretBlock: Data + ) -> Data { let key = SymmetricKey(data: authenticationKey) var hmac = HMAC.init(key: key) hmac.update(data: Data(poolName.utf8)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift index d6687065a7..03e84f157b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct VerifyPasswordSRP: Action { let identifier = "VerifyPasswordSRP" @@ -16,16 +16,20 @@ struct VerifyPasswordSRP: Action { let authResponse: InitiateAuthOutput let clientMetadata: ClientMetadata - init(stateData: SRPStateData, - authResponse: InitiateAuthOutput, - clientMetadata: ClientMetadata) { + init( + stateData: SRPStateData, + authResponse: InitiateAuthOutput, + clientMetadata: ClientMetadata + ) { self.stateData = stateData self.authResponse = authResponse self.clientMetadata = clientMetadata } - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) let inputUsername = stateData.username @@ -46,17 +50,21 @@ struct VerifyPasswordSRP: Action { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: environment.authEnvironment().credentialsClient) + credentialStoreClient: environment.authEnvironment().credentialsClient + ) deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) - let signature = try signature(userIdForSRP: userIdForSRP, - saltHex: saltHex, - secretBlock: secretBlock, - serverPublicBHexString: serverPublicB, - srpClient: srpClient, - poolId: userPoolEnv.userPoolConfiguration.poolId) + with: environment + ) + let signature = try signature( + userIdForSRP: userIdForSRP, + saltHex: saltHex, + secretBlock: secretBlock, + serverPublicBHexString: serverPublicB, + srpClient: srpClient, + poolId: userPoolEnv.userPoolConfiguration.poolId + ) let request = await RespondToAuthChallengeInput.passwordVerifier( username: username, stateData: stateData, @@ -66,30 +74,38 @@ struct VerifyPasswordSRP: Action { clientMetadata: clientMetadata, deviceMetadata: deviceMetadata, asfDeviceId: asfDeviceId, - environment: userPoolEnv) + environment: userPoolEnv + ) let responseEvent = try await UserPoolSignInHelper.sendRespondToAuth( request: request, for: username, signInMethod: .apiBased(.userSRP), - environment: userPoolEnv) - logVerbose("\(#fileID) Sending event \(responseEvent)", - environment: environment) + environment: userPoolEnv + ) + logVerbose( + "\(#fileID) Sending event \(responseEvent)", + environment: environment + ) await dispatcher.send(responseEvent) } catch let error as SignInError { logVerbose("\(#fileID) SRPSignInError \(error)", environment: environment) let event = SignInEvent( eventType: .throwPasswordVerifierError(error) ) - logVerbose("\(#fileID) Sending event \(event)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(event)", + environment: environment + ) await dispatcher.send(event) } catch let error where deviceNotFound(error: error, deviceMetadata: deviceMetadata) { logVerbose("\(#fileID) Received device not found \(error)", environment: environment) // Remove the saved device details and retry password verify await DeviceMetadataHelper.removeDeviceMetaData(for: username, with: environment) let event = SignInEvent(eventType: .retryRespondPasswordVerifier(stateData, authResponse, clientMetadata)) - logVerbose("\(#fileID) Sending event \(event)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(event)", + environment: environment + ) await dispatcher.send(event) } catch { logVerbose("\(#fileID) SRPSignInError Generic \(error)", environment: environment) @@ -97,8 +113,10 @@ struct VerifyPasswordSRP: Action { let event = SignInEvent( eventType: .throwAuthError(authError) ) - logVerbose("\(#fileID) Sending event \(event)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(event)", + environment: environment + ) await dispatcher.send(event) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/CompleteTOTPSetup.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/CompleteTOTPSetup.swift index ef4a63e26a..48b5ef7096 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/CompleteTOTPSetup.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/CompleteTOTPSetup.swift @@ -28,7 +28,8 @@ struct CompleteTOTPSetup: Action { deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) + with: environment + ) var challengeResponses = [ "USERNAME": username @@ -50,14 +51,16 @@ struct CompleteTOTPSetup: Action { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: authEnv.credentialsClient) + credentialStoreClient: authEnv.credentialsClient + ) var userContextData: CognitoIdentityProviderClientTypes.UserContextDataType? if let encodedData = await CognitoUserPoolASF.encodedContext( username: username, asfDeviceId: asfDeviceId, asfClient: userpoolEnv.cognitoUserPoolASFFactory(), - userPoolConfiguration: userpoolEnv.userPoolConfiguration) { + userPoolConfiguration: userpoolEnv.userPoolConfiguration + ) { userContextData = .init(encodedData: encodedData) } @@ -71,29 +74,37 @@ struct CompleteTOTPSetup: Action { challengeResponses: challengeResponses, clientId: userPoolClientId, session: userSession, - userContextData: userContextData) + userContextData: userContextData + ) let responseEvent = try await UserPoolSignInHelper.sendRespondToAuth( request: input, for: username, signInMethod: signInEventData.signInMethod, - environment: userpoolEnv) - logVerbose("\(#fileID) Sending event \(responseEvent)", - environment: environment) + environment: userpoolEnv + ) + logVerbose( + "\(#fileID) Sending event \(responseEvent)", + environment: environment + ) await dispatcher.send(responseEvent) } catch let error as SignInError { logError(error.authError.errorDescription, environment: environment) let errorEvent = SignInEvent(eventType: .throwAuthError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } catch { let error = SignInError.service(error: error) logError(error.authError.errorDescription, environment: environment) let errorEvent = SignInEvent(eventType: .throwAuthError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/InitializeTOTPSetup.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/InitializeTOTPSetup.swift index 8fd033dae4..69d20c863c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/InitializeTOTPSetup.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/InitializeTOTPSetup.swift @@ -16,7 +16,8 @@ struct InitializeTOTPSetup: Action { logVerbose("\(#fileID) Start execution", environment: environment) let event = SetUpTOTPEvent( id: UUID().uuidString, - eventType: .setUpTOTP(authResponse)) + eventType: .setUpTOTP(authResponse) + ) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/SetUpTOTP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/SetUpTOTP.swift index ff9f8633ac..291f6cf305 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/SetUpTOTP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/SetUpTOTP.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct SetUpTOTP: Action { @@ -31,7 +31,8 @@ struct SetUpTOTP: Action { } guard let session = result.session, - let secretCode = result.secretCode else { + let secretCode = result.secretCode + else { throw SignInError.unknown(message: "Error unwrapping result associateSoftwareToken result") } @@ -39,22 +40,29 @@ struct SetUpTOTP: Action { .waitForAnswer(.init( secretCode: secretCode, session: session, - username: username))) - logVerbose("\(#fileID) Sending event \(responseEvent)", - environment: environment) + username: username + ))) + logVerbose( + "\(#fileID) Sending event \(responseEvent)", + environment: environment + ) await dispatcher.send(responseEvent) } catch let error as SignInError { logError(error.authError.errorDescription, environment: environment) let errorEvent = SetUpTOTPEvent(eventType: .throwError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } catch { let error = SignInError.service(error: error) logError(error.authError.errorDescription, environment: environment) let errorEvent = SetUpTOTPEvent(eventType: .throwError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/VerifyTOTPSetup.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/VerifyTOTPSetup.swift index dd1b37450d..c415cae27e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/VerifyTOTPSetup.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/VerifyTOTPSetup.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct VerifyTOTPSetup: Action { @@ -25,7 +25,8 @@ struct VerifyTOTPSetup: Action { let input = VerifySoftwareTokenInput( friendlyDeviceName: friendlyDeviceName, session: session, - userCode: totpCode) + userCode: totpCode + ) // Initiate TOTP verification let result = try await client.verifySoftwareToken(input: input) @@ -36,21 +37,27 @@ struct VerifyTOTPSetup: Action { let responseEvent = SetUpTOTPEvent(eventType: .respondToAuthChallenge(session)) - logVerbose("\(#fileID) Sending event \(responseEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(responseEvent)", + environment: environment + ) await dispatcher.send(responseEvent) } catch let error as SignInError { logError(error.authError.errorDescription, environment: environment) let errorEvent = SetUpTOTPEvent(eventType: .throwError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } catch { let error = SignInError.service(error: error) logError(error.authError.errorDescription, environment: environment) let errorEvent = SetUpTOTPEvent(eventType: .throwError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/VerifySignInChallenge.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/VerifySignInChallenge.swift index 45c6556ce2..f94aa2c7da 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/VerifySignInChallenge.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/VerifySignInChallenge.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct VerifySignInChallenge: Action { @@ -33,11 +33,13 @@ struct VerifySignInChallenge: Action { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: environment.authEnvironment().credentialsClient) + credentialStoreClient: environment.authEnvironment().credentialsClient + ) deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( - for: username, - with: environment) + for: username, + with: environment + ) let input = await RespondToAuthChallengeInput.verifyChallenge( username: username, @@ -49,15 +51,19 @@ struct VerifySignInChallenge: Action { asfDeviceId: asfDeviceId, attributes: confirmSignEventData.attributes, deviceMetadata: deviceMetadata, - environment: userpoolEnv) + environment: userpoolEnv + ) let responseEvent = try await UserPoolSignInHelper.sendRespondToAuth( request: input, for: username, signInMethod: signInMethod, - environment: userpoolEnv) - logVerbose("\(#fileID) Sending event \(responseEvent)", - environment: environment) + environment: userpoolEnv + ) + logVerbose( + "\(#fileID) Sending event \(responseEvent)", + environment: environment + ) await dispatcher.send(responseEvent) } catch let error where deviceNotFound(error: error, deviceMetadata: deviceMetadata) { logVerbose("\(#fileID) Received device not found \(error)", environment: environment) @@ -70,14 +76,18 @@ struct VerifySignInChallenge: Action { await dispatcher.send(event) } catch let error as SignInError { let errorEvent = SignInEvent(eventType: .throwAuthError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } catch { let error = SignInError.service(error: error) let errorEvent = SignInEvent(eventType: .throwAuthError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/BuildRevokeTokenError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/BuildRevokeTokenError.swift index d4a3d5f429..3eb250552e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/BuildRevokeTokenError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/BuildRevokeTokenError.swift @@ -20,12 +20,14 @@ struct BuildRevokeTokenError: Action { logVerbose("\(#fileID) Starting execution", environment: environment) let revokeTokenError = AWSCognitoRevokeTokenError( refreshToken: signedInData.cognitoUserPoolTokens.refreshToken, - error: .service("", "", nil)) + error: .service("", "", nil) + ) let event = SignOutEvent(eventType: .signOutLocally( signedInData, hostedUIError: hostedUIError, globalSignOutError: globalSignOutError, - revokeTokenError: revokeTokenError)) + revokeTokenError: revokeTokenError + )) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/InitiateSignOut.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/InitiateSignOut.swift index dddb53bd49..bd89225197 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/InitiateSignOut.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/InitiateSignOut.swift @@ -21,8 +21,10 @@ struct InitiateSignOut: Action { let event: SignOutEvent if case .hostedUI(let options) = signedInData.signInMethod, options.preferPrivateSession == false { - event = SignOutEvent(eventType: .invokeHostedUISignOut(signOutEventData, - signedInData)) + event = SignOutEvent(eventType: .invokeHostedUISignOut( + signOutEventData, + signedInData + )) } else if signOutEventData.globalSignOut { event = SignOutEvent(eventType: .signOutGlobally(signedInData)) } else { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/RevokeToken.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/RevokeToken.swift index 642db164f2..8d0804b8c4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/RevokeToken.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/RevokeToken.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AWSCognitoIdentityProvider import Amplify +import AWSCognitoIdentityProvider +import Foundation struct RevokeToken: Action { @@ -59,19 +59,22 @@ struct RevokeToken: Action { let internalError = authErrorConvertible.authError revokeTokenError = AWSCognitoRevokeTokenError( refreshToken: signedInData.cognitoUserPoolTokens.refreshToken, - error: internalError) - } else if let error = error { + error: internalError + ) + } else if let error { let internalError = AuthError.service("", "", error) revokeTokenError = AWSCognitoRevokeTokenError( refreshToken: signedInData.cognitoUserPoolTokens.refreshToken, - error: internalError) + error: internalError + ) } let event = SignOutEvent(eventType: .signOutLocally( signedInData, hostedUIError: hostedUIError, globalSignOutError: globalSignOutError, - revokeTokenError: revokeTokenError)) + revokeTokenError: revokeTokenError + )) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/ShowHostedUISignOut.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/ShowHostedUISignOut.swift index 9cdf64017b..a5a1b6c88a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/ShowHostedUISignOut.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/ShowHostedUISignOut.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AuthenticationServices +import Foundation class ShowHostedUISignOut: NSObject, Action { @@ -25,14 +25,16 @@ class ShowHostedUISignOut: NSObject, Action { logVerbose("\(#fileID) Starting execution", environment: environment) guard let environment = environment as? AuthEnvironment, - let hostedUIEnvironment = environment.hostedUIEnvironment else { + let hostedUIEnvironment = environment.hostedUIEnvironment + else { let error = HostedUIError.pluginConfiguration(AuthPluginErrorConstants.configurationError) await sendEvent(with: error, dispatcher: dispatcher, environment: environment) return } let hostedUIConfig = hostedUIEnvironment.configuration guard let callbackURL = URL(string: hostedUIConfig.oauth.signOutRedirectURI), - let callbackURLScheme = callbackURL.scheme else { + let callbackURLScheme = callbackURL.scheme + else { await sendEvent(with: HostedUIError.signOutRedirectURI, dispatcher: dispatcher, environment: environment) return } @@ -44,44 +46,51 @@ class ShowHostedUISignOut: NSObject, Action { url: logoutURL, callbackScheme: callbackURLScheme, inPrivate: false, - presentationAnchor: signOutEvent.presentationAnchor) + presentationAnchor: signOutEvent.presentationAnchor + ) await sendEvent(with: nil, dispatcher: dispatcher, environment: environment) } catch { - self.logVerbose("\(#fileID) Received error \(error)", environment: environment) + logVerbose("\(#fileID) Received error \(error)", environment: environment) await sendEvent(with: error, dispatcher: dispatcher, environment: environment) } } - func sendEvent(with error: Error?, - dispatcher: EventDispatcher, - environment: Environment) async { + func sendEvent( + with error: Error?, + dispatcher: EventDispatcher, + environment: Environment + ) async { let event: SignOutEvent if let hostedUIInternalError = error as? HostedUIError { event = SignOutEvent(eventType: .hostedUISignOutError(hostedUIInternalError)) } else if let error = error as? AuthErrorConvertible { event = getEvent(for: AWSCognitoHostedUIError(error: error.authError)) - } else if let error = error { + } else if let error { let serviceError = AuthError.service( - "HostedUI failed with error", - "", + "HostedUI failed with error", + "", error ) event = getEvent(for: AWSCognitoHostedUIError(error: serviceError)) } else { event = getEvent(for: nil) } - self.logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) + logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } private func getEvent(for hostedUIError: AWSCognitoHostedUIError?) -> SignOutEvent { - if self.signOutEvent.globalSignOut { - return SignOutEvent(eventType: .signOutGlobally(self.signInData, - hostedUIError: hostedUIError)) + if signOutEvent.globalSignOut { + return SignOutEvent(eventType: .signOutGlobally( + signInData, + hostedUIError: hostedUIError + )) } else { - return SignOutEvent(eventType: .revokeToken(self.signInData, - hostedUIError: hostedUIError)) + return SignOutEvent(eventType: .revokeToken( + signInData, + hostedUIError: hostedUIError + )) } } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutGlobally.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutGlobally.swift index 778f32fd46..526595c056 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutGlobally.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutGlobally.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AWSCognitoIdentityProvider import Amplify +import AWSCognitoIdentityProvider +import Foundation struct SignOutGlobally: Action { @@ -55,19 +55,22 @@ struct SignOutGlobally: Action { let internalError = authErrorConvertible.authError globalSignOutError = AWSCognitoGlobalSignOutError( accessToken: signedInData.cognitoUserPoolTokens.accessToken, - error: internalError) - } else if let error = error { + error: internalError + ) + } else if let error { let internalError = AuthError.service("", "", error) globalSignOutError = AWSCognitoGlobalSignOutError( accessToken: signedInData.cognitoUserPoolTokens.accessToken, - error: internalError) + error: internalError + ) } - if let globalSignOutError = globalSignOutError { + if let globalSignOutError { let event = SignOutEvent(eventType: .globalSignOutError( signedInData, globalSignOutError: globalSignOutError, - hostedUIError: hostedUIError)) + hostedUIError: hostedUIError + )) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) return @@ -75,7 +78,8 @@ struct SignOutGlobally: Action { let event = SignOutEvent(eventType: .revokeToken( signedInData, - hostedUIError: hostedUIError)) + hostedUIError: hostedUIError + )) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutLocally.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutLocally.swift index cc9be1abea..f73b0a867c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutLocally.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutLocally.swift @@ -25,7 +25,8 @@ struct SignOutLocally: Action { event = SignOutEvent(eventType: .signedOutSuccess( hostedUIError: hostedUIError, globalSignOutError: globalSignOutError, - revokeTokenError: revokeTokenError)) + revokeTokenError: revokeTokenError + )) } catch { let signOutError = AuthenticationError.unknown( diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+ClientBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+ClientBehavior.swift index 503c9b3d4c..d3b9dc0f88 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+ClientBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+ClientBehavior.swift @@ -5,34 +5,42 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AuthenticationServices +import Foundation // swiftlint:disable force_cast extension AWSCognitoAuthPlugin: AuthCategoryBehavior { - public func signUp(username: String, - password: String?, - options: AuthSignUpRequest.Options?) async throws -> AuthSignUpResult { + public func signUp( + username: String, + password: String?, + options: AuthSignUpRequest.Options? + ) async throws -> AuthSignUpResult { let options = options ?? AuthSignUpRequest.Options() - let request = AuthSignUpRequest(username: username, - password: password, - options: options) + let request = AuthSignUpRequest( + username: username, + password: password, + options: options + ) let task = AWSAuthSignUpTask(request, authEnvironment: authEnvironment) return try await taskQueue.sync { return try await task.value } as! AuthSignUpResult } - public func confirmSignUp(for username: String, - confirmationCode: String, - options: AuthConfirmSignUpRequest.Options?) + public func confirmSignUp( + for username: String, + confirmationCode: String, + options: AuthConfirmSignUpRequest.Options? + ) async throws -> AuthSignUpResult { let options = options ?? AuthConfirmSignUpRequest.Options() - let request = AuthConfirmSignUpRequest(username: username, - code: confirmationCode, - options: options) + let request = AuthConfirmSignUpRequest( + username: username, + code: confirmationCode, + options: options + ) let task = AWSAuthConfirmSignUpTask(request, authEnvironment: authEnvironment) return try await taskQueue.sync { return try await task.value @@ -49,11 +57,15 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { } #if os(iOS) || os(macOS) || os(visionOS) - public func signInWithWebUI(presentationAnchor: AuthUIPresentationAnchor? = nil, - options: AuthWebUISignInRequest.Options?) async throws -> AuthSignInResult { + public func signInWithWebUI( + presentationAnchor: AuthUIPresentationAnchor? = nil, + options: AuthWebUISignInRequest.Options? + ) async throws -> AuthSignInResult { let options = options ?? AuthWebUISignInRequest.Options() - let request = AuthWebUISignInRequest(presentationAnchor: presentationAnchor, - options: options) + let request = AuthWebUISignInRequest( + presentationAnchor: presentationAnchor, + options: options + ) let task = AWSAuthWebUISignInTask( request, authConfiguration: authConfiguration, @@ -65,13 +77,17 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { } as! AuthSignInResult } - public func signInWithWebUI(for authProvider: AuthProvider, - presentationAnchor: AuthUIPresentationAnchor? = nil, - options: AuthWebUISignInRequest.Options?) async throws -> AuthSignInResult { + public func signInWithWebUI( + for authProvider: AuthProvider, + presentationAnchor: AuthUIPresentationAnchor? = nil, + options: AuthWebUISignInRequest.Options? + ) async throws -> AuthSignInResult { let options = options ?? AuthWebUISignInRequest.Options() - let request = AuthWebUISignInRequest(presentationAnchor: presentationAnchor, - authProvider: authProvider, - options: options) + let request = AuthWebUISignInRequest( + presentationAnchor: presentationAnchor, + authProvider: authProvider, + options: options + ) let task = AWSAuthWebUISignInTask( request, authConfiguration: authConfiguration, @@ -84,15 +100,21 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { } #endif - public func confirmSignIn(challengeResponse: String, - options: AuthConfirmSignInRequest.Options? = nil) async throws -> AuthSignInResult { + public func confirmSignIn( + challengeResponse: String, + options: AuthConfirmSignInRequest.Options? = nil + ) async throws -> AuthSignInResult { let options = options ?? AuthConfirmSignInRequest.Options() - let request = AuthConfirmSignInRequest(challengeResponse: challengeResponse, - options: options) - let task = AWSAuthConfirmSignInTask(request, - stateMachine: authStateMachine, - configuration: authConfiguration) + let request = AuthConfirmSignInRequest( + challengeResponse: challengeResponse, + options: options + ) + let task = AWSAuthConfirmSignInTask( + request, + stateMachine: authStateMachine, + configuration: authConfiguration + ) return try await taskQueue.sync { return try await task.value } as! AuthSignInResult @@ -129,31 +151,41 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { } as! AuthResetPasswordResult } - public func confirmResetPassword(for username: String, - with newPassword: String, - confirmationCode: String, - options: AuthConfirmResetPasswordRequest.Options?) async throws { + public func confirmResetPassword( + for username: String, + with newPassword: String, + confirmationCode: String, + options: AuthConfirmResetPasswordRequest.Options? + ) async throws { let options = options ?? AuthConfirmResetPasswordRequest.Options() - let request = AuthConfirmResetPasswordRequest(username: username, - newPassword: newPassword, - confirmationCode: confirmationCode, - options: options) + let request = AuthConfirmResetPasswordRequest( + username: username, + newPassword: newPassword, + confirmationCode: confirmationCode, + options: options + ) let task = AWSAuthConfirmResetPasswordTask(request, environment: authEnvironment, authConfiguration: authConfiguration) _ = try await taskQueue.sync { return try await task.value } } - public func signIn(username: String?, - password: String?, - options: AuthSignInRequest.Options?) async throws -> AuthSignInResult { + public func signIn( + username: String?, + password: String?, + options: AuthSignInRequest.Options? + ) async throws -> AuthSignInResult { let options = options ?? AuthSignInRequest.Options() - let request = AuthSignInRequest(username: username, - password: password, - options: options) - let task = AWSAuthSignInTask(request, - authStateMachine: self.authStateMachine, - configuration: authConfiguration) + let request = AuthSignInRequest( + username: username, + password: password, + options: options + ) + let task = AWSAuthSignInTask( + request, + authStateMachine: authStateMachine, + configuration: authConfiguration + ) return try await taskQueue.sync { return try await task.value } as! AuthSignInResult @@ -161,8 +193,9 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { public func deleteUser() async throws { let task = AWSAuthDeleteUserTask( - authStateMachine: self.authStateMachine, - authConfiguraiton: authConfiguration) + authStateMachine: authStateMachine, + authConfiguraiton: authConfiguration + ) _ = try await taskQueue.sync { return try await task.value } @@ -171,7 +204,8 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { public func setUpTOTP() async throws -> TOTPSetupDetails { let task = SetUpTOTPTask( authStateMachine: authStateMachine, - userPoolFactory: authEnvironment.cognitoUserPoolFactory) + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) return try await taskQueue.sync { return try await task.value } as! TOTPSetupDetails @@ -184,11 +218,13 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { let options = options ?? VerifyTOTPSetupRequest.Options() let request = VerifyTOTPSetupRequest( code: code, - options: options) + options: options + ) let task = VerifyTOTPSetupTask( request, authStateMachine: authStateMachine, - userPoolFactory: authEnvironment.cognitoUserPoolFactory) + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) _ = try await taskQueue.sync { return try await task.value } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+DeviceBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+DeviceBehavior.swift index 4dc7c9c348..1e7e909dde 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+DeviceBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+DeviceBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension AWSCognitoAuthPlugin: AuthCategoryDeviceBehavior { @@ -14,9 +14,11 @@ extension AWSCognitoAuthPlugin: AuthCategoryDeviceBehavior { -> [AuthDevice] { let options = options ?? AuthFetchDevicesRequest.Options() let request = AuthFetchDevicesRequest(options: options) - let task = AWSAuthFetchDevicesTask(request, - authStateMachine: authStateMachine, - userPoolFactory: authEnvironment.cognitoUserPoolFactory) + let task = AWSAuthFetchDevicesTask( + request, + authStateMachine: authStateMachine, + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) return try await taskQueue.sync { return try await task.value } as! [AuthDevice] // swiftlint:disable:this force_cast @@ -28,9 +30,11 @@ extension AWSCognitoAuthPlugin: AuthCategoryDeviceBehavior { ) async throws { let options = options ?? AuthForgetDeviceRequest.Options() let request = AuthForgetDeviceRequest(device: device, options: options) - let task = AWSAuthForgetDeviceTask(request, - authStateMachine: authStateMachine, - environment: authEnvironment) + let task = AWSAuthForgetDeviceTask( + request, + authStateMachine: authStateMachine, + environment: authEnvironment + ) _ = try await taskQueue.sync { return try await task.value } @@ -39,9 +43,11 @@ extension AWSCognitoAuthPlugin: AuthCategoryDeviceBehavior { public func rememberDevice( options: AuthRememberDeviceRequest.Options? = nil) async throws { let options = options ?? AuthRememberDeviceRequest.Options() let request = AuthRememberDeviceRequest(options: options) - let task = AWSAuthRememberDeviceTask(request, - authStateMachine: authStateMachine, - environment: authEnvironment) + let task = AWSAuthRememberDeviceTask( + request, + authStateMachine: authStateMachine, + environment: authEnvironment + ) _ = try await taskQueue.sync { return try await task.value } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+UserBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+UserBehavior.swift index 21df88d96b..770bbb1b55 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+UserBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+UserBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation // swiftlint:disable force_cast public extension AWSCognitoAuthPlugin { @@ -30,8 +30,10 @@ public extension AWSCognitoAuthPlugin { } as! AuthUpdateAttributeResult } - func update(userAttributes: [AuthUserAttribute], - options: AuthUpdateUserAttributesRequest.Options? = nil) + func update( + userAttributes: [AuthUserAttribute], + options: AuthUpdateUserAttributesRequest.Options? = nil + ) async throws -> [AuthUserAttributeKey: AuthUpdateAttributeResult] { let options = options ?? AuthUpdateUserAttributesRequest.Options() @@ -50,7 +52,8 @@ public extension AWSCognitoAuthPlugin { let options = options ?? AuthAttributeResendConfirmationCodeRequest.Options() let request = AuthAttributeResendConfirmationCodeRequest( - attributeKey: userAttributeKey, options: options) + attributeKey: userAttributeKey, options: options + ) let task = AWSAuthAttributeResendConfirmationCodeTask( request, authStateMachine: authStateMachine, @@ -68,10 +71,12 @@ public extension AWSCognitoAuthPlugin { ) async throws -> AuthCodeDeliveryDetails { let options = options ?? AuthSendUserAttributeVerificationCodeRequest.Options() let request = AuthSendUserAttributeVerificationCodeRequest( - attributeKey: userAttributeKey, options: options) + attributeKey: userAttributeKey, options: options + ) let task = AWSAuthSendUserAttributeVerificationCodeTask( request, authStateMachine: authStateMachine, - userPoolFactory: authEnvironment.cognitoUserPoolFactory) + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) return try await taskQueue.sync { return try await task.value } as! AuthCodeDeliveryDetails @@ -82,7 +87,8 @@ public extension AWSCognitoAuthPlugin { let request = AuthConfirmUserAttributeRequest( attributeKey: userAttribute, confirmationCode: confirmationCode, - options: options) + options: options + ) let task = AWSAuthConfirmUserAttributeTask(request, authStateMachine: authStateMachine, userPoolFactory: authEnvironment.cognitoUserPoolFactory) _ = try await taskQueue.sync { return try await task.value diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AWSCognitoAuthCredentialStore.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AWSCognitoAuthCredentialStore.swift index 28654896ea..89c72c7a48 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AWSCognitoAuthCredentialStore.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AWSCognitoAuthCredentialStore.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation @_spi(KeychainStore) import AWSPluginsCore struct AWSCognitoAuthCredentialStore { @@ -63,8 +63,7 @@ struct AWSCognitoAuthCredentialStore { /// - Old Identity Pool Config == New Identity Pool Config if oldUserPoolConfiguration == nil && newIdentityConfigData != nil && - oldIdentityPoolConfiguration == newIdentityConfigData - { + oldIdentityPoolConfiguration == newIdentityConfigData { // retrieve data from the old namespace and save with the new namespace if let oldCognitoCredentialsData = try? keychain._getData(oldNameSpace) { try? keychain._set(oldCognitoCredentialsData, key: newNameSpace) @@ -98,13 +97,15 @@ struct AWSCognitoAuthCredentialStore { private func generateDeviceMetadataKey( for username: String, - with configuration: AuthConfiguration) -> String { + with configuration: AuthConfiguration + ) -> String { return "\(storeKey(for: authConfiguration)).\(username).\(deviceMetadataKey)" } private func generateASFDeviceKey( for username: String, - with configuration: AuthConfiguration) -> String { + with configuration: AuthConfiguration + ) -> String { return "\(storeKey(for: authConfiguration)).\(username).\(deviceASFKey)" } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials+CognitoSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials+CognitoSession.swift index 326c8e19cb..54ee20a6d5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials+CognitoSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials+CognitoSession.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension AmplifyCredentials { static let expiryBufferInSeconds = TimeInterval.seconds(2 * 60) @@ -20,11 +20,13 @@ extension AmplifyCredentials { isSignedIn: true, identityIdResult: .failure(identityError), awsCredentialsResult: .failure(credentialsError), - cognitoTokensResult: .success(signedInData.cognitoUserPoolTokens)) + cognitoTokensResult: .success(signedInData.cognitoUserPoolTokens) + ) case .identityPoolOnly(let identityID, let credentials): return AuthCognitoSignedOutSessionHelper.makeSignedOutSession( identityId: identityID, - awsCredentials: credentials) + awsCredentials: credentials + ) case .identityPoolWithFederation(_, let identityId, let awsCredentials): return AWSAuthCognitoSession( isSignedIn: true, @@ -43,7 +45,8 @@ extension AmplifyCredentials { isSignedIn: true, identityIdResult: .success(identityID), awsCredentialsResult: .success(credentials), - cognitoTokensResult: .success(signedInData.cognitoUserPoolTokens)) + cognitoTokensResult: .success(signedInData.cognitoUserPoolTokens) + ) case .noCredentials: return AuthCognitoSignedOutSessionHelper.makeSessionWithNoGuestAccess() } @@ -64,9 +67,11 @@ extension AmplifyCredentials { case .identityPoolOnly(identityID: _, credentials: let awsCredentials): doesExpire = awsCredentials.doesExpire(in: expiryBuffer) - case .userPoolAndIdentityPool(signedInData: let data, - identityID: _, - credentials: let awsCredentials): + case .userPoolAndIdentityPool( + signedInData: let data, + identityID: _, + credentials: let awsCredentials + ): doesExpire = ( data.cognitoUserPoolTokens.doesExpire(in: expiryBuffer) || awsCredentials.doesExpire(in: expiryBuffer) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials.swift index 3d93d21d79..1ce0b9f8a6 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials.swift @@ -5,24 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Internal representation of Credentials Auth category maintain. enum AmplifyCredentials { case userPoolOnly(signedInData: SignedInData) - case identityPoolOnly(identityID: String, - credentials: AuthAWSCognitoCredentials) - - case identityPoolWithFederation(federatedToken: FederatedToken, - identityID: String, - credentials: AuthAWSCognitoCredentials) - - case userPoolAndIdentityPool(signedInData: SignedInData, - identityID: String, - credentials: AuthAWSCognitoCredentials) + case identityPoolOnly( + identityID: String, + credentials: AuthAWSCognitoCredentials + ) + + case identityPoolWithFederation( + federatedToken: FederatedToken, + identityID: String, + credentials: AuthAWSCognitoCredentials + ) + + case userPoolAndIdentityPool( + signedInData: SignedInData, + identityID: String, + credentials: AuthAWSCognitoCredentials + ) case noCredentials } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthEnvironment.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthEnvironment.swift index b8dd44df29..f6afd000c3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthEnvironment.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthEnvironment.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct AuthEnvironment: Environment, LoggerProvider { let configuration: AuthConfiguration diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthorizationEnvironment.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthorizationEnvironment.swift index 8337c3fb76..33b8676e5d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthorizationEnvironment.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthorizationEnvironment.swift @@ -41,14 +41,14 @@ struct BasicAuthorizationEnvironment: AuthorizationEnvironment { extension AuthEnvironment: AuthorizationEnvironment { var identityPoolConfiguration: IdentityPoolConfigurationData { - guard let authorizationEnvironment = authorizationEnvironment else { + guard let authorizationEnvironment else { fatalError("Could not find authorization environment") } return authorizationEnvironment.identityPoolConfiguration } var cognitoIdentityFactory: CognitoIdentityFactory { - guard let authorizationEnvironment = authorizationEnvironment else { + guard let authorizationEnvironment else { fatalError("Could not find authorization environment") } return authorizationEnvironment.cognitoIdentityFactory diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/CredentialStoreEnvironment.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/CredentialStoreEnvironment.swift index a7a54a7039..13cff87751 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/CredentialStoreEnvironment.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/CredentialStoreEnvironment.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import AWSPluginsCore import Amplify +import AWSPluginsCore struct CredentialEnvironment: Environment, LoggerProvider { let authConfiguration: AuthConfiguration @@ -35,9 +35,11 @@ struct BasicCredentialStoreEnvironment: CredentialStoreEnvironment { // Optional let eventIDFactory: EventIDFactory - init(amplifyCredentialStoreFactory: @escaping AmplifyAuthCredentialStoreFactory, - legacyKeychainStoreFactory: @escaping KeychainStoreFactory, - eventIDFactory: @escaping EventIDFactory = UUIDFactory.factory) { + init( + amplifyCredentialStoreFactory: @escaping AmplifyAuthCredentialStoreFactory, + legacyKeychainStoreFactory: @escaping KeychainStoreFactory, + eventIDFactory: @escaping EventIDFactory = UUIDFactory.factory + ) { self.amplifyCredentialStoreFactory = amplifyCredentialStoreFactory self.legacyKeychainStoreFactory = legacyKeychainStoreFactory self.eventIDFactory = eventIDFactory diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/SRPAuthEnvironment.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/SRPAuthEnvironment.swift index 822a9e37f3..a012c706ea 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/SRPAuthEnvironment.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/SRPAuthEnvironment.swift @@ -24,8 +24,10 @@ struct BasicSRPAuthEnvironment: SRPAuthEnvironment { cognitoUserPoolFactory: @escaping CognitoUserPoolFactory, eventIDFactory: @escaping EventIDFactory = UUIDFactory.factory, srpClientFactory: @escaping SRPClientFactory = AmplifySRPClient.init(NHexValue:gHexValue:), - srpConfiguration: (nHexValue: String, gHexValue: String) = (nHexValue: SRPCommonConfig.nHexValue, - gHexValue: SRPCommonConfig.gHexValue) + srpConfiguration: (nHexValue: String, gHexValue: String) = ( + nHexValue: SRPCommonConfig.nHexValue, + gHexValue: SRPCommonConfig.gHexValue + ) ) { self.userPoolConfiguration = userPoolConfiguration self.cognitoUserPoolFactory = cognitoUserPoolFactory diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/HubEvents/AuthHubEventHandler.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/HubEvents/AuthHubEventHandler.swift index c8248e156f..c70e9637e4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/HubEvents/AuthHubEventHandler.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/HubEvents/AuthHubEventHandler.swift @@ -40,14 +40,16 @@ class AuthHubEventHandler: AuthHubEventBehavior { case HubPayload.EventName.Auth.signInAPI: guard let event = payload.data as? AWSAuthSignInTask.AmplifyAuthTaskResult, - case let .success(result) = event else { + case let .success(result) = event + else { return } self?.handleSignInEvent(result) case HubPayload.EventName.Auth.confirmSignInAPI: guard let event = payload.data as? AWSAuthConfirmSignInTask.AmplifyAuthTaskResult, - case let .success(result) = event else { + case let .success(result) = event + else { return } self?.handleSignInEvent(result) @@ -55,14 +57,16 @@ class AuthHubEventHandler: AuthHubEventBehavior { #if os(iOS) || os(macOS) case HubPayload.EventName.Auth.webUISignInAPI: guard let event = payload.data as? AWSAuthWebUISignInTask.AmplifyAuthTaskResult, - case let .success(result) = event else { + case let .success(result) = event + else { return } self?.handleSignInEvent(result) case HubPayload.EventName.Auth.socialWebUISignInAPI: guard let event = payload.data as? AWSAuthWebUISignInTask.AmplifyAuthTaskResult, - case let .success(result) = event else { + case let .success(result) = event + else { return } self?.handleSignInEvent(result) @@ -70,7 +74,8 @@ class AuthHubEventHandler: AuthHubEventBehavior { case HubPayload.EventName.Auth.deleteUserAPI: guard let event = payload.data as? AWSAuthDeleteUserTask.AmplifyAuthTaskResult, - case .success = event else { + case .success = event + else { return } self?.sendUserDeletedEvent() @@ -89,7 +94,8 @@ class AuthHubEventHandler: AuthHubEventBehavior { case HubPayload.EventName.Auth.fetchSessionAPI: guard let event = payload.data as? AWSAuthFetchSessionTask.AmplifyAuthTaskResult, - case let .success(result) = event else { + case let .success(result) = event + else { return } self?.handleSessionEvent(result) @@ -109,7 +115,8 @@ class AuthHubEventHandler: AuthHubEventBehavior { private func handleSessionEvent(_ sessionResult: AuthSession) { guard let tokensProvider = sessionResult as? AuthCognitoTokensProvider, - case let .failure(authError) = tokensProvider.getCognitoTokens() else { + case let .failure(authError) = tokensProvider.getCognitoTokens() + else { return } guard case .sessionExpired = authError else { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthCognitoSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthCognitoSession.swift index 59d799e963..8dc177cd86 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthCognitoSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthCognitoSession.swift @@ -27,10 +27,12 @@ public struct AWSAuthCognitoSession: AuthSession, public let userPoolTokensResult: Result - init(isSignedIn: Bool, - identityIdResult: Result, - awsCredentialsResult: Result, - cognitoTokensResult: Result) { + init( + isSignedIn: Bool, + identityIdResult: Result, + awsCredentialsResult: Result, + cognitoTokensResult: Result + ) { self.isSignedIn = isSignedIn self.identityIdResult = identityIdResult self.awsCredentialsResult = awsCredentialsResult @@ -62,8 +64,9 @@ public struct AWSAuthCognitoSession: AuthSession, return .success(userSub) } catch AuthError.signedOut { return .failure(AuthError.signedOut( - AuthPluginErrorConstants.userSubSignOutError.errorDescription, - AuthPluginErrorConstants.userSubSignOutError.recoverySuggestion)) + AuthPluginErrorConstants.userSubSignOutError.errorDescription, + AuthPluginErrorConstants.userSubSignOutError.recoverySuggestion + )) } catch let error as AuthError { return .failure(error) } catch { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthDevice.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthDevice.swift index b2ad2fbedd..310251820f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthDevice.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthDevice.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public struct AWSAuthDevice: AuthDevice { @@ -28,12 +28,14 @@ public struct AWSAuthDevice: AuthDevice { /// The date this device was last updated. public let lastModifiedDate: Date? - public init(id: String, - name: String, - attributes: [String: String]?, - createdDate: Date?, - lastAuthenticatedDate: Date?, - lastModifiedDate: Date?) { + public init( + id: String, + name: String, + attributes: [String: String]?, + createdDate: Date?, + lastAuthenticatedDate: Date?, + lastModifiedDate: Date? + ) { self.id = id self.name = name self.attributes = attributes diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthUser.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthUser.swift index 07172c8da2..7cbd2c56e8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthUser.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthUser.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify public struct AWSAuthUser: AuthUser { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoAuthService.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoAuthService.swift index f61bd5ca52..a7b98bc275 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoAuthService.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoAuthService.swift @@ -20,6 +20,8 @@ public enum AWSCognitoAuthService { /// Both AWS Cognito User Pool and AWS Identity Pool auth services are configured. The associated /// value contains the underlying low level clients. - case userPoolAndIdentityPool(CognitoIdentityProviderClient, - CognitoIdentityClient) + case userPoolAndIdentityPool( + CognitoIdentityProviderClient, + CognitoIdentityClient + ) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoNetworkPreferences.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoNetworkPreferences.swift index 2be4f3279b..3d9d6d65ef 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoNetworkPreferences.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoNetworkPreferences.swift @@ -16,14 +16,16 @@ public struct AWSCognitoNetworkPreferences { public let timeoutIntervalForRequest: TimeInterval /// The maximum amount of time that a resource request should be allowed to take. - /// + /// /// NOTE: This value is only applicable to HostedUI because the underlying Swift SDK does /// not support resource timeouts public let timeoutIntervalForResource: TimeInterval? - public init(maxRetryCount: UInt32, - timeoutIntervalForRequest: TimeInterval, - timeoutIntervalForResource: TimeInterval? = nil) { + public init( + maxRetryCount: UInt32, + timeoutIntervalForRequest: TimeInterval, + timeoutIntervalForResource: TimeInterval? = nil + ) { self.maxRetryCount = maxRetryCount self.timeoutIntervalForRequest = timeoutIntervalForRequest self.timeoutIntervalForResource = timeoutIntervalForResource diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoSignOutResult.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoSignOutResult.swift index f8786e6353..0bb2bc4512 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoSignOutResult.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoSignOutResult.swift @@ -19,9 +19,11 @@ public enum AWSCognitoSignOutResult: AuthSignOutResult { case complete - case partial(revokeTokenError: AWSCognitoRevokeTokenError?, - globalSignOutError: AWSCognitoGlobalSignOutError?, - hostedUIError: AWSCognitoHostedUIError?) + case partial( + revokeTokenError: AWSCognitoRevokeTokenError?, + globalSignOutError: AWSCognitoGlobalSignOutError?, + hostedUIError: AWSCognitoHostedUIError? + ) case failed(AuthError) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoUserPoolTokens.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoUserPoolTokens.swift index 38d34ba4d9..1aec9b7f6c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoUserPoolTokens.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoUserPoolTokens.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation public struct AWSCognitoUserPoolTokens: AuthCognitoTokens { @@ -21,10 +21,12 @@ public struct AWSCognitoUserPoolTokens: AuthCognitoTokens { // swiftlint:disable:next line_length @available(*, deprecated, message: "Use of `init(idToken,accessToken,refreshToken:expiresIn)` is deprecated, use `exp` claim in the `idToken` or `accessToken` instead") - public init(idToken: String, - accessToken: String, - refreshToken: String, - expiresIn: Int) { + public init( + idToken: String, + accessToken: String, + refreshToken: String, + expiresIn: Int + ) { self.idToken = idToken self.accessToken = accessToken self.refreshToken = refreshToken @@ -33,26 +35,30 @@ public struct AWSCognitoUserPoolTokens: AuthCognitoTokens { // swiftlint:disable:next line_length @available(*, deprecated, message: "Use of `init(idToken,accessToken,refreshToken:expiration)` is deprecated, use `exp` claim in the `idToken` or `accessToken` instead") - public init(idToken: String, - accessToken: String, - refreshToken: String, - expiration: Date) { + public init( + idToken: String, + accessToken: String, + refreshToken: String, + expiration: Date + ) { self.idToken = idToken self.accessToken = accessToken self.refreshToken = refreshToken self.expiration = expiration } - init(idToken: String, - accessToken: String, - refreshToken: String, - expiresIn: Int? = nil) { + init( + idToken: String, + accessToken: String, + refreshToken: String, + expiresIn: Int? = nil + ) { self.idToken = idToken self.accessToken = accessToken self.refreshToken = refreshToken - if let expiresIn = expiresIn { + if let expiresIn { self.expiration = Date().addingTimeInterval(TimeInterval(expiresIn)) } else { let expirationDoubleValue: Double diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthAWSCognitoCredentials.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthAWSCognitoCredentials.swift index c3bcb015f5..19082e8f0f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthAWSCognitoCredentials.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthAWSCognitoCredentials.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation public struct AuthAWSCognitoCredentials: AWSTemporaryCredentials { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthChallengeType.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthChallengeType.swift index 272ecc8702..8be41cb0c2 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthChallengeType.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthChallengeType.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation enum AuthChallengeType { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthFlowType.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthFlowType.swift index 7320fe6bef..d7a9c364dd 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthFlowType.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthFlowType.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation public enum AuthFlowType: String { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/MFATypeExtension.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/MFATypeExtension.swift index afeedeb0c3..6614194fe5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/MFATypeExtension.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/MFATypeExtension.swift @@ -10,7 +10,7 @@ import Foundation extension MFAType: DefaultLogger { - internal init?(rawValue: String) { + init?(rawValue: String) { if rawValue.caseInsensitiveCompare("SMS_MFA") == .orderedSame { self = .sms } else if rawValue.caseInsensitiveCompare("SOFTWARE_TOKEN_MFA") == .orderedSame { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignInOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignInOptions.swift index ce54b5a908..bca07f4deb 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignInOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignInOptions.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify public struct AWSAuthConfirmSignInOptions { @@ -19,7 +20,8 @@ public struct AWSAuthConfirmSignInOptions { public init( userAttributes: [AuthUserAttribute]? = nil, metadata: [String: String]? = nil, - friendlyDeviceName: String? = nil) { + friendlyDeviceName: String? = nil + ) { self.userAttributes = userAttributes self.metadata = metadata self.friendlyDeviceName = friendlyDeviceName diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignUpOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignUpOptions.swift index c661c54855..4f2ff6bca1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignUpOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignUpOptions.swift @@ -13,8 +13,10 @@ public struct AWSAuthConfirmSignUpOptions { public let forceAliasCreation: Bool? - public init(metadata: [String: String]? = nil, - forceAliasCreation: Bool? = nil) { + public init( + metadata: [String: String]? = nil, + forceAliasCreation: Bool? = nil + ) { self.metadata = metadata self.forceAliasCreation = forceAliasCreation } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthResetPasswordOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthResetPasswordOptions.swift index e73ab0759a..3aecf5e584 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthResetPasswordOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthResetPasswordOptions.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Foundation public struct AWSAuthResetPasswordOptions { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthSignInOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthSignInOptions.swift index 6b6a0ee6d4..3b747fdd84 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthSignInOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthSignInOptions.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import AWSCognitoIdentityProvider +import Foundation public struct AWSAuthSignInOptions { @@ -26,9 +27,11 @@ public struct AWSAuthSignInOptions { public var validationData: [String: String]? @available(*, deprecated, renamed: "init(metadata:authFlowType:)") - public init(validationData: [String: String]? = nil, - metadata: [String: String]? = nil, - authFlowType: AuthFlowType? = nil) { + public init( + validationData: [String: String]? = nil, + metadata: [String: String]? = nil, + authFlowType: AuthFlowType? = nil + ) { self.validationData = validationData self.metadata = metadata self.authFlowType = authFlowType diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthWebUISignInOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthWebUISignInOptions.swift index 1b3751acdf..4f0268600a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthWebUISignInOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthWebUISignInOptions.swift @@ -6,8 +6,8 @@ // #if os(iOS) || os(macOS) || os(visionOS) -import Foundation import Amplify +import Foundation public struct AWSAuthWebUISignInOptions { @@ -27,16 +27,18 @@ public struct AWSAuthWebUISignInOptions { /// Safari always honors the request. public let preferPrivateSession: Bool - public init(idpIdentifier: String? = nil, - preferPrivateSession: Bool = false) { + public init( + idpIdentifier: String? = nil, + preferPrivateSession: Bool = false + ) { self.idpIdentifier = idpIdentifier self.preferPrivateSession = preferPrivateSession } } -extension AuthWebUISignInRequest.Options { +public extension AuthWebUISignInRequest.Options { - public static func preferPrivateSession() -> AuthWebUISignInRequest.Options { + static func preferPrivateSession() -> AuthWebUISignInRequest.Options { let pluginOptions = AWSAuthWebUISignInOptions(preferPrivateSession: true) let options = AuthWebUISignInRequest.Options(pluginOptions: pluginOptions) return options diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/AuthConfigureOperation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/AuthConfigureOperation.swift index 376ffefc4c..c24f676b18 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/AuthConfigureOperation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/AuthConfigureOperation.swift @@ -5,16 +5,17 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation -import ClientRuntime import AWSCognitoIdentityProvider +import ClientRuntime typealias ConfigureOperation = AmplifyOperation< AuthConfigureRequest, Void, - AuthError> + AuthError +> class AuthConfigureOperation: ConfigureOperation { @@ -22,16 +23,20 @@ class AuthConfigureOperation: ConfigureOperation { let authStateMachine: AuthStateMachine let credentialStoreStateMachine: CredentialStoreStateMachine - init(request: AuthConfigureRequest, - authStateMachine: AuthStateMachine, - credentialStoreStateMachine: CredentialStoreStateMachine) { + init( + request: AuthConfigureRequest, + authStateMachine: AuthStateMachine, + credentialStoreStateMachine: CredentialStoreStateMachine + ) { self.authConfiguration = request.authConfiguration self.authStateMachine = authStateMachine self.credentialStoreStateMachine = credentialStoreStateMachine - super.init(categoryType: .auth, - eventName: "InternalConfigureAuth", - request: request) + super.init( + categoryType: .auth, + eventName: "InternalConfigureAuth", + request: request + ) } override public func main() { @@ -39,7 +44,8 @@ class AuthConfigureOperation: ConfigureOperation { finish() dispatch(result: .failure(AuthError.configuration( "Configuration operation was cancelled", - "", nil))) + "", nil + ))) return } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/AmplifyOperationHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/AmplifyOperationHelper.swift index 3e4e761629..e96fab68f3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/AmplifyOperationHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/AmplifyOperationHelper.swift @@ -9,7 +9,9 @@ import Foundation typealias AuthStateMachine = StateMachine< AuthState, - AuthEnvironment> + AuthEnvironment +> typealias CredentialStoreStateMachine = StateMachine< CredentialStoreState, - CredentialEnvironment> + CredentialEnvironment +> diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/ClearFederationOperationHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/ClearFederationOperationHelper.swift index df5c6d46fe..0593cfc6e5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/ClearFederationOperationHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/ClearFederationOperationHelper.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct ClearFederationOperationHelper { @@ -17,7 +17,8 @@ struct ClearFederationOperationHelper { guard case .configured(let authNState, let authZState) = currentState else { let authError = AuthError.invalidState( "Clearing of federation failed.", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) throw authError } @@ -28,7 +29,8 @@ struct ClearFederationOperationHelper { default: let authError = AuthError.invalidState( "Clearing of federation failed.", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) throw authError } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/FetchAuthSessionOperationHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/FetchAuthSessionOperationHelper.swift index 98504afe89..c8a480d0de 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/FetchAuthSessionOperationHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/FetchAuthSessionOperationHelper.swift @@ -5,15 +5,17 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation class FetchAuthSessionOperationHelper { typealias FetchAuthSessionCompletion = (Result) -> Void - func fetch(_ authStateMachine: AuthStateMachine, - forceRefresh: Bool = false) async throws -> AuthSession { + func fetch( + _ authStateMachine: AuthStateMachine, + forceRefresh: Bool = false + ) async throws -> AuthSession { let state = await authStateMachine.currentState guard case .configured(_, let authorizationState) = state else { let message = "Auth state machine not in configured state: \(state)" @@ -36,7 +38,8 @@ class FetchAuthSessionOperationHelper { return try await refreshIfRequired( existingCredentials: credentials, authStateMachine: authStateMachine, - forceRefresh: forceRefresh) + forceRefresh: forceRefresh + ) case .error(let error): if case .sessionExpired(let error) = error { @@ -48,7 +51,8 @@ class FetchAuthSessionOperationHelper { return try await refreshIfRequired( existingCredentials: credentials, authStateMachine: authStateMachine, - forceRefresh: forceRefresh) + forceRefresh: forceRefresh + ) } else { log.verbose("Session is in error state \(error)") let event = AuthorizationEvent(eventType: .fetchUnAuthSession) @@ -64,7 +68,8 @@ class FetchAuthSessionOperationHelper { func refreshIfRequired( existingCredentials credentials: AmplifyCredentials, authStateMachine: AuthStateMachine, - forceRefresh: Bool) async throws -> AuthSession { + forceRefresh: Bool + ) async throws -> AuthSession { if forceRefresh || !credentials.areValid() { var event: AuthorizationEvent @@ -100,12 +105,15 @@ class FetchAuthSessionOperationHelper { case .error(let authorizationError): return try sessionResultWithError( authorizationError, - authenticationState: authenticationState) + authenticationState: authenticationState + ) default: continue } } - throw AuthError.invalidState("Could not fetch session due to internal error", - "Auth plugin is in an invalid state") + throw AuthError.invalidState( + "Could not fetch session due to internal error", + "Auth plugin is in an invalid state" + ) } func sessionResultWithError( @@ -140,7 +148,8 @@ class FetchAuthSessionOperationHelper { isSignedIn: isSignedIn, identityIdResult: .failure(authError), awsCredentialsResult: .failure(authError), - cognitoTokensResult: .failure(authError)) + cognitoTokensResult: .failure(authError) + ) return session } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/HostedUISignInHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/HostedUISignInHelper.swift index 5b0c35cefe..5aec48a307 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/HostedUISignInHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/HostedUISignInHelper.swift @@ -6,8 +6,8 @@ // #if os(iOS) || os(macOS) || os(visionOS) -import Foundation import Amplify +import Foundation struct HostedUISignInHelper: DefaultLogger { @@ -17,9 +17,11 @@ struct HostedUISignInHelper: DefaultLogger { let configuration: AuthConfiguration - init(request: AuthWebUISignInRequest, - authstateMachine: AuthStateMachine, - configuration: AuthConfiguration) { + init( + request: AuthWebUISignInRequest, + authstateMachine: AuthStateMachine, + configuration: AuthConfiguration + ) { self.request = request self.authStateMachine = authstateMachine self.configuration = configuration @@ -51,7 +53,8 @@ struct HostedUISignInHelper: DefaultLogger { case .signedIn: throw AuthError.invalidState( "There is already a user in signedIn state. SignOut the user first before calling signIn", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) case .signedOut: return default: continue @@ -81,8 +84,10 @@ struct HostedUISignInHelper: DefaultLogger { await sendSignInEvent(oauthConfiguration: oauthConfiguration) log.verbose("Wait for signIn to complete") for await state in stateSequences { - guard case .configured(let authNState, - let authZState) = state else { continue } + guard case .configured( + let authNState, + let authZState + ) = state else { continue } switch authNState { case .signedIn: @@ -115,16 +120,22 @@ struct HostedUISignInHelper: DefaultLogger { let privateSession = pluginOptions?.preferPrivateSession ?? false let idpIdentifier = pluginOptions?.idpIdentifier - let providerInfo = HostedUIProviderInfo(authProvider: request.authProvider, - idpIdentifier: idpIdentifier) + let providerInfo = HostedUIProviderInfo( + authProvider: request.authProvider, + idpIdentifier: idpIdentifier + ) let scopeFromConfig = oauthConfiguration.scopes - let hostedUIOptions = HostedUIOptions(scopes: request.options.scopes ?? scopeFromConfig, - providerInfo: providerInfo, - presentationAnchor: request.presentationAnchor, - preferPrivateSession: privateSession) - let signInData = SignInEventData(username: nil, - password: nil, - signInMethod: .hostedUI(hostedUIOptions)) + let hostedUIOptions = HostedUIOptions( + scopes: request.options.scopes ?? scopeFromConfig, + providerInfo: providerInfo, + presentationAnchor: request.presentationAnchor, + preferPrivateSession: privateSession + ) + let signInData = SignInEventData( + username: nil, + password: nil, + signInMethod: .hostedUI(hostedUIOptions) + ) let event = AuthenticationEvent.init(eventType: .signInRequested(signInData)) await authStateMachine.send(event) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/UpdateAttributesOperationHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/UpdateAttributesOperationHelper.swift index 269cf048e8..4239b0c7e7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/UpdateAttributesOperationHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/UpdateAttributesOperationHelper.swift @@ -6,10 +6,10 @@ // import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore -struct UpdateAttributesOperationHelper { +enum UpdateAttributesOperationHelper { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -17,13 +17,16 @@ struct UpdateAttributesOperationHelper { attributes: [AuthUserAttribute], accessToken: String, userPoolFactory: @escaping CognitoUserPoolFactory, - clientMetaData: [String: String]) async throws -> [AuthUserAttributeKey: AuthUpdateAttributeResult] { + clientMetaData: [String: String] + ) async throws -> [AuthUserAttributeKey: AuthUpdateAttributeResult] { let userPoolService = try userPoolFactory() - let input = UpdateUserAttributesInput(accessToken: accessToken, - clientMetadata: clientMetaData, - userAttributes: attributes.map({ $0.sdkClientAttributeType() })) + let input = UpdateUserAttributesInput( + accessToken: accessToken, + clientMetadata: clientMetaData, + userAttributes: attributes.map { $0.sdkClientAttributeType() } + ) let result = try await userPoolService.updateUserAttributes(input: input) @@ -32,8 +35,10 @@ struct UpdateAttributesOperationHelper { if let attribute = item.attributeName { let authCodeDeliveryDetails = item.toAuthCodeDeliveryDetails() let nextStep = AuthUpdateAttributeStep.confirmAttributeWithCode(authCodeDeliveryDetails, nil) - let updateAttributeResult = AuthUpdateAttributeResult(isUpdated: false, - nextStep: nextStep) + let updateAttributeResult = AuthUpdateAttributeResult( + isUpdated: false, + nextStep: nextStep + ) finalResult[AuthUserAttributeKey(rawValue: attribute)] = updateAttributeResult } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Request/AuthFederateToIdentityPoolRequest.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Request/AuthFederateToIdentityPoolRequest.swift index 2ab68e1c01..571932f115 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Request/AuthFederateToIdentityPoolRequest.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Request/AuthFederateToIdentityPoolRequest.swift @@ -18,9 +18,11 @@ public struct AuthFederateToIdentityPoolRequest: AmplifyOperationRequest { /// Extra request options defined in `FederateToIdentityPoolRequest.Options` public var options: Options - public init(token: String, - provider: AuthProvider, - options: Options) { + public init( + token: String, + provider: AuthProvider, + options: Options + ) { self.token = token self.provider = provider self.options = options diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/AmplifySRPClient.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/AmplifySRPClient.swift index de41eead55..c81306db5e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/AmplifySRPClient.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/AmplifySRPClient.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AmplifySRP import AmplifyBigInteger +import AmplifySRP +import Foundation struct AmplifySRPClient: SRPClientBehavior { @@ -31,18 +31,22 @@ struct AmplifySRPClient: SRPClientBehavior { func generateClientKeyPair() -> SRPKeys { let publicHexValue = client.publicA.asString(radix: 16) let privateHexValue = client.privateA.asString(radix: 16) - let srpKeys = SRPKeys(publicKeyHexValue: publicHexValue, - privateKeyHexValue: privateHexValue) + let srpKeys = SRPKeys( + publicKeyHexValue: publicHexValue, + privateKeyHexValue: privateHexValue + ) return srpKeys } // swiftlint:disable:next function_parameter_count - func calculateSharedSecret(username: String, - password: String, - saltHexValue: String, - clientPrivateKeyHexValue: String, - clientPublicKeyHexValue: String, - serverPublicKeyHexValue: String) throws -> String { + func calculateSharedSecret( + username: String, + password: String, + saltHexValue: String, + clientPrivateKeyHexValue: String, + clientPublicKeyHexValue: String, + serverPublicKeyHexValue: String + ) throws -> String { guard let clientPublicNum = BigInt(clientPublicKeyHexValue, radix: 16) else { throw SRPError.numberConversion } @@ -58,18 +62,22 @@ struct AmplifySRPClient: SRPClientBehavior { guard serverPublicKeyNum % commonState.prime != BigInt(0) else { throw SRPError.illegalParameter } - let sharedSecret = SRPClientState.calculateSessionKey(username: username, - password: password, - publicClientKey: clientPublicNum, - privateClientKey: clientPrivateNum, - publicServerKey: serverPublicKeyNum, - salt: saltNum, - commonState: commonState) + let sharedSecret = SRPClientState.calculateSessionKey( + username: username, + password: password, + publicClientKey: clientPublicNum, + privateClientKey: clientPrivateNum, + publicServerKey: serverPublicKeyNum, + salt: saltNum, + commonState: commonState + ) return sharedSecret.asString(radix: 16) } - static func calculateUHexValue(clientPublicKeyHexValue: String, - serverPublicKeyHexValue: String) throws -> String { + static func calculateUHexValue( + clientPublicKeyHexValue: String, + serverPublicKeyHexValue: String + ) throws -> String { guard let clientPublicNum = BigInt(clientPublicKeyHexValue, radix: 16) else { throw SRPError.numberConversion } @@ -79,8 +87,10 @@ struct AmplifySRPClient: SRPClientBehavior { let signedClientPublicKey = AmplifyBigIntHelper.getSignedData(num: clientPublicNum) let signedServerPublicKey = AmplifyBigIntHelper.getSignedData(num: serverPublicNum) - let u = SRPClientState.calculcateU(publicClientKey: signedClientPublicKey, - publicServerKey: signedServerPublicKey) + let u = SRPClientState.calculcateU( + publicClientKey: signedClientPublicKey, + publicServerKey: signedServerPublicKey + ) return u.asString(radix: 16) } @@ -99,20 +109,23 @@ struct AmplifySRPClient: SRPClientBehavior { keyingMaterial: Data(keyingMaterial), salt: Data(salt), info: "Caldera Derived Key", - outputLength: 16) + outputLength: 16 + ) return authenticationkey } func generateDevicePasswordVerifier( deviceGroupKey: String, deviceKey: String, - password: String) -> (salt: Data, passwordVerifier: Data) { + password: String + ) -> (salt: Data, passwordVerifier: Data) { let passwordVerifier = SRPClientState.calculateDevicePasswordVerifier( deviceGroupKey: deviceGroupKey, deviceKey: deviceKey, password: password, - commonState: commonState) + commonState: commonState + ) let verifierData = Data(AmplifyBigIntHelper.getSignedData( num: passwordVerifier.passwordVerifier)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/SRPClientBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/SRPClientBehavior.swift index 2b1c549df6..ed7d5a5a1c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/SRPClientBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/SRPClientBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AmplifySRP +import Foundation protocol SRPClientBehavior { @@ -14,24 +14,29 @@ protocol SRPClientBehavior { func generateClientKeyPair() -> SRPKeys - func calculateSharedSecret(username: String, - password: String, - saltHexValue: String, - clientPrivateKeyHexValue: String, - clientPublicKeyHexValue: String, - serverPublicKeyHexValue: String) throws -> String + func calculateSharedSecret( + username: String, + password: String, + saltHexValue: String, + clientPrivateKeyHexValue: String, + clientPublicKeyHexValue: String, + serverPublicKeyHexValue: String + ) throws -> String static func calculateUHexValue( clientPublicKeyHexValue: String, - serverPublicKeyHexValue: String) throws -> String + serverPublicKeyHexValue: String + ) throws -> String static func generateAuthenticationKey( - sharedSecretHexValue: String, uHexValue: String) throws -> Data + sharedSecretHexValue: String, uHexValue: String + ) throws -> Data func generateDevicePasswordVerifier( deviceGroupKey: String, deviceKey: String, - password: String) -> (salt: Data, passwordVerifier: Data) + password: String + ) -> (salt: Data, passwordVerifier: Data) } enum SRPError: Error { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift index dbe795e4fc..7a0610bbfa 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSCognitoIdentity import AWSClientRuntime +import AWSCognitoIdentity +import Foundation // AWSCognitoIdentity extension AWSCognitoIdentity.ExternalServiceException: AuthErrorConvertible { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift index 2328f1da8d..86be29305f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoIdentityProvider +import Foundation @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime extension ForbiddenException: AuthErrorConvertible { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AuthErrorConvertible.swift index e811b761d9..6221452a2f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AuthErrorConvertible.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// A type that can be represented as an AuthError /// diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ClientError+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ClientError+AuthErrorConvertible.swift index b890ee76be..695f15c3ae 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ClientError+AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ClientError+AuthErrorConvertible.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation import Smithy import SmithyHTTPAPI diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/CommonRunTimeError+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/CommonRunTimeError+AuthErrorConvertible.swift index 8244b277a5..2bdff43b41 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/CommonRunTimeError+AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/CommonRunTimeError+AuthErrorConvertible.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AwsCommonRuntimeKit -import AwsCIo import AwsCHttp +import AwsCIo +import AwsCommonRuntimeKit +import Foundation private let connectivityErrorCodes: Set = [ AWS_ERROR_HTTP_CONNECTION_CLOSED.rawValue, @@ -30,8 +30,7 @@ private let connectivityErrorCodes: Set = [ extension CommonRunTimeError: AuthErrorConvertible { var authError: AuthError { - let error: CRTError - switch self { case .crtError(let crtError): error = crtError } + let error: CRTError = switch self { case .crtError(let crtError): crtError } if connectivityErrorCodes.contains(UInt32(error.code)) { return .service(error.name, error.message, AWSCognitoAuthError.network) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/AuthUserAttribute+Helper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/AuthUserAttribute+Helper.swift index 532cd251aa..4b811ad4dd 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/AuthUserAttribute+Helper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/AuthUserAttribute+Helper.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation extension AuthUserAttribute { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/ListDevicesOutputResponse+Helper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/ListDevicesOutputResponse+Helper.swift index 570f5bfb5d..b68e4a435c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/ListDevicesOutputResponse+Helper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/ListDevicesOutputResponse+Helper.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoIdentityProvider import AWSPluginsCore +import Foundation extension CognitoIdentityProviderClientTypes.DeviceType { @@ -27,6 +27,7 @@ extension CognitoIdentityProviderClientTypes.DeviceType { attributes: attributes, createdDate: deviceCreateDate, lastAuthenticatedDate: deviceLastAuthenticatedDate, - lastModifiedDate: deviceLastModifiedDate) + lastModifiedDate: deviceLastModifiedDate + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/SignUpOutputResponse+Helper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/SignUpOutputResponse+Helper.swift index df971aef31..a416c46163 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/SignUpOutputResponse+Helper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/SignUpOutputResponse+Helper.swift @@ -6,13 +6,13 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation extension SignUpOutput { var authResponse: AuthSignUpResult { - if self.userConfirmed { + if userConfirmed { return .init(.done, userID: userSub) } return AuthSignUpResult( @@ -46,7 +46,8 @@ extension CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType { } return AuthCodeDeliveryDetails( destination: destination, - attributeKey: AuthUserAttributeKey(rawValue: attributeToVerify)) + attributeKey: AuthUserAttributeKey(rawValue: attributeToVerify) + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/SdkTypealiases.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/SdkTypealiases.swift index 6baf521d3b..ccd8818bf8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/SdkTypealiases.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/SdkTypealiases.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSClientRuntime import ClientRuntime +import Foundation import SmithyHTTPAPI public typealias NetworkResult = (Result) -> Void diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalytics.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalytics.swift index 8c3a6972be..ad8c591910 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalytics.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalytics.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation @_spi(KeychainStore) import AWSPluginsCore struct UserPoolAnalytics: UserPoolAnalyticsBehavior { @@ -15,14 +15,16 @@ struct UserPoolAnalytics: UserPoolAnalyticsBehavior { static let AWSPinpointContextKeychainUniqueIdKey = "com.amazonaws.AWSPinpointContextKeychainUniqueIdKey" let pinpointEndpoint: String? - init(_ configuration: UserPoolConfigurationData?, - credentialStoreEnvironment: CredentialStoreEnvironment) throws { + init( + _ configuration: UserPoolConfigurationData?, + credentialStoreEnvironment: CredentialStoreEnvironment + ) throws { if let pinpointId = configuration?.pinpointAppId, !pinpointId.isEmpty { - pinpointEndpoint = try UserPoolAnalytics.getInternalPinpointEndpoint( + self.pinpointEndpoint = try UserPoolAnalytics.getInternalPinpointEndpoint( credentialStoreEnvironment) } else { - pinpointEndpoint = nil + self.pinpointEndpoint = nil } } @@ -37,15 +39,17 @@ struct UserPoolAnalytics: UserPoolAnalyticsBehavior { AWSPinpointContextKeychainUniqueIdKey) else { let uniqueValue = UUID().uuidString.lowercased() - try legacyKeychainStore._set(AWSPinpointContextKeychainUniqueIdKey, - key: uniqueValue) + try legacyKeychainStore._set( + AWSPinpointContextKeychainUniqueIdKey, + key: uniqueValue + ) return uniqueValue } return value } func analyticsMetadata() -> CognitoIdentityProviderClientTypes.AnalyticsMetadataType? { - if let pinpointEndpoint = pinpointEndpoint { + if let pinpointEndpoint { return .init(analyticsEndpointId: pinpointEndpoint) } return nil diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalyticsBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalyticsBehavior.swift index c8ceddf5a0..53a6d68006 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalyticsBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalyticsBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation protocol UserPoolAnalyticsBehavior { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/AuthConfiguration.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/AuthConfiguration.swift index ce3d08e37d..4775198989 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/AuthConfiguration.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/AuthConfiguration.swift @@ -43,8 +43,10 @@ extension AuthConfiguration: Codable { guard userConfigData != nil || idpConfigData != nil else { throw DecodingError.dataCorrupted( - DecodingError.Context(codingPath: values.codingPath, - debugDescription: "Unable to decode") + DecodingError.Context( + codingPath: values.codingPath, + debugDescription: "Unable to decode" + ) ) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/DeviceMetadata.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/DeviceMetadata.swift index 42ac10651c..56141cfebc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/DeviceMetadata.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/DeviceMetadata.swift @@ -19,9 +19,11 @@ enum DeviceMetadata { let deviceGroupKey: String let deviceSecret: String - init(deviceKey: String, - deviceGroupKey: String, - deviceSecret: String = UUID().uuidString) { + init( + deviceKey: String, + deviceGroupKey: String, + deviceSecret: String = UUID().uuidString + ) { self.deviceKey = deviceKey self.deviceGroupKey = deviceGroupKey self.deviceSecret = deviceSecret @@ -59,13 +61,14 @@ extension DeviceMetadata: CustomDebugStringConvertible { extension CognitoIdentityProviderClientTypes.AuthenticationResultType { var deviceMetadata: DeviceMetadata { - if let newDeviceMetadata = newDeviceMetadata, + if let newDeviceMetadata, let deviceKey = newDeviceMetadata.deviceKey, let deviceGroupKey = newDeviceMetadata.deviceGroupKey { let data = DeviceMetadata.Data( deviceKey: deviceKey, - deviceGroupKey: deviceGroupKey) + deviceGroupKey: deviceGroupKey + ) return .metadata(data) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/FederatedToken.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/FederatedToken.swift index 03d15cb9f2..fd75c7a9ab 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/FederatedToken.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/FederatedToken.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct FederatedToken { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIConfigurationData.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIConfigurationData.swift index 4c62415442..c342ca8dca 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIConfigurationData.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIConfigurationData.swift @@ -18,9 +18,11 @@ struct HostedUIConfigurationData: Equatable { // OAuth related information let oauth: OAuthConfigurationData - init(clientId: String, - oauth: OAuthConfigurationData, - clientSecret: String? = nil) { + init( + clientId: String, + oauth: OAuthConfigurationData, + clientSecret: String? = nil + ) { self.clientId = clientId self.oauth = oauth self.clientSecret = clientSecret diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIOptions.swift index 9f0d0b3f28..7ef648ebdf 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIOptions.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct HostedUIOptions { @@ -32,10 +32,10 @@ extension HostedUIOptions: Codable { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - scopes = try values.decode(Array.self, forKey: .scopes) - providerInfo = try values.decode(HostedUIProviderInfo.self, forKey: .providerInfo) - preferPrivateSession = try values.decode(Bool.self, forKey: .preferPrivateSession) - presentationAnchor = nil + self.scopes = try values.decode(Array.self, forKey: .scopes) + self.providerInfo = try values.decode(HostedUIProviderInfo.self, forKey: .providerInfo) + self.preferPrivateSession = try values.decode(Bool.self, forKey: .preferPrivateSession) + self.presentationAnchor = nil } func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIProviderInfo.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIProviderInfo.swift index 799be98f7b..ba4bc4db20 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIProviderInfo.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIProviderInfo.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct HostedUIProviderInfo: Equatable { @@ -24,8 +24,8 @@ extension HostedUIProviderInfo: Codable { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - idpIdentifier = try values.decodeIfPresent(String.self, forKey: .idpIdentifier) - authProvider = nil + self.idpIdentifier = try values.decodeIfPresent(String.self, forKey: .idpIdentifier) + self.authProvider = nil } func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift index c8a5297f86..71bfc036eb 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoIdentityProvider +import Foundation struct RespondToAuthChallenge: Equatable { @@ -24,10 +24,12 @@ struct RespondToAuthChallenge: Equatable { extension RespondToAuthChallenge { var codeDeliveryDetails: AuthCodeDeliveryDetails { - guard let parameters = parameters, + guard let parameters, let medium = parameters["CODE_DELIVERY_DELIVERY_MEDIUM"] else { - return AuthCodeDeliveryDetails(destination: .unknown(nil), - attributeKey: nil) + return AuthCodeDeliveryDetails( + destination: .unknown(nil), + attributeKey: nil + ) } var deliveryDestination = DeliveryDestination.unknown(nil) @@ -35,8 +37,10 @@ extension RespondToAuthChallenge { if medium == "SMS" { deliveryDestination = .sms(destination) } - return AuthCodeDeliveryDetails(destination: deliveryDestination, - attributeKey: nil) + return AuthCodeDeliveryDetails( + destination: deliveryDestination, + attributeKey: nil + ) } var getAllowedMFATypesForSelection: Set { @@ -51,8 +55,8 @@ extension RespondToAuthChallenge { private func getMFATypes(forKey key: String) -> Set { guard let mfaTypeParameters = parameters?[key], let mfaTypesArray = try? JSONDecoder().decode( - [String].self, - from: Data(mfaTypeParameters.utf8) + [String].self, + from: Data(mfaTypeParameters.utf8) ) else { return .init() } @@ -61,8 +65,10 @@ extension RespondToAuthChallenge { } var debugDictionary: [String: Any] { - return ["challenge": challenge, - "username": username.masked()] + return [ + "challenge": challenge, + "username": username.masked() + ] } func getChallengeKey() throws -> String { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignInEventData.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignInEventData.swift index dad365c91d..505e6fe033 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignInEventData.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignInEventData.swift @@ -15,10 +15,12 @@ struct SignInEventData { let signInMethod: SignInMethod - init(username: String?, - password: String?, - clientMetadata: [String: String] = [:], - signInMethod: SignInMethod) { + init( + username: String?, + password: String?, + clientMetadata: [String: String] = [:], + signInMethod: SignInMethod + ) { self.username = username self.password = password self.clientMetadata = clientMetadata diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignOutEventData.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignOutEventData.swift index 1dbdbfcac2..85d5a4209a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignOutEventData.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignOutEventData.swift @@ -43,8 +43,8 @@ extension SignOutEventData: Codable { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - globalSignOut = try values.decode(Bool.self, forKey: .globalSignOut) - presentationAnchor = nil + self.globalSignOut = try values.decode(Bool.self, forKey: .globalSignOut) + self.presentationAnchor = nil } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignedInData.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignedInData.swift index da3dc0bf02..b75f93085e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignedInData.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignedInData.swift @@ -15,10 +15,11 @@ struct SignedInData { let deviceMetadata: DeviceMetadata let cognitoUserPoolTokens: AWSCognitoUserPoolTokens - init(signedInDate: Date, - signInMethod: SignInMethod, - deviceMetadata: DeviceMetadata = .noData, - cognitoUserPoolTokens: AWSCognitoUserPoolTokens + init( + signedInDate: Date, + signInMethod: SignInMethod, + deviceMetadata: DeviceMetadata = .noData, + cognitoUserPoolTokens: AWSCognitoUserPoolTokens ) { let user = try? TokenParserHelper.getAuthUser(accessToken: cognitoUserPoolTokens.accessToken) self.userId = user?.userId ?? "unknown" diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/AuthorizationError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/AuthorizationError.swift index 249c189781..b65b7af350 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/AuthorizationError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/AuthorizationError.swift @@ -25,7 +25,8 @@ extension AuthorizationError: AuthErrorConvertible { return .sessionExpired( "Session expired", "Invoke Auth.signIn to re-authenticate the user", - error) + error + ) case .configuration(let message): return .configuration(message, "") case .service(let error): @@ -35,7 +36,8 @@ extension AuthorizationError: AuthErrorConvertible { return .service( "Service error occurred", AmplifyErrorMessages.reportBugToAWS(), - error) + error + ) } case .invalidState(let message): return .invalidState(message, AuthPluginErrorConstants.invalidStateError, nil) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/FetchSessionError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/FetchSessionError.swift index 72e3857a8a..692ff4a4e8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/FetchSessionError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/FetchSessionError.swift @@ -55,18 +55,21 @@ extension FetchSessionError: AuthErrorConvertible { case .noIdentityPool: return .configuration( "No identity pool configuration found", - AuthPluginErrorConstants.configurationError) + AuthPluginErrorConstants.configurationError + ) case .noUserPool: return .configuration( "No user pool configuration found", - AuthPluginErrorConstants.configurationError) + AuthPluginErrorConstants.configurationError + ) case .invalidTokens: return .unknown( "Invalid tokens received when refreshing session") case .notAuthorized: return .notAuthorized( "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) + AuthPluginErrorConstants.notAuthorizedError + ) case .invalidIdentityID: return .unknown("Invalid identity id received when fetching session") case .invalidAWSCredentials: @@ -74,7 +77,8 @@ extension FetchSessionError: AuthErrorConvertible { case .noCredentialsToRefresh: return .service( "No credentials found to refresh", - AmplifyErrorMessages.reportBugToAWS()) + AmplifyErrorMessages.reportBugToAWS() + ) case .federationNotSupportedDuringRefresh: return .unknown( "Refreshing credentials from federationToIdentityPool is not supported \(AmplifyErrorMessages.reportBugToAWS())") @@ -85,7 +89,8 @@ extension FetchSessionError: AuthErrorConvertible { return .service( "Service error occurred", AmplifyErrorMessages.reportBugToAWS(), - error) + error + ) } } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/SignOutError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/SignOutError.swift index 7aaff48375..b3ece1f910 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/SignOutError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/SignOutError.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation enum SignOutError: Error { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/AuthEvents.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/AuthEvents.swift index ac3b2bb595..6350703e76 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/AuthEvents.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/AuthEvents.swift @@ -44,9 +44,11 @@ struct AuthEvent: StateMachineEvent { } } - init(id: String = UUID().uuidString, - eventType: EventType, - time: Date? = Date()) { + init( + id: String = UUID().uuidString, + eventType: EventType, + time: Date? = Date() + ) { self.id = id self.eventType = eventType self.time = time diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/CredentialStoreEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/CredentialStoreEvent.swift index 28522a3b3a..323f142dd7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/CredentialStoreEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/CredentialStoreEvent.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation enum CredentialStoreData: Codable, Equatable { case amplifyCredentials(AmplifyCredentials) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/DeleteUserEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/DeleteUserEvent.swift index 728deb5c30..2187054962 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/DeleteUserEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/DeleteUserEvent.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation typealias AccessToken = String @@ -41,9 +41,11 @@ struct DeleteUserEvent: StateMachineEvent { } } - init(id: String = UUID().uuidString, - eventType: EventType, - time: Date? = nil) { + init( + id: String = UUID().uuidString, + eventType: EventType, + time: Date? = nil + ) { self.id = id self.eventType = eventType self.time = time diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SetUpTOTPEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SetUpTOTPEvent.swift index 387262e785..186454befc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SetUpTOTPEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SetUpTOTPEvent.swift @@ -43,9 +43,11 @@ struct SetUpTOTPEvent: StateMachineEvent { } } - init(id: String = UUID().uuidString, - eventType: EventType, - time: Date? = nil) { + init( + id: String = UUID().uuidString, + eventType: EventType, + time: Date? = nil + ) { self.id = id self.eventType = eventType self.time = time diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInChallengeEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInChallengeEvent.swift index c85b03bf22..b45e12b3e1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInChallengeEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInChallengeEvent.swift @@ -34,9 +34,11 @@ struct SignInChallengeEvent: StateMachineEvent { } } - init(id: String = UUID().uuidString, - eventType: EventType, - time: Date? = nil) { + init( + id: String = UUID().uuidString, + eventType: EventType, + time: Date? = nil + ) { self.id = id self.eventType = eventType self.time = time diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInEvent.swift index 6733421a1f..97faac9dd8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInEvent.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation typealias Username = String typealias Password = String @@ -82,9 +82,11 @@ struct SignInEvent: StateMachineEvent { } } - init(id: String = UUID().uuidString, - eventType: EventType, - time: Date? = nil) { + init( + id: String = UUID().uuidString, + eventType: EventType, + time: Date? = nil + ) { self.id = id self.eventType = eventType self.time = time diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignOutEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignOutEvent.swift index 3d223e5a7a..85475dc293 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignOutEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignOutEvent.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation struct SignOutEvent: StateMachineEvent { var data: Any? @@ -14,30 +14,37 @@ struct SignOutEvent: StateMachineEvent { enum EventType { case signOutGlobally( SignedInData, - hostedUIError: AWSCognitoHostedUIError? = nil) + hostedUIError: AWSCognitoHostedUIError? = nil + ) case revokeToken( SignedInData, hostedUIError: AWSCognitoHostedUIError? = nil, - globalSignOutError: AWSCognitoGlobalSignOutError? = nil) + globalSignOutError: AWSCognitoGlobalSignOutError? = nil + ) case signOutLocally( SignedInData, hostedUIError: AWSCognitoHostedUIError? = nil, globalSignOutError: AWSCognitoGlobalSignOutError? = nil, - revokeTokenError: AWSCognitoRevokeTokenError? = nil) + revokeTokenError: AWSCognitoRevokeTokenError? = nil + ) case signOutGuest case invokeHostedUISignOut(SignOutEventData, SignedInData) - case signedOutSuccess(hostedUIError: AWSCognitoHostedUIError? = nil, - globalSignOutError: AWSCognitoGlobalSignOutError? = nil, - revokeTokenError: AWSCognitoRevokeTokenError? = nil) + case signedOutSuccess( + hostedUIError: AWSCognitoHostedUIError? = nil, + globalSignOutError: AWSCognitoGlobalSignOutError? = nil, + revokeTokenError: AWSCognitoRevokeTokenError? = nil + ) - case globalSignOutError(SignedInData, - globalSignOutError: AWSCognitoGlobalSignOutError, - hostedUIError: AWSCognitoHostedUIError? = nil) + case globalSignOutError( + SignedInData, + globalSignOutError: AWSCognitoGlobalSignOutError, + hostedUIError: AWSCognitoHostedUIError? = nil + ) case signedOutFailure(AuthenticationError) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/AuthorizationState.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/AuthorizationState.swift index e68f8fbce1..7dc4b5bf32 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/AuthorizationState.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/AuthorizationState.swift @@ -20,12 +20,15 @@ enum AuthorizationState: State { case federatingToIdentityPool( FetchAuthSessionState, FederatedToken, - existingCredentials: AmplifyCredentials) + existingCredentials: AmplifyCredentials + ) case fetchingUnAuthSession(FetchAuthSessionState) - case fetchingAuthSessionWithUserPool(FetchAuthSessionState, - SignedInData) + case fetchingAuthSessionWithUserPool( + FetchAuthSessionState, + SignedInData + ) case refreshingSession(existingCredentials: AmplifyCredentials, RefreshSessionState) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/CredentialStoreState.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/CredentialStoreState.swift index febd203c0b..fb6847a8cc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/CredentialStoreState.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/CredentialStoreState.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation enum CredentialStoreState: State { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthState+Debug.swift index 56a8c92f92..3235f0cdf3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthState+Debug.swift @@ -11,23 +11,21 @@ extension AuthState: CustomDebugStringConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notConfigured: - additionalMetadataDictionary = [:] + [:] case .configuringAuth: - additionalMetadataDictionary = [:] + [:] case .configuringAuthentication(let authenticationState): - additionalMetadataDictionary = authenticationState.debugDictionary + authenticationState.debugDictionary case .validatingCredentialsAndConfiguration: - additionalMetadataDictionary = [:] + [:] case .configuringAuthorization(let authenticationState, let authorizationState): - additionalMetadataDictionary = authenticationState.debugDictionary.merging( + authenticationState.debugDictionary.merging( authorizationState.debugDictionary, uniquingKeysWith: {$1} ) case .configured(let authenticationState, let authorizationState): - additionalMetadataDictionary = authenticationState.debugDictionary.merging( + authenticationState.debugDictionary.merging( authorizationState.debugDictionary, uniquingKeysWith: {$1} ) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthenticationState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthenticationState+Debug.swift index 451f8e36b5..37737259e0 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthenticationState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthenticationState+Debug.swift @@ -8,34 +8,33 @@ extension AuthenticationState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notConfigured: - additionalMetadataDictionary = [:] + [:] case .configured: - additionalMetadataDictionary = [:] + [:] case .signingOut(let signOutState): - additionalMetadataDictionary = signOutState.debugDictionary + signOutState.debugDictionary case .signedOut(let signedOutData): - additionalMetadataDictionary = signedOutData.debugDictionary + signedOutData.debugDictionary case .signingIn(let signInState): - additionalMetadataDictionary = signInState.debugDictionary + signInState.debugDictionary case .signedIn(let signedInData): - additionalMetadataDictionary = signedInData.debugDictionary + signedInData.debugDictionary case .federatedToIdentityPool, .clearingFederation, .federatingToIdentityPool: - additionalMetadataDictionary = [:] + [:] case .deletingUser(_, let deleteUserState): - additionalMetadataDictionary = deleteUserState.debugDictionary + deleteUserState.debugDictionary case .error(let error): - additionalMetadataDictionary = [ + [ "Error": error ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthorizationState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthorizationState+Debug.swift index d66207a120..5a298c0c5a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthorizationState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthorizationState+Debug.swift @@ -19,8 +19,10 @@ extension AuthorizationState: CustomDebugDictionaryConvertible { .deletingUser: additionalMetadataDictionary = [:] case .refreshingSession(existingCredentials: let credentials, let state): - additionalMetadataDictionary = ["existing": credentials.debugDescription, - "refreshState": state.debugDictionary] + additionalMetadataDictionary = [ + "existing": credentials.debugDescription, + "refreshState": state.debugDictionary + ] case .fetchingUnAuthSession(let state), .fetchingAuthSessionWithUserPool(let state, _), .federatingToIdentityPool(let state, _, _): diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CredentialStoreState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CredentialStoreState+Debug.swift index 4b9eb908af..b4a63e689e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CredentialStoreState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CredentialStoreState+Debug.swift @@ -9,26 +9,24 @@ import Foundation extension CredentialStoreState: CustomDebugStringConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notConfigured, .migratingLegacyStore, .loadingStoredCredentials, .storingCredentials, .clearingCredentials, .idle: - additionalMetadataDictionary = [:] + [:] case .clearedCredential(let dataType): - additionalMetadataDictionary = [ + [ "clearedDataType": dataType ] case .success(let data): - additionalMetadataDictionary = [ + [ "savedData": data ] case .error(let error): - additionalMetadataDictionary = [ + [ "errorType": error ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CustomSignInState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CustomSignInState+Debug.swift index 316bf2daa2..6267589485 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CustomSignInState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CustomSignInState+Debug.swift @@ -11,16 +11,15 @@ extension CustomSignInState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .initiating(let signInEventData): - additionalMetadataDictionary = signInEventData.debugDictionary + signInEventData.debugDictionary case .signedIn(let signedInData): - additionalMetadataDictionary = signedInData.debugDictionary + signedInData.debugDictionary case .error(let error): - additionalMetadataDictionary = [ + [ "Error": error ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeleteUserState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeleteUserState+Debug.swift index f2a0c1dc88..5a983348da 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeleteUserState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeleteUserState+Debug.swift @@ -8,18 +8,17 @@ extension DeleteUserState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .deletingUser: - additionalMetadataDictionary = [:] + [:] case .signingOut(let signedOutState): - additionalMetadataDictionary = signedOutState.debugDictionary + signedOutState.debugDictionary case .userDeleted: - additionalMetadataDictionary = [:] + [:] case .error(let error): - additionalMetadataDictionary = [ + [ "Error": error ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeviceSRPState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeviceSRPState+Debug.swift index 3b0e80913d..4adb72c240 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeviceSRPState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeviceSRPState+Debug.swift @@ -11,20 +11,19 @@ extension DeviceSRPState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .initiatingDeviceSRP: - additionalMetadataDictionary = [:] + [:] case .cancelling: - additionalMetadataDictionary = [:] + [:] case .respondingDevicePasswordVerifier(let srpStateData): - additionalMetadataDictionary = srpStateData.debugDictionary + srpStateData.debugDictionary case .signedIn(let signedInData): - additionalMetadataDictionary = signedInData.debugDictionary + signedInData.debugDictionary case .error(let error): - additionalMetadataDictionary = [ + [ "Error": error ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/FetchAuthSessionState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/FetchAuthSessionState+Debug.swift index 57c7f9646a..415d478e80 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/FetchAuthSessionState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/FetchAuthSessionState+Debug.swift @@ -10,18 +10,17 @@ import Foundation extension FetchAuthSessionState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .fetchingIdentityID: - additionalMetadataDictionary = [:] + [:] case .fetchingAWSCredentials: - additionalMetadataDictionary = [:] + [:] case .fetched: - additionalMetadataDictionary = [:] + [:] case .error(let error): - additionalMetadataDictionary = ["error": error] + ["error": error] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/HostedUISignInState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/HostedUISignInState+Debug.swift index 82b14798f7..b5bdd699ec 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/HostedUISignInState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/HostedUISignInState+Debug.swift @@ -8,14 +8,13 @@ extension HostedUISignInState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .error(let error): - additionalMetadataDictionary = ["error": error] + ["error": error] default: - additionalMetadataDictionary = [:] + [:] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/MigrateSignInState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/MigrateSignInState+Debug.swift index a0df091306..df1c70da71 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/MigrateSignInState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/MigrateSignInState+Debug.swift @@ -11,18 +11,16 @@ extension MigrateSignInState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .signingIn: - additionalMetadataDictionary = [:] + [:] case .signedIn(let signedInData): - additionalMetadataDictionary = ["SignedInData": signedInData.debugDictionary] + ["SignedInData": signedInData.debugDictionary] case .error: - additionalMetadataDictionary = [:] + [:] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/RefreshSessionState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/RefreshSessionState+Debug.swift index fedc330c46..59a4c79383 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/RefreshSessionState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/RefreshSessionState+Debug.swift @@ -10,14 +10,13 @@ import Foundation extension RefreshSessionState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .fetchingAuthSessionWithUserPool(let state, _): - additionalMetadataDictionary = ["fetchingSession": state.debugDictionary] + ["fetchingSession": state.debugDictionary] case .error(let error): - additionalMetadataDictionary = ["error": error] + ["error": error] default: - additionalMetadataDictionary = [:] + [:] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SRPSignInState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SRPSignInState+Debug.swift index f61b26644b..df3cc457c3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SRPSignInState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SRPSignInState+Debug.swift @@ -11,20 +11,19 @@ extension SRPSignInState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .initiatingSRPA(let signInEventData): - additionalMetadataDictionary = signInEventData.debugDictionary + signInEventData.debugDictionary case .cancelling: - additionalMetadataDictionary = [:] + [:] case .respondingPasswordVerifier(let srpStateData): - additionalMetadataDictionary = srpStateData.debugDictionary + srpStateData.debugDictionary case .signedIn(let signedInData): - additionalMetadataDictionary = signedInData.debugDictionary + signedInData.debugDictionary case .error(let error): - additionalMetadataDictionary = [ + [ "Error": error ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInChallengeState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInChallengeState+Debug.swift index 7ded00a585..e8480bdfbd 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInChallengeState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInChallengeState+Debug.swift @@ -21,7 +21,8 @@ extension SignInChallengeState: CustomDebugDictionaryConvertible { [ "error": error ], - uniquingKeysWith: {$1}) + uniquingKeysWith: {$1} + ) default: additionalMetadataDictionary = [:] } return [type: additionalMetadataDictionary] diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInState+Debug.swift index 1cba475ba8..05fb240464 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInState+Debug.swift @@ -11,45 +11,45 @@ extension SignInState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .signingInWithSRP(let srpSignInState, let signInEventData): - additionalMetadataDictionary = srpSignInState.debugDictionary.merging( + srpSignInState.debugDictionary.merging( signInEventData.debugDictionary, uniquingKeysWith: {$1} ) case .signingInWithHostedUI(let substate): - additionalMetadataDictionary = substate.debugDictionary + substate.debugDictionary case .resolvingChallenge(let challengeState, let challengeType, let signInMethod): - additionalMetadataDictionary = challengeState.debugDictionary.merging( + challengeState.debugDictionary.merging( [ "challengeType": challengeType, "signInMethod": signInMethod ], - uniquingKeysWith: {$1}) + uniquingKeysWith: {$1} + ) case .notStarted: - additionalMetadataDictionary = [:] + [:] case .signingInWithSRPCustom(let srpstate, _): - additionalMetadataDictionary = ["SRPSignInStaet": srpstate.debugDictionary] + ["SRPSignInStaet": srpstate.debugDictionary] case .signingInWithCustom(let customSignIn, _): - additionalMetadataDictionary = ["CustomSignInState": customSignIn.debugDictionary] + ["CustomSignInState": customSignIn.debugDictionary] case .signingInViaMigrateAuth(let migrateSignInState, _): - additionalMetadataDictionary = ["MigrateSignInState": migrateSignInState.debugDictionary] + ["MigrateSignInState": migrateSignInState.debugDictionary] case .confirmingDevice: - additionalMetadataDictionary = [:] + [:] case .resolvingDeviceSrpa(let deviceSRPState): - additionalMetadataDictionary = ["DeviceSRPState": deviceSRPState.debugDictionary] + ["DeviceSRPState": deviceSRPState.debugDictionary] case .signedIn(let data): - additionalMetadataDictionary = ["SignedInData": data.debugDictionary] + ["SignedInData": data.debugDictionary] case .resolvingTOTPSetup(let signInTOTPSetupState, let signInEventData): - additionalMetadataDictionary = [ + [ "SignInTOTPSetupState": signInTOTPSetupState.debugDictionary, - "SignInEventData": signInEventData.debugDictionary] + "SignInEventData": signInEventData.debugDictionary + ] case .error: - additionalMetadataDictionary = [:] + [:] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInTOTPSetupState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInTOTPSetupState+Debug.swift index 53b796378f..7adc148cfb 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInTOTPSetupState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInTOTPSetupState+Debug.swift @@ -10,20 +10,20 @@ import Foundation extension SignInTOTPSetupState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .waitingForAnswer(let signInTOTPSetupData): - additionalMetadataDictionary = signInTOTPSetupData.debugDictionary + signInTOTPSetupData.debugDictionary case .verifying(let signInSetupData, let confirmSignInEventData): - additionalMetadataDictionary = confirmSignInEventData.debugDictionary.merging( + confirmSignInEventData.debugDictionary.merging( signInSetupData.debugDictionary, - uniquingKeysWith: {$1}) + uniquingKeysWith: {$1} + ) case .error(let data, let error): - additionalMetadataDictionary = [ + [ "totpSetupData": data ?? "Nil", "error": error ] - default: additionalMetadataDictionary = [:] + default: [:] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignOutState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignOutState+Debug.swift index f8805e88c5..9bffe49222 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignOutState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignOutState+Debug.swift @@ -11,13 +11,11 @@ extension SignOutState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .error(let error): - additionalMetadataDictionary = ["Error": error] + ["Error": error] default: - additionalMetadataDictionary = [:] + [:] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/HostedUISignInState.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/HostedUISignInState.swift index 81cea4671c..b76c2fcac7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/HostedUISignInState.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/HostedUISignInState.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation enum HostedUISignInState: State { case notStarted diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/RefreshSessionState.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/RefreshSessionState.swift index 48e816f8fc..dffbe0df61 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/RefreshSessionState.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/RefreshSessionState.swift @@ -39,8 +39,10 @@ extension RefreshSessionState: Equatable { (.refreshed, .refreshed), (.error, .error): return true - case (.fetchingAuthSessionWithUserPool(let lhsFetchState, _), - .fetchingAuthSessionWithUserPool(let rhsFetchState, _)): + case ( + .fetchingAuthSessionWithUserPool(let lhsFetchState, _), + .fetchingAuthSessionWithUserPool(let rhsFetchState, _) + ): return lhsFetchState == rhsFetchState default: return false diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/KeychainStoreError+AuthConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/KeychainStoreError+AuthConvertible.swift index 1a37569191..c65f88ff6c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/KeychainStoreError+AuthConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/KeychainStoreError+AuthConvertible.swift @@ -5,26 +5,26 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AWSPluginsCore import Amplify +import AWSPluginsCore +import Foundation extension KeychainStoreError: AuthErrorConvertible { var authError: AuthError { switch self { case .configuration(let message): - return .configuration(message, self.recoverySuggestion) + return .configuration(message, recoverySuggestion) case .unknown(let errorDescription, let error): return .unknown(errorDescription, error) case .conversionError(let errorDescription, let error): - return .configuration(errorDescription, self.recoverySuggestion, error) + return .configuration(errorDescription, recoverySuggestion, error) case .codingError(let errorDescription, let error): - return .configuration(errorDescription, self.recoverySuggestion, error) + return .configuration(errorDescription, recoverySuggestion, error) case .itemNotFound: - return .service(self.errorDescription, self.recoverySuggestion) + return .service(errorDescription, recoverySuggestion) case .securityError: - return .service(self.errorDescription, self.recoverySuggestion) + return .service(errorDescription, recoverySuggestion) } } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift index a6e21bced9..6812413bd6 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import ClientRuntime import AWSCognitoIdentityProvider +import ClientRuntime +import Foundation extension SignInError { @@ -50,7 +50,8 @@ extension SignInError: AuthErrorConvertible { return AuthError.validation( field, AuthPluginErrorConstants.signInUsernameError.errorDescription, - AuthPluginErrorConstants.signInUsernameError.recoverySuggestion) + AuthPluginErrorConstants.signInUsernameError.recoverySuggestion + ) case .unknown(let message): return .unknown(message, nil) case .hostedUI(let error): @@ -66,54 +67,64 @@ extension HostedUIError: AuthErrorConvertible { case .signInURI: return .configuration( AuthPluginErrorConstants.hostedUISignInURI.errorDescription, - AuthPluginErrorConstants.hostedUISignInURI.recoverySuggestion) + AuthPluginErrorConstants.hostedUISignInURI.recoverySuggestion + ) case .tokenURI: return .configuration( AuthPluginErrorConstants.hostedUITokenURI.errorDescription, - AuthPluginErrorConstants.hostedUITokenURI.recoverySuggestion) + AuthPluginErrorConstants.hostedUITokenURI.recoverySuggestion + ) case .signOutURI: return .configuration( AuthPluginErrorConstants.hostedUISignOutURI.errorDescription, - AuthPluginErrorConstants.hostedUISignOutURI.recoverySuggestion) + AuthPluginErrorConstants.hostedUISignOutURI.recoverySuggestion + ) case .signOutRedirectURI: return .configuration( AuthPluginErrorConstants.hostedUISignOutRedirectURI.errorDescription, - AuthPluginErrorConstants.hostedUISignOutRedirectURI.recoverySuggestion) + AuthPluginErrorConstants.hostedUISignOutRedirectURI.recoverySuggestion + ) case .proofCalculation: return .invalidState( AuthPluginErrorConstants.hostedUIProofCalculation.errorDescription, - AuthPluginErrorConstants.hostedUIProofCalculation.recoverySuggestion) + AuthPluginErrorConstants.hostedUIProofCalculation.recoverySuggestion + ) case .codeValidation: return .service( AuthPluginErrorConstants.hostedUISecurityFailedError.errorDescription, - AuthPluginErrorConstants.hostedUISecurityFailedError.recoverySuggestion) + AuthPluginErrorConstants.hostedUISecurityFailedError.recoverySuggestion + ) case .tokenParsing: return .service( AuthPluginErrorConstants.tokenParsingError.errorDescription, - AuthPluginErrorConstants.tokenParsingError.recoverySuggestion) + AuthPluginErrorConstants.tokenParsingError.recoverySuggestion + ) case .cancelled: return .service( AuthPluginErrorConstants.hostedUIUserCancelledError.errorDescription, AuthPluginErrorConstants.hostedUIUserCancelledError.recoverySuggestion, - AWSCognitoAuthError.userCancelled) + AWSCognitoAuthError.userCancelled + ) case .invalidContext: return .invalidState( AuthPluginErrorConstants.hostedUIInvalidPresentation.errorDescription, - AuthPluginErrorConstants.hostedUIInvalidPresentation.recoverySuggestion) + AuthPluginErrorConstants.hostedUIInvalidPresentation.recoverySuggestion + ) case .unableToStartASWebAuthenticationSession: return .service( AuthPluginErrorConstants.hostedUIUnableToStartASWebAuthenticationSession.errorDescription, AuthPluginErrorConstants.hostedUIUnableToStartASWebAuthenticationSession.recoverySuggestion, - AWSCognitoAuthError.errorLoadingUI) + AWSCognitoAuthError.errorLoadingUI + ) case .serviceMessage(let message): return .service(message, AuthPluginErrorConstants.serviceError) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignUpError+Helper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignUpError+Helper.swift index 56a1644467..9868d0f4b1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignUpError+Helper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignUpError+Helper.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension SignUpError: AuthErrorConvertible { var authError: AuthError { @@ -17,12 +17,14 @@ extension SignUpError: AuthErrorConvertible { return AuthError.validation( AuthPluginErrorConstants.signUpUsernameError.field, AuthPluginErrorConstants.signUpUsernameError.errorDescription, - AuthPluginErrorConstants.signUpUsernameError.recoverySuggestion, nil) + AuthPluginErrorConstants.signUpUsernameError.recoverySuggestion, nil + ) case .invalidPassword: return AuthError.validation( AuthPluginErrorConstants.signUpPasswordError.field, AuthPluginErrorConstants.signUpPasswordError.errorDescription, - AuthPluginErrorConstants.signUpPasswordError.recoverySuggestion, nil) + AuthPluginErrorConstants.signUpPasswordError.recoverySuggestion, nil + ) case .invalidConfirmationCode(message: let message): fatalError("Fix me \(message)") case .service(error: let error): diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/AuthState/AuthState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/AuthState/AuthState+Resolver.swift index d4f9e98c6c..d263dde4f4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/AuthState/AuthState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/AuthState/AuthState+Resolver.swift @@ -32,7 +32,8 @@ extension AuthState { case .validateCredentialAndConfiguration(let authConfiguration, let credentials): let action = ValidateCredentialsAndConfiguration( authConfiguration: authConfiguration, - cachedCredentials: credentials) + cachedCredentials: credentials + ) let newState = AuthState.validatingCredentialsAndConfiguration return .init(newState: newState, actions: [action]) default: @@ -44,7 +45,8 @@ extension AuthState { let newState = AuthState.configuringAuthentication(.notConfigured) let action = InitializeAuthenticationConfiguration( configuration: authConfiguration, - storedCredentials: storedCredentials) + storedCredentials: storedCredentials + ) return .init(newState: newState, actions: [action]) case .configureAuthorization(_, let storedCredentials): let newState = AuthState.configuringAuthorization(.notConfigured, .notConfigured) @@ -71,8 +73,10 @@ extension AuthState { let authNresolution = authenticationResolver.resolve(oldState: authenticationState, byApplying: event) let authZresolution = authorizationResolver.resolve(oldState: authorizationState, byApplying: event) guard case .authorizationConfigured = isAuthEvent(event)?.eventType else { - let newState = AuthState.configuringAuthorization(authNresolution.newState, - authZresolution.newState) + let newState = AuthState.configuringAuthorization( + authNresolution.newState, + authZresolution.newState + ) return .init(newState: newState, actions: authNresolution.actions + authZresolution.actions) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authentication/AuthenticationState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authentication/AuthenticationState+Resolver.swift index d7703d9482..b9f7c77b2c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authentication/AuthenticationState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authentication/AuthenticationState+Resolver.swift @@ -36,8 +36,10 @@ extension AuthenticationState { return .from(oldState) } case .signingOut(let signOutState): - return resolveSigningOutState(byApplying: event, - to: signOutState) + return resolveSigningOutState( + byApplying: event, + to: signOutState + ) case .signedOut(let signedOutData): if let authEvent = event as? AuthenticationEvent { return resolveSignedOut( byApplying: authEvent, to: signedOutData) @@ -56,7 +58,8 @@ extension AuthenticationState { return resolveDeleteUser( byApplying: deleteUserEvent, to: .notStarted, - with: signedInData) + with: signedInData + ) } else { return .from(oldState) } @@ -68,7 +71,8 @@ extension AuthenticationState { newState: .clearingFederation, actions: [ ClearFederationToIdentityPool() - ]) + ] + ) } else if let authZEvent = event.isAuthorizationEvent, case .startFederationToIdentityPool = authZEvent { return .init(newState: .federatingToIdentityPool) @@ -114,7 +118,8 @@ extension AuthenticationState { return resolveDeleteUser( byApplying: event, to: deleteUserState, - with: signedInData) + with: signedInData + ) } case .error: @@ -130,7 +135,8 @@ extension AuthenticationState { newState: .clearingFederation, actions: [ ClearFederationToIdentityPool() - ]) + ] + ) } else { return .from(oldState) } @@ -195,8 +201,10 @@ extension AuthenticationState { ) -> StateResolution { switch authEvent.eventType { case .signOutRequested(let signOutEventData): - let action = InitiateSignOut(signedInData: currentSignedInData, - signOutEventData: signOutEventData) + let action = InitiateSignOut( + signedInData: currentSignedInData, + signOutEventData: signOutEventData + ) let signOutState = SignOutState.notStarted let resolution = StateResolution( newState: AuthenticationState.signingOut(signOutState), @@ -207,7 +215,8 @@ extension AuthenticationState { case .cancelSignIn: let action = InitiateSignOut( signedInData: currentSignedInData, - signOutEventData: .init(globalSignOut: false)) + signOutEventData: .init(globalSignOut: false) + ) let signOutState = SignOutState.notStarted let resolution = StateResolution( newState: AuthenticationState.signingOut(signOutState), @@ -222,15 +231,18 @@ extension AuthenticationState { private func resolveDeleteUser( byApplying deleteUserEvent: StateMachineEvent, to oldState: DeleteUserState, - with signedInData: SignedInData) -> StateResolution { + with signedInData: SignedInData + ) -> StateResolution { let resolver = DeleteUserState.Resolver(signedInData: signedInData) let resolution = resolver.resolve(oldState: oldState, byApplying: deleteUserEvent) let newState = AuthenticationState.deletingUser(signedInData, resolution.newState) return .init(newState: newState, actions: resolution.actions) } - private func resolveSigningInState(oldState: AuthenticationState, - event: StateMachineEvent) -> StateResolution { + private func resolveSigningInState( + oldState: AuthenticationState, + event: StateMachineEvent + ) -> StateResolution { if let authEvent = event as? AuthenticationEvent, case .error(let error) = authEvent.eventType { return .init(newState: .error(error)) @@ -252,8 +264,10 @@ extension AuthenticationState { return .init(newState: .signedIn(signedInData)) } - let resolution = SignInState.Resolver().resolve(oldState: signInState, - byApplying: event) + let resolution = SignInState.Resolver().resolve( + oldState: signInState, + byApplying: event + ) return .init(newState: .signingIn(resolution.newState), actions: resolution.actions) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authorization/AuthorizationState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authorization/AuthorizationState+Resolver.swift index 51be1d9500..d7ca1f27ea 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authorization/AuthorizationState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authorization/AuthorizationState+Resolver.swift @@ -29,7 +29,8 @@ extension AuthorizationState { signedInData: signedInData) return .init( newState: .fetchingAuthSessionWithUserPool(.notStarted, signedInData), - actions: [action]) + actions: [action] + ) case .error(let error): return .init(newState: .error(AuthorizationError.service(error: error))) case .cancelSignIn: @@ -53,17 +54,21 @@ extension AuthorizationState { } if case .startFederationToIdentityPool( - let federatedToken, let identityId) = event.isAuthorizationEvent { + let federatedToken, let identityId + ) = event.isAuthorizationEvent { let action = InitializeFederationToIdentityPool( federatedToken: federatedToken, - developerProvidedIdentityId: identityId) + developerProvidedIdentityId: identityId + ) return .init( newState: .federatingToIdentityPool( .notStarted, federatedToken, - existingCredentials: .noCredentials), - actions: [action]) + existingCredentials: .noCredentials + ), + actions: [action] + ) } return .from(oldState) @@ -81,23 +86,28 @@ extension AuthorizationState { let action = InitializeFederationToIdentityPool( federatedToken: federatedToken, - developerProvidedIdentityId: identityId) + developerProvidedIdentityId: identityId + ) return .init( newState: .federatingToIdentityPool( .notStarted, federatedToken, - existingCredentials: credentials), - actions: [action]) + existingCredentials: credentials + ), + actions: [action] + ) } if case .refreshSession(let forceRefresh) = event.isAuthorizationEvent { let action = InitializeRefreshSession( existingCredentials: credentials, - isForceRefresh: forceRefresh) + isForceRefresh: forceRefresh + ) let subState = RefreshSessionState.notStarted return .init(newState: .refreshingSession( existingCredentials: credentials, - subState), actions: [action]) + subState + ), actions: [action]) } if case .deleteUser = event.isDeleteUserEvent { @@ -107,17 +117,23 @@ extension AuthorizationState { return .from(oldState) case .federatingToIdentityPool( - let fetchSessionState, let federatedToken, let credentials): + let fetchSessionState, let federatedToken, let credentials + ): - if case .fetched(let identityID, - let credentials) = event.isAuthorizationEvent { + if case .fetched( + let identityID, + let credentials + ) = event.isAuthorizationEvent { let amplifyCredentials = AmplifyCredentials.identityPoolWithFederation( federatedToken: federatedToken, identityID: identityID, - credentials: credentials) + credentials: credentials + ) let action = PersistCredentials(credentials: amplifyCredentials) - return .init(newState: .storingCredentials(amplifyCredentials), - actions: [action]) + return .init( + newState: .storingCredentials(amplifyCredentials), + actions: [action] + ) } if case .receivedSessionError(let error) = event.isAuthorizationEvent { @@ -134,8 +150,10 @@ extension AuthorizationState { newState: .federatingToIdentityPool( resolution.newState, federatedToken, - existingCredentials: credentials), - actions: resolution.actions) + existingCredentials: credentials + ), + actions: resolution.actions + ) case .signingOut(let credentials): if let signOutEvent = event.isSignOutEvent, @@ -144,7 +162,7 @@ extension AuthorizationState { } if let authenEvent = event.isAuthenticationEvent, case .cancelSignOut = authenEvent { - if let credentials = credentials { + if let credentials { return .init(newState: .sessionEstablished(credentials)) } else { return .init(newState: .configured) @@ -164,14 +182,19 @@ extension AuthorizationState { case .fetchingUnAuthSession(let fetchSessionState): - if case .fetched(let identityID, - let credentials) = event.isAuthorizationEvent { + if case .fetched( + let identityID, + let credentials + ) = event.isAuthorizationEvent { let amplifyCredentials = AmplifyCredentials.identityPoolOnly( identityID: identityID, - credentials: credentials) + credentials: credentials + ) let action = PersistCredentials(credentials: amplifyCredentials) - return .init(newState: .storingCredentials(amplifyCredentials), - actions: [action]) + return .init( + newState: .storingCredentials(amplifyCredentials), + actions: [action] + ) } if case .receivedSessionError(let error) = event.isAuthorizationEvent { @@ -184,31 +207,41 @@ extension AuthorizationState { let resolver = FetchAuthSessionState.Resolver() let resolution = resolver.resolve(oldState: fetchSessionState, byApplying: event) - return .init(newState: .fetchingUnAuthSession(resolution.newState), - actions: resolution.actions) + return .init( + newState: .fetchingUnAuthSession(resolution.newState), + actions: resolution.actions + ) case .fetchingAuthSessionWithUserPool(let fetchSessionState, let signedInData): - if case .fetched(let identityID, - let credentials) = event.isAuthorizationEvent { + if case .fetched( + let identityID, + let credentials + ) = event.isAuthorizationEvent { let amplifyCredentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: signedInData, identityID: identityID, - credentials: credentials) + credentials: credentials + ) let action = PersistCredentials(credentials: amplifyCredentials) - return .init(newState: .storingCredentials(amplifyCredentials), - actions: [action]) + return .init( + newState: .storingCredentials(amplifyCredentials), + actions: [action] + ) } else if case .receivedSessionError(let fetchError) = event.isAuthorizationEvent { let amplifyCredentials = AmplifyCredentials.userPoolOnly( signedInData: signedInData) if case .noIdentityPool = fetchError { let action = PersistCredentials(credentials: amplifyCredentials) - return .init(newState: .storingCredentials(amplifyCredentials), - actions: [action]) + return .init( + newState: .storingCredentials(amplifyCredentials), + actions: [action] + ) } let authorizationError = AuthorizationError.sessionError( fetchError, - amplifyCredentials) + amplifyCredentials + ) return .init(newState: .error(authorizationError)) } else if case .throwError(let error) = event.isAuthorizationEvent { @@ -216,20 +249,25 @@ extension AuthorizationState { signedInData: signedInData) let authorizationError = AuthorizationError.sessionError( .service(error), - amplifyCredentials) + amplifyCredentials + ) return .init(newState: .error(authorizationError)) } let resolver = FetchAuthSessionState.Resolver() let resolution = resolver.resolve(oldState: fetchSessionState, byApplying: event) - return .init(newState: .fetchingAuthSessionWithUserPool(resolution.newState, signedInData), - actions: resolution.actions) + return .init( + newState: .fetchingAuthSessionWithUserPool(resolution.newState, signedInData), + actions: resolution.actions + ) case .refreshingSession(let existingCredentials, let refreshState): if case .refreshed(let amplifyCredentials) = event.isAuthorizationEvent { let action = PersistCredentials(credentials: amplifyCredentials) - return .init(newState: .storingCredentials(amplifyCredentials), - actions: [action]) + return .init( + newState: .storingCredentials(amplifyCredentials), + actions: [action] + ) } if case .receivedSessionError(let error) = event.isAuthorizationEvent { @@ -243,7 +281,8 @@ extension AuthorizationState { let resolution = resolver.resolve(oldState: refreshState, byApplying: event) return .init(newState: .refreshingSession( existingCredentials: existingCredentials, - resolution.newState), actions: resolution.actions) + resolution.newState + ), actions: resolution.actions) case .storingCredentials: if case .sessionEstablished(let credentials) = event.isAuthorizationEvent { @@ -287,13 +326,16 @@ extension AuthorizationState { let action = InitializeFederationToIdentityPool( federatedToken: federatedToken, - developerProvidedIdentityId: identityId) + developerProvidedIdentityId: identityId + ) return .init( newState: .federatingToIdentityPool( .notStarted, federatedToken, - existingCredentials: existingCredentials), - actions: [action]) + existingCredentials: existingCredentials + ), + actions: [action] + ) } // If authorization is under session error, we try to refresh it again to see if @@ -302,11 +344,13 @@ extension AuthorizationState { case .sessionError(_, let credentials) = error { let action = InitializeRefreshSession( existingCredentials: credentials, - isForceRefresh: forceRefresh) + isForceRefresh: forceRefresh + ) let subState = RefreshSessionState.notStarted return .init(newState: .refreshingSession( existingCredentials: credentials, - subState), actions: [action]) + subState + ), actions: [action]) } return .from(oldState) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/CustomAuth/CustomSignInState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/CustomAuth/CustomSignInState+Resolver.swift index 370524c44f..827a677e8b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/CustomAuth/CustomSignInState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/CustomAuth/CustomSignInState+Resolver.swift @@ -50,7 +50,8 @@ extension CustomSignInState { let action = InitiateCustomAuth( username: username, clientMetadata: signInEventData.clientMetadata, - deviceMetadata: deviceMetadata) + deviceMetadata: deviceMetadata + ) return StateResolution( newState: CustomSignInState.initiating(signInEventData), actions: [action] @@ -62,11 +63,14 @@ extension CustomSignInState { private func resolveInitiating( from oldState: CustomSignInState, - byApplying signInEvent: SignInEvent) -> StateResolution { + byApplying signInEvent: SignInEvent + ) -> StateResolution { switch signInEvent.eventType { case .finalizeSignIn(let signedInData): - return .init(newState: .signedIn(signedInData), - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .signedIn(signedInData), + actions: [SignInComplete(signedInData: signedInData)] + ) default: return .from(oldState) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/DeleteUser/DeleteUserState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/DeleteUser/DeleteUserState+Resolver.swift index 34e5ad0f7b..e27ca8e1ac 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/DeleteUser/DeleteUserState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/DeleteUser/DeleteUserState+Resolver.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension DeleteUserState { @@ -16,8 +16,10 @@ extension DeleteUserState { let signedInData: SignedInData - func resolve(oldState: DeleteUserState, - byApplying event: StateMachineEvent) -> StateResolution { + func resolve( + oldState: DeleteUserState, + byApplying event: StateMachineEvent + ) -> StateResolution { switch oldState { @@ -70,7 +72,7 @@ extension DeleteUserState { let resolution = resolver.resolve(oldState: signOutState, byApplying: event) switch resolution.newState { case .signedOut(let signedOutData): - let action = InformUserDeletedAndSignedOut(result: .success((signedOutData))) + let action = InformUserDeletedAndSignedOut(result: .success(signedOutData)) let newState = DeleteUserState.userDeleted(signedOutData) var resolutionActions = resolution.actions resolutionActions.append(action) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/FetchAuthSession/FetchAuthSessionState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/FetchAuthSession/FetchAuthSessionState+Resolver.swift index f0d2ddeba9..6956202404 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/FetchAuthSession/FetchAuthSessionState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/FetchAuthSession/FetchAuthSessionState+Resolver.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AWSPluginsCore import Amplify +import AWSPluginsCore +import Foundation extension FetchAuthSessionState { @@ -15,8 +15,10 @@ extension FetchAuthSessionState { var defaultState: FetchAuthSessionState = .notStarted - func resolve(oldState: FetchAuthSessionState, - byApplying event: StateMachineEvent) + func resolve( + oldState: FetchAuthSessionState, + byApplying event: StateMachineEvent + ) -> StateResolution { guard let eventType = isFetchAuthSessionEvent(event)?.eventType else { @@ -28,22 +30,31 @@ extension FetchAuthSessionState { switch eventType { case .fetchUnAuthIdentityID: - return .init(newState: .fetchingIdentityID(UnAuthLoginsMapProvider()), - actions: [FetchAuthIdentityId()]) + return .init( + newState: .fetchingIdentityID(UnAuthLoginsMapProvider()), + actions: [FetchAuthIdentityId()] + ) case .fetchAuthenticatedIdentityID(let provider): - return .init(newState: .fetchingIdentityID(provider), - actions: [FetchAuthIdentityId(loginsMap: provider.loginsMap)]) + return .init( + newState: .fetchingIdentityID(provider), + actions: [FetchAuthIdentityId(loginsMap: provider.loginsMap)] + ) case .fetchAWSCredentials(let identityId, let loginsMapProvider): let action = FetchAuthAWSCredentials( loginsMap: loginsMapProvider.loginsMap, - identityID: identityId) - return .init(newState: .fetchingAWSCredentials(identityId, loginsMapProvider), - actions: [action]) + identityID: identityId + ) + return .init( + newState: .fetchingAWSCredentials(identityId, loginsMapProvider), + actions: [action] + ) case .throwError(let error): - return .init(newState: .error(error), - actions: [InformSessionError(error: error)]) + return .init( + newState: .error(error), + actions: [InformSessionError(error: error)] + ) default: return .from(oldState) } @@ -54,9 +65,12 @@ extension FetchAuthSessionState { case .fetchedIdentityID(let identityID): let action = FetchAuthAWSCredentials( loginsMap: loginsMapProvider.loginsMap, - identityID: identityID) - return .init(newState: .fetchingAWSCredentials(identityID, loginsMapProvider), - actions: [action]) + identityID: identityID + ) + return .init( + newState: .fetchingAWSCredentials(identityID, loginsMapProvider), + actions: [action] + ) case .throwError(let error): let action = InformSessionError(error: error) return .init(newState: .error(error), actions: [action]) @@ -70,7 +84,8 @@ extension FetchAuthSessionState { case .fetchedAWSCredentials(let identityID, let credentials): let action = InformSessionFetched( identityID: identityID, - credentials: credentials) + credentials: credentials + ) return .init(newState: .fetched(identityID, credentials), actions: [action]) case .throwError(let error): let action = InformSessionError(error: error) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/MigrateAuth/MigrateSignInState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/MigrateAuth/MigrateSignInState+Resolver.swift index 21e4ef5f70..ac4ec340b8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/MigrateAuth/MigrateSignInState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/MigrateAuth/MigrateSignInState+Resolver.swift @@ -49,7 +49,8 @@ extension MigrateSignInState { return errorStateWithCancelSignIn(error) } guard let password = signInEventData.password, - !password.isEmpty else { + !password.isEmpty + else { let error = SignInError.inputValidation( field: AuthPluginErrorConstants.signInPasswordError.field ) @@ -59,7 +60,8 @@ extension MigrateSignInState { username: username, password: password, clientMetadata: signInEventData.clientMetadata, - deviceMetadata: deviceMetadata) + deviceMetadata: deviceMetadata + ) return StateResolution( newState: MigrateSignInState.signingIn(signInEventData), actions: [action] @@ -71,11 +73,14 @@ extension MigrateSignInState { private func resolveInitiating( from oldState: MigrateSignInState, - byApplying signInEvent: SignInEvent) -> StateResolution { + byApplying signInEvent: SignInEvent + ) -> StateResolution { switch signInEvent.eventType { case .finalizeSignIn(let signedInData): - return .init(newState: .signedIn(signedInData), - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .signedIn(signedInData), + actions: [SignInComplete(signedInData: signedInData)] + ) default: return .from(oldState) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/RefreshSession/RefreshSessionState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/RefreshSession/RefreshSessionState+Resolver.swift index 3a0828f867..d64ad5f745 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/RefreshSession/RefreshSessionState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/RefreshSession/RefreshSessionState+Resolver.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension RefreshSessionState { @@ -15,8 +15,10 @@ extension RefreshSessionState { var defaultState: RefreshSessionState = .notStarted // swiftlint:disable:next cyclomatic_complexity - func resolve(oldState: RefreshSessionState, - byApplying event: StateMachineEvent) -> StateResolution { + func resolve( + oldState: RefreshSessionState, + byApplying event: StateMachineEvent + ) -> StateResolution { switch oldState { @@ -24,34 +26,46 @@ extension RefreshSessionState { if case .refreshCognitoUserPool(let signedInData) = event.isRefreshSessionEvent { let action = RefreshUserPoolTokens(existingSignedIndata: signedInData) - return .init(newState: .refreshingUserPoolToken(signedInData), - actions: [action]) + return .init( + newState: .refreshingUserPoolToken(signedInData), + actions: [action] + ) } if case .refreshCognitoUserPoolWithIdentityId( let signedInData, - let identityID) = event.isRefreshSessionEvent { + let identityID + ) = event.isRefreshSessionEvent { let action = RefreshUserPoolTokens(existingSignedIndata: signedInData) - return .init(newState: + return .init( + newState: .refreshingUserPoolTokenWithIdentity(signedInData, identityID), - actions: [action]) + actions: [action] + ) } if case .refreshUnAuthAWSCredentials(let identityID) = event.isRefreshSessionEvent { let provider = UnAuthLoginsMapProvider() - let action = FetchAuthAWSCredentials(loginsMap: provider.loginsMap, - identityID: identityID) - return .init(newState: .refreshingUnAuthAWSCredentials(identityID), - actions: [action]) + let action = FetchAuthAWSCredentials( + loginsMap: provider.loginsMap, + identityID: identityID + ) + return .init( + newState: .refreshingUnAuthAWSCredentials(identityID), + actions: [action] + ) } if case .refreshAWSCredentialsWithUserPool( let identityID, let signedInData, - let provider) = event.isRefreshSessionEvent { - let action = FetchAuthAWSCredentials(loginsMap: provider.loginsMap, - identityID: identityID) + let provider + ) = event.isRefreshSessionEvent { + let action = FetchAuthAWSCredentials( + loginsMap: provider.loginsMap, + identityID: identityID + ) return .init(newState: .refreshingAWSCredentialsWithUserPoolTokens( signedInData, identityID @@ -78,8 +92,10 @@ extension RefreshSessionState { if case .refreshIdentityInfo(let signedInData, _) = event.isRefreshSessionEvent { let action = InitializeFetchAuthSessionWithUserPool(signedInData: signedInData) - return .init(newState: .fetchingAuthSessionWithUserPool(.notStarted, signedInData), - actions: [action]) + return .init( + newState: .fetchingAuthSessionWithUserPool(.notStarted, signedInData), + actions: [action] + ) } return .from(oldState) @@ -95,11 +111,14 @@ extension RefreshSessionState { return .init(newState: .refreshed(credentials), actions: [action]) } if case .refreshIdentityInfo(let signedInData, let provider) = event.isRefreshSessionEvent { - let action = FetchAuthAWSCredentials(loginsMap: provider.loginsMap, - identityID: identityID) + let action = FetchAuthAWSCredentials( + loginsMap: provider.loginsMap, + identityID: identityID + ) return .init(newState: .refreshingAWSCredentialsWithUserPoolTokens( signedInData, - identityID), actions: [action]) + identityID + ), actions: [action]) } return .from(oldState) @@ -109,21 +128,27 @@ extension RefreshSessionState { let action = InformSessionError(error: error) return .init(newState: .error(error), actions: [action]) } - if case .fetched(let identityID, - let credentials) = event.isAuthorizationEvent { + if case .fetched( + let identityID, + let credentials + ) = event.isAuthorizationEvent { let credentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: signedInData, identityID: identityID, - credentials: credentials) + credentials: credentials + ) let action = InformSessionRefreshed(credentials: credentials) return .init(newState: .refreshed(credentials), actions: [action]) } let resolver = FetchAuthSessionState.Resolver() - let resolution = resolver.resolve(oldState: fetchSessionState, - byApplying: event) + let resolution = resolver.resolve( + oldState: fetchSessionState, + byApplying: event + ) return .init(newState: .fetchingAuthSessionWithUserPool( resolution.newState, - signedInData), actions: resolution.actions) + signedInData + ), actions: resolution.actions) case .refreshingUnAuthAWSCredentials: @@ -133,10 +158,12 @@ extension RefreshSessionState { } if case .fetchedAWSCredentials( let identityID, - let credentials) = event.isFetchSessionEvent { + let credentials + ) = event.isFetchSessionEvent { let amplifyCredentials = AmplifyCredentials.identityPoolOnly( identityID: identityID, - credentials: credentials) + credentials: credentials + ) let action = InformSessionRefreshed(credentials: amplifyCredentials) return .init(newState: .refreshed(amplifyCredentials), actions: [action]) } @@ -150,11 +177,13 @@ extension RefreshSessionState { } if case .fetchedAWSCredentials( let identityID, - let credentials) = event.isFetchSessionEvent { + let credentials + ) = event.isFetchSessionEvent { let amplifyCredentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: signedInData, identityID: identityID, - credentials: credentials) + credentials: credentials + ) let action = InformSessionRefreshed(credentials: amplifyCredentials) return .init(newState: .refreshed(amplifyCredentials), actions: [action]) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/DeviceSRPState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/DeviceSRPState+Resolver.swift index a95a2aa06d..2bcff08926 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/DeviceSRPState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/DeviceSRPState+Resolver.swift @@ -35,11 +35,13 @@ extension DeviceSRPState { case .initiatingDeviceSRP: return resolveRespondingDeviceSRPA( byApplying: deviceSrpSignInEvent, - from: oldState) + from: oldState + ) case .respondingDevicePasswordVerifier(let srpStateData): return resolveRespondingVerifyPassword( srpStateData: srpStateData, - byApplying: deviceSrpSignInEvent) + byApplying: deviceSrpSignInEvent + ) case .signedIn, .error: return .from(oldState) case .cancelling: @@ -53,7 +55,8 @@ extension DeviceSRPState { case .respondDeviceSRPChallenge(let username, let authResponse): let action = InitiateAuthDeviceSRP( username: username, - authResponse: authResponse) + authResponse: authResponse + ) return StateResolution( newState: DeviceSRPState.initiatingDeviceSRP, actions: [action] @@ -65,13 +68,15 @@ extension DeviceSRPState { private func resolveRespondingDeviceSRPA( byApplying signInEvent: SignInEvent, - from oldState: DeviceSRPState) + from oldState: DeviceSRPState + ) -> StateResolution { switch signInEvent.eventType { case .respondDevicePasswordVerifier(let srpStateData, let authResponse): let action = VerifyDevicePasswordSRP( stateData: srpStateData, - authResponse: authResponse) + authResponse: authResponse + ) return StateResolution( newState: DeviceSRPState.respondingDevicePasswordVerifier(srpStateData), actions: [action] @@ -85,12 +90,15 @@ extension DeviceSRPState { private func resolveRespondingVerifyPassword( srpStateData: SRPStateData, - byApplying signInEvent: SignInEvent) + byApplying signInEvent: SignInEvent + ) -> StateResolution { switch signInEvent.eventType { case .finalizeSignIn(let signedInData): - return .init(newState: .signedIn(signedInData), - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .signedIn(signedInData), + actions: [SignInComplete(signedInData: signedInData)] + ) case .cancelSRPSignIn: return .from(.cancelling) default: diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/SRPSignInState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/SRPSignInState+Resolver.swift index 7336e0ad58..756ca5c5bb 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/SRPSignInState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/SRPSignInState+Resolver.swift @@ -35,11 +35,13 @@ extension SRPSignInState { case .initiatingSRPA(let signInEventData): return resolveInitiatingSRPA( byApplying: srpSignInEvent, - from: oldState) + from: oldState + ) case .respondingPasswordVerifier(let srpStateData): return resolveRespondingVerifyPassword( srpStateData: srpStateData, - byApplying: srpSignInEvent) + byApplying: srpSignInEvent + ) case .signedIn, .error: return .from(oldState) case .cancelling: @@ -72,7 +74,8 @@ extension SRPSignInState { password: password, authFlowType: authFlowType, deviceMetadata: deviceMetadata, - clientMetadata: signInEventData.clientMetadata) + clientMetadata: signInEventData.clientMetadata + ) return StateResolution( newState: SRPSignInState.initiatingSRPA(signInEventData), actions: [action] @@ -84,14 +87,16 @@ extension SRPSignInState { private func resolveInitiatingSRPA( byApplying signInEvent: SignInEvent, - from oldState: SRPSignInState) + from oldState: SRPSignInState + ) -> StateResolution { switch signInEvent.eventType { case .respondPasswordVerifier(let srpStateData, let authResponse, let clientMetadata): let action = VerifyPasswordSRP( stateData: srpStateData, authResponse: authResponse, - clientMetadata: clientMetadata) + clientMetadata: clientMetadata + ) return StateResolution( newState: SRPSignInState.respondingPasswordVerifier(srpStateData), actions: [action] @@ -105,21 +110,25 @@ extension SRPSignInState { private func resolveRespondingVerifyPassword( srpStateData: SRPStateData, - byApplying signInEvent: SignInEvent) + byApplying signInEvent: SignInEvent + ) -> StateResolution { switch signInEvent.eventType { case .retryRespondPasswordVerifier(let srpStateData, let authResponse, let clientMetadata): let action = VerifyPasswordSRP( stateData: srpStateData, authResponse: authResponse, - clientMetadata: clientMetadata) + clientMetadata: clientMetadata + ) return StateResolution( newState: SRPSignInState.respondingPasswordVerifier(srpStateData), actions: [action] ) case .finalizeSignIn(let signedInData): - return .init(newState: .signedIn(signedInData), - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .signedIn(signedInData), + actions: [SignInComplete(signedInData: signedInData)] + ) case .cancelSRPSignIn: return .from(.cancelling) default: diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/HostedUISignInState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/HostedUISignInState+Resolver.swift index 6bb811523a..aaaa371142 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/HostedUISignInState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/HostedUISignInState+Resolver.swift @@ -16,7 +16,8 @@ extension HostedUISignInState { func resolve( oldState: HostedUISignInState, - byApplying event: StateMachineEvent) + byApplying event: StateMachineEvent + ) -> StateResolution { switch oldState { @@ -47,8 +48,10 @@ extension HostedUISignInState { return .init(newState: .error(error), actions: [action]) } if case .finalizeSignIn(let signedInData) = event.isSignInEvent { - return .init(newState: .done, - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .done, + actions: [SignInComplete(signedInData: signedInData)] + ) } return .from(oldState) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInChallengeState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInChallengeState+Resolver.swift index bff26db8a3..000c031eea 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInChallengeState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInChallengeState+Resolver.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Foundation extension SignInChallengeState { @@ -15,7 +16,8 @@ extension SignInChallengeState { func resolve( oldState: SignInChallengeState, - byApplying event: StateMachineEvent) + byApplying event: StateMachineEvent + ) -> StateResolution { switch oldState { @@ -32,7 +34,8 @@ extension SignInChallengeState { let action = VerifySignInChallenge( challenge: challenge, confirmSignEventData: answerEventData, - signInMethod: signInMethod) + signInMethod: signInMethod + ) return .init( newState: .verifying(challenge, signInMethod, answerEventData.answer), actions: [action] @@ -46,7 +49,8 @@ extension SignInChallengeState { let action = VerifySignInChallenge( challenge: challenge, confirmSignEventData: answerEventData, - signInMethod: signInMethod) + signInMethod: signInMethod + ) return .init( newState: .verifying(challenge, signInMethod, answerEventData.answer), actions: [action] @@ -54,8 +58,10 @@ extension SignInChallengeState { } if case .finalizeSignIn(let signedInData) = event.isSignInEvent { - return .init(newState: .verified, - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .verified, + actions: [SignInComplete(signedInData: signedInData)] + ) } if case .throwAuthError(let error) = event.isSignInEvent { @@ -70,7 +76,8 @@ extension SignInChallengeState { let action = VerifySignInChallenge( challenge: challenge, confirmSignEventData: answerEventData, - signInMethod: signInMethod) + signInMethod: signInMethod + ) return .init( newState: .verifying(challenge, signInMethod, answerEventData.answer), actions: [action] diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInState+Resolver.swift index d95da1588c..dc819cc3a1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInState+Resolver.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Foundation extension SignInState { @@ -17,7 +18,8 @@ extension SignInState { // swiftlint:disable:next cyclomatic_complexity function_body_length func resolve( oldState: SignInState, - byApplying event: StateMachineEvent) + byApplying event: StateMachineEvent + ) -> StateResolution { switch oldState { @@ -25,24 +27,32 @@ extension SignInState { if case .initiateSignInWithSRP(let signInEventData, let deviceMetadata) = event.isSignInEvent { let action = StartSRPFlow( signInEventData: signInEventData, - deviceMetadata: deviceMetadata) - return .init(newState: .signingInWithSRP(.notStarted, signInEventData), - actions: [action]) + deviceMetadata: deviceMetadata + ) + return .init( + newState: .signingInWithSRP(.notStarted, signInEventData), + actions: [action] + ) } if case .initiateCustomSignIn(let signInEventData, let deviceMetadata) = event.isSignInEvent { let action = StartCustomSignInFlow( signInEventData: signInEventData, - deviceMetadata: deviceMetadata) + deviceMetadata: deviceMetadata + ) return .init( newState: .signingInWithCustom(.notStarted, signInEventData), - actions: [action]) + actions: [action] + ) } if case .initiateCustomSignInWithSRP(let signInEventData, let deviceMetadata) = event.isSignInEvent { let action = StartSRPFlow( signInEventData: signInEventData, - deviceMetadata: deviceMetadata) - return .init(newState: .signingInWithSRPCustom(.notStarted, signInEventData), - actions: [action]) + deviceMetadata: deviceMetadata + ) + return .init( + newState: .signingInWithSRPCustom(.notStarted, signInEventData), + actions: [action] + ) } if case .initiateHostedUISignIn(let options) = event.isSignInEvent { let action = InitializeHostedUISignIn(options: options) @@ -51,9 +61,12 @@ extension SignInState { if case .initiateMigrateAuth(let signInEventData, let deviceMetadata) = event.isSignInEvent { let action = StartMigrateAuthFlow( signInEventData: signInEventData, - deviceMetadata: deviceMetadata) - return .init(newState: .signingInViaMigrateAuth(.notStarted, signInEventData), - actions: [action]) + deviceMetadata: deviceMetadata + ) + return .init( + newState: .signingInViaMigrateAuth(.notStarted, signInEventData), + actions: [action] + ) } return .from(oldState) @@ -63,8 +76,10 @@ extension SignInState { return .init(newState: .signedIn(signedInData)) } - let resolution = HostedUISignInState.Resolver().resolve(oldState: hostedUIState, - byApplying: event) + let resolution = HostedUISignInState.Resolver().resolve( + oldState: hostedUIState, + byApplying: event + ) let newState = SignInState.signingInWithHostedUI(resolution.newState) return .init(newState: newState, actions: resolution.actions) @@ -72,22 +87,29 @@ extension SignInState { let signInMethod = SignInMethod.apiBased(.userSRP) if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInMethod + ) let subState = SignInChallengeState.notStarted - return .init(newState: + return .init( + newState: .resolvingChallenge( subState, challenge.challenge.authChallengeType, signInMethod - ), actions: [action]) + ), + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .confirmDevice(let signedInData) = signInEvent.eventType { let action = ConfirmDevice(signedInData: signedInData) - return .init(newState: .confirmingDevice, - actions: [action]) + return .init( + newState: .confirmingDevice, + actions: [action] + ) } if let signInEvent = event as? SignInEvent, @@ -95,31 +117,42 @@ extension SignInState { case .respondingPasswordVerifier = srpSignInState { let action = StartDeviceSRPFlow( username: username, - authResponse: challengeResponse) - return .init(newState: .resolvingDeviceSrpa(.notStarted), - actions: [action]) + authResponse: challengeResponse + ) + return .init( + newState: .resolvingDeviceSrpa(.notStarted), + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateTOTPSetup(_, let challengeResponse) = signInEvent.eventType { let action = InitializeTOTPSetup( authResponse: challengeResponse) - return .init(newState: .resolvingTOTPSetup(.notStarted, signInEventData), - actions: [action]) + return .init( + newState: .resolvingTOTPSetup(.notStarted, signInEventData), + actions: [action] + ) } - let resolution = SRPSignInState.Resolver().resolve(oldState: srpSignInState, - byApplying: event) - let signingInWithSRP = SignInState.signingInWithSRP(resolution.newState, - signInEventData) + let resolution = SRPSignInState.Resolver().resolve( + oldState: srpSignInState, + byApplying: event + ) + let signingInWithSRP = SignInState.signingInWithSRP( + resolution.newState, + signInEventData + ) return .init(newState: signingInWithSRP, actions: resolution.actions) case .signingInWithCustom(let customSignInState, let signInEventData): let signInMethod = SignInMethod.apiBased(.customWithoutSRP) if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInMethod + ) let subState = SignInChallengeState.notStarted return .init(newState: .resolvingChallenge( subState, @@ -131,51 +164,65 @@ extension SignInState { if let signInEvent = event as? SignInEvent, case .confirmDevice(let signedInData) = signInEvent.eventType { let action = ConfirmDevice(signedInData: signedInData) - return .init(newState: .confirmingDevice, - actions: [action]) + return .init( + newState: .confirmingDevice, + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateDeviceSRP(let username, let challengeResponse) = signInEvent.eventType { let action = StartDeviceSRPFlow( username: username, - authResponse: challengeResponse) - return .init(newState: .resolvingDeviceSrpa(.notStarted), - actions: [action]) + authResponse: challengeResponse + ) + return .init( + newState: .resolvingDeviceSrpa(.notStarted), + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateTOTPSetup(_, let challengeResponse) = signInEvent.eventType { let action = InitializeTOTPSetup( authResponse: challengeResponse) - return .init(newState: .resolvingTOTPSetup(.notStarted, signInEventData), - actions: [action]) + return .init( + newState: .resolvingTOTPSetup(.notStarted, signInEventData), + actions: [action] + ) } let resolution = CustomSignInState.Resolver().resolve( - oldState: customSignInState, byApplying: event) + oldState: customSignInState, byApplying: event + ) let signingInWithCustom = SignInState.signingInWithCustom( - resolution.newState, signInEventData) + resolution.newState, signInEventData + ) return .init(newState: signingInWithCustom, actions: resolution.actions) case .signingInViaMigrateAuth(let migrateSignInState, let signInEventData): let signInMethod = SignInMethod.apiBased(.userPassword) if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInMethod + ) let subState = SignInChallengeState.notStarted return .init(newState: .resolvingChallenge( subState, challenge.challenge.authChallengeType, - signInMethod), actions: [action]) + signInMethod + ), actions: [action]) } if let signInEvent = event as? SignInEvent, case .confirmDevice(let signedInData) = signInEvent.eventType { let action = ConfirmDevice(signedInData: signedInData) - return .init(newState: .confirmingDevice, - actions: [action]) + return .init( + newState: .confirmingDevice, + actions: [action] + ) } if let signInEvent = event as? SignInEvent, @@ -183,23 +230,30 @@ extension SignInState { case .signingIn = migrateSignInState { let action = StartDeviceSRPFlow( username: username, - authResponse: challengeResponse) - return .init(newState: .resolvingDeviceSrpa(.notStarted), - actions: [action]) + authResponse: challengeResponse + ) + return .init( + newState: .resolvingDeviceSrpa(.notStarted), + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateTOTPSetup(_, let challengeResponse) = signInEvent.eventType { let action = InitializeTOTPSetup( authResponse: challengeResponse) - return .init(newState: .resolvingTOTPSetup(.notStarted, signInEventData), - actions: [action]) + return .init( + newState: .resolvingTOTPSetup(.notStarted, signInEventData), + actions: [action] + ) } let resolution = MigrateSignInState.Resolver().resolve( - oldState: migrateSignInState, byApplying: event) + oldState: migrateSignInState, byApplying: event + ) let signingInWithMigration = SignInState.signingInViaMigrateAuth( - resolution.newState, signInEventData) + resolution.newState, signInEventData + ) return .init(newState: signingInWithMigration, actions: resolution.actions) case .resolvingChallenge(let challengeState, let challengeType, let signInMethod): @@ -207,30 +261,38 @@ extension SignInState { if let signInEvent = event as? SignInEvent, case .confirmDevice(let signedInData) = signInEvent.eventType { let action = ConfirmDevice(signedInData: signedInData) - return .init(newState: .confirmingDevice, - actions: [action]) + return .init( + newState: .confirmingDevice, + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateDeviceSRP(let username, let challengeResponse) = signInEvent.eventType { let action = StartDeviceSRPFlow( username: username, - authResponse: challengeResponse) - return .init(newState: .resolvingDeviceSrpa(.notStarted), - actions: [action]) + authResponse: challengeResponse + ) + return .init( + newState: .resolvingDeviceSrpa(.notStarted), + actions: [action] + ) } // This could when we have nested challenges // Example newPasswordRequired -> sms_mfa if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInMethod + ) let subState = SignInChallengeState.notStarted return .init(newState: .resolvingChallenge( subState, challenge.challenge.authChallengeType, - signInMethod), actions: [action]) + signInMethod + ), actions: [action]) } if let signInEvent = event as? SignInEvent, @@ -240,26 +302,34 @@ extension SignInState { return .init( newState: .resolvingTOTPSetup( .notStarted, - .init(username: username, - password: nil, - signInMethod: signInMethod)), - actions: [action]) + .init( + username: username, + password: nil, + signInMethod: signInMethod + ) + ), + actions: [action] + ) } let resolution = SignInChallengeState.Resolver().resolve( oldState: challengeState, - byApplying: event) + byApplying: event + ) return .init(newState: .resolvingChallenge( resolution.newState, challengeType, - signInMethod), actions: resolution.actions) + signInMethod + ), actions: resolution.actions) case .signingInWithSRPCustom(let srpSignInState, let signInEventData): let signInMethod = SignInMethod.apiBased(.customWithSRP) if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInMethod + ) let subState = SignInChallengeState.notStarted return .init(newState: .resolvingChallenge( subState, @@ -272,43 +342,58 @@ extension SignInState { case .initiateDeviceSRP(let username, let challengeResponse) = signInEvent.eventType { let action = StartDeviceSRPFlow( username: username, - authResponse: challengeResponse) - return .init(newState: .resolvingDeviceSrpa(.notStarted), - actions: [action]) + authResponse: challengeResponse + ) + return .init( + newState: .resolvingDeviceSrpa(.notStarted), + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateTOTPSetup(_, let challengeResponse) = signInEvent.eventType { let action = InitializeTOTPSetup( authResponse: challengeResponse) - return .init(newState: .resolvingTOTPSetup(.notStarted, signInEventData), - actions: [action]) + return .init( + newState: .resolvingTOTPSetup(.notStarted, signInEventData), + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .confirmDevice(let signedInData) = signInEvent.eventType { let action = ConfirmDevice(signedInData: signedInData) - return .init(newState: .confirmingDevice, - actions: [action]) + return .init( + newState: .confirmingDevice, + actions: [action] + ) } - let resolution = SRPSignInState.Resolver().resolve(oldState: srpSignInState, - byApplying: event) - let signingInWithSRP = SignInState.signingInWithSRPCustom(resolution.newState, - signInEventData) + let resolution = SRPSignInState.Resolver().resolve( + oldState: srpSignInState, + byApplying: event + ) + let signingInWithSRP = SignInState.signingInWithSRPCustom( + resolution.newState, + signInEventData + ) return .init(newState: signingInWithSRP, actions: resolution.actions) case .resolvingTOTPSetup(let setUpTOTPState, let signInEventData): if case .finalizeSignIn(let signedInData) = event.isSignInEvent { - return .init(newState: .signedIn(signedInData), - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .signedIn(signedInData), + actions: [SignInComplete(signedInData: signedInData)] + ) } if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInEventData.signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInEventData.signInMethod + ) let subState = SignInChallengeState.notStarted return .init(newState: .resolvingChallenge( subState, @@ -320,64 +405,83 @@ extension SignInState { if let signInEvent = event as? SignInEvent, case .confirmDevice(let signedInData) = signInEvent.eventType { let action = ConfirmDevice(signedInData: signedInData) - return .init(newState: .confirmingDevice, - actions: [action]) + return .init( + newState: .confirmingDevice, + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateDeviceSRP(let username, let challengeResponse) = signInEvent.eventType { let action = StartDeviceSRPFlow( username: username, - authResponse: challengeResponse) - return .init(newState: .resolvingDeviceSrpa(.notStarted), - actions: [action]) + authResponse: challengeResponse + ) + return .init( + newState: .resolvingDeviceSrpa(.notStarted), + actions: [action] + ) } let resolution = SignInTOTPSetupState.Resolver( signInEventData: signInEventData).resolve( oldState: setUpTOTPState, - byApplying: event) + byApplying: event + ) let settingUpTOTPState = SignInState.resolvingTOTPSetup( resolution.newState, - signInEventData) + signInEventData + ) return .init(newState: settingUpTOTPState, actions: resolution.actions) case .resolvingDeviceSrpa(let deviceSrpState): let signInMethod = SignInMethod.apiBased(.userSRP) if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInMethod + ) let subState = SignInChallengeState.notStarted return .init(newState: .resolvingChallenge( subState, challenge.challenge.authChallengeType, - signInMethod), actions: [action]) + signInMethod + ), actions: [action]) } if let signInEvent = event as? SignInEvent, case .initiateTOTPSetup(let username, let challengeResponse) = signInEvent.eventType { let action = InitializeTOTPSetup( authResponse: challengeResponse) - return .init(newState: + return .init( + newState: .resolvingTOTPSetup( .notStarted, - .init(username: username, - password: nil, - signInMethod: signInMethod)), - actions: [action]) - } - - let resolution = DeviceSRPState.Resolver().resolve(oldState: deviceSrpState, - byApplying: event) + .init( + username: username, + password: nil, + signInMethod: signInMethod + ) + ), + actions: [action] + ) + } + + let resolution = DeviceSRPState.Resolver().resolve( + oldState: deviceSrpState, + byApplying: event + ) let resolvingDeviceSrpa = SignInState.resolvingDeviceSrpa(resolution.newState) return .init(newState: resolvingDeviceSrpa, actions: resolution.actions) case .confirmingDevice: if case .finalizeSignIn(let signedInData) = event.isSignInEvent { - return .init(newState: .signedIn(signedInData), - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .signedIn(signedInData), + actions: [SignInComplete(signedInData: signedInData)] + ) } return .from(oldState) case .signedIn, .error: diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignOut/SignOutState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignOut/SignOutState+Resolver.swift index 17523862b4..239e632d70 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignOut/SignOutState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignOut/SignOutState+Resolver.swift @@ -37,16 +37,20 @@ extension SignOutState { guard let signOutEvent = event as? SignOutEvent else { return .from(oldState) } - return resolveSigningOutLocally(byApplying: signOutEvent, - from: oldState, - signedInData: signedInData) + return resolveSigningOutLocally( + byApplying: signOutEvent, + from: oldState, + signedInData: signedInData + ) case .signingOutHostedUI(let signedInData): guard let signOutEvent = event as? SignOutEvent else { return .from(oldState) } - return resolveHostedUISignOut(byApplying: signOutEvent, - signedInData: signedInData, - from: oldState) + return resolveHostedUISignOut( + byApplying: signOutEvent, + signedInData: signedInData, + from: oldState + ) case .buildingRevokeTokenError: guard let signOutEvent = event as? SignOutEvent else { return .from(oldState) @@ -61,58 +65,79 @@ extension SignOutState { private func resolveNotStarted( byApplying signOutEvent: SignOutEvent, - from oldState: SignOutState) -> StateResolution { + from oldState: SignOutState + ) -> StateResolution { switch signOutEvent.eventType { case .signOutGlobally(let signedInData, hostedUIError: let hostedUIError): - let action = SignOutGlobally(signedInData: signedInData, - hostedUIError: hostedUIError) + let action = SignOutGlobally( + signedInData: signedInData, + hostedUIError: hostedUIError + ) return StateResolution( newState: SignOutState.signingOutGlobally, actions: [action] ) - case .revokeToken(let signedInData, - hostedUIError: let hostedUIError, - globalSignOutError: let globalSignOutError): - let action = RevokeToken(signedInData: signedInData, - hostedUIError: hostedUIError, - globalSignOutError: globalSignOutError) + case .revokeToken( + let signedInData, + hostedUIError: let hostedUIError, + globalSignOutError: let globalSignOutError + ): + let action = RevokeToken( + signedInData: signedInData, + hostedUIError: hostedUIError, + globalSignOutError: globalSignOutError + ) return StateResolution( newState: SignOutState.revokingToken, actions: [action] ) case .invokeHostedUISignOut(let signOutEventData, let signedInData): - let action = ShowHostedUISignOut(signOutEvent: signOutEventData, - signInData: signedInData) + let action = ShowHostedUISignOut( + signOutEvent: signOutEventData, + signInData: signedInData + ) return .init(newState: .signingOutHostedUI(signedInData), actions: [action]) case .signOutGuest: - let action = SignOutLocally(hostedUIError: nil, - globalSignOutError: nil, - revokeTokenError: nil) - return .init(newState: .signingOutLocally(nil), - actions: [action]) + let action = SignOutLocally( + hostedUIError: nil, + globalSignOutError: nil, + revokeTokenError: nil + ) + return .init( + newState: .signingOutLocally(nil), + actions: [action] + ) default: return .from(oldState) } } - private func resolveHostedUISignOut(byApplying signOutEvent: SignOutEvent, - signedInData: SignedInData, - from oldState: SignOutState) + private func resolveHostedUISignOut( + byApplying signOutEvent: SignOutEvent, + signedInData: SignedInData, + from oldState: SignOutState + ) -> StateResolution { switch signOutEvent.eventType { case .signOutGlobally(let signedInData, hostedUIError: let hostedUIError): - let action = SignOutGlobally(signedInData: signedInData, - hostedUIError: hostedUIError) + let action = SignOutGlobally( + signedInData: signedInData, + hostedUIError: hostedUIError + ) return StateResolution( newState: SignOutState.signingOutGlobally, actions: [action] ) - case .revokeToken(let signedInData, - hostedUIError: let hostedUIError, - globalSignOutError: let globalSignOutError): - let action = RevokeToken(signedInData: signedInData, - hostedUIError: hostedUIError, - globalSignOutError: globalSignOutError) + case .revokeToken( + let signedInData, + hostedUIError: let hostedUIError, + globalSignOutError: let globalSignOutError + ): + let action = RevokeToken( + signedInData: signedInData, + hostedUIError: hostedUIError, + globalSignOutError: globalSignOutError + ) return StateResolution( newState: SignOutState.revokingToken, actions: [action] @@ -127,26 +152,37 @@ extension SignOutState { private func resolveSigningOutGlobally( byApplying signOutEvent: SignOutEvent, - from oldState: SignOutState) -> StateResolution { + from oldState: SignOutState + ) -> StateResolution { switch signOutEvent.eventType { - case .revokeToken(let signedInData, - hostedUIError: let hostedUIError, - globalSignOutError: let globalSignOutError): - let action = RevokeToken(signedInData: signedInData, - hostedUIError: hostedUIError, - globalSignOutError: globalSignOutError) + case .revokeToken( + let signedInData, + hostedUIError: let hostedUIError, + globalSignOutError: let globalSignOutError + ): + let action = RevokeToken( + signedInData: signedInData, + hostedUIError: hostedUIError, + globalSignOutError: globalSignOutError + ) return StateResolution( newState: SignOutState.revokingToken, actions: [action] ) - case .globalSignOutError(let signedInData, - globalSignOutError: let globalSignOutError, - hostedUIError: let hostedUIError): - let action = BuildRevokeTokenError(signedInData: signedInData, - hostedUIError: hostedUIError, - globalSignOutError: globalSignOutError) - return .init(newState: .buildingRevokeTokenError, - actions: [action]) + case .globalSignOutError( + let signedInData, + globalSignOutError: let globalSignOutError, + hostedUIError: let hostedUIError + ): + let action = BuildRevokeTokenError( + signedInData: signedInData, + hostedUIError: hostedUIError, + globalSignOutError: globalSignOutError + ) + return .init( + newState: .buildingRevokeTokenError, + actions: [action] + ) default: return .from(oldState) @@ -155,35 +191,49 @@ extension SignOutState { private func resolveRevokingToken( byApplying signOutEvent: SignOutEvent, - from oldState: SignOutState) -> StateResolution { + from oldState: SignOutState + ) -> StateResolution { switch signOutEvent.eventType { - case .signOutLocally(let signedInData, - hostedUIError: let hostedUIError, - globalSignOutError: let globalSignOutError, - revokeTokenError: let revokeTokenError): - let action = SignOutLocally(hostedUIError: hostedUIError, - globalSignOutError: globalSignOutError, - revokeTokenError: revokeTokenError) - return .init(newState: .signingOutLocally(signedInData), - actions: [action]) + case .signOutLocally( + let signedInData, + hostedUIError: let hostedUIError, + globalSignOutError: let globalSignOutError, + revokeTokenError: let revokeTokenError + ): + let action = SignOutLocally( + hostedUIError: hostedUIError, + globalSignOutError: globalSignOutError, + revokeTokenError: revokeTokenError + ) + return .init( + newState: .signingOutLocally(signedInData), + actions: [action] + ) default: return .from(oldState) } } - private func resolveBuildingRevokeTokenError ( + private func resolveBuildingRevokeTokenError( byApplying signOutEvent: SignOutEvent, - from oldState: SignOutState) -> StateResolution { + from oldState: SignOutState + ) -> StateResolution { switch signOutEvent.eventType { - case .signOutLocally(let signedInData, - hostedUIError: let hostedUIError, - globalSignOutError: let globalSignOutError, - revokeTokenError: let revokeTokenError): - let action = SignOutLocally(hostedUIError: hostedUIError, - globalSignOutError: globalSignOutError, - revokeTokenError: revokeTokenError) - return .init(newState: .signingOutLocally(signedInData), - actions: [action]) + case .signOutLocally( + let signedInData, + hostedUIError: let hostedUIError, + globalSignOutError: let globalSignOutError, + revokeTokenError: let revokeTokenError + ): + let action = SignOutLocally( + hostedUIError: hostedUIError, + globalSignOutError: globalSignOutError, + revokeTokenError: revokeTokenError + ) + return .init( + newState: .signingOutLocally(signedInData), + actions: [action] + ) default: return .from(oldState) } @@ -192,12 +242,15 @@ extension SignOutState { private func resolveSigningOutLocally( byApplying event: SignOutEvent, from oldState: SignOutState, - signedInData: SignedInData?) + signedInData: SignedInData? + ) -> StateResolution { switch event.eventType { - case .signedOutSuccess(hostedUIError: let hostedUIError, - globalSignOutError: let globalSignOutError, - revokeTokenError: let revokeTokenError): + case .signedOutSuccess( + hostedUIError: let hostedUIError, + globalSignOutError: let globalSignOutError, + revokeTokenError: let revokeTokenError + ): let signedOutData = SignedOutData( lastKnownUserName: signedInData?.username, hostedUIError: hostedUIError, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/TOTPSetup/SignInTOTPSetupState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/TOTPSetup/SignInTOTPSetupState+Resolver.swift index d9ac9e2dee..ea0c0ea1ee 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/TOTPSetup/SignInTOTPSetupState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/TOTPSetup/SignInTOTPSetupState+Resolver.swift @@ -31,13 +31,17 @@ extension SignInTOTPSetupState { case .waitingForAnswer(let signInTOTPSetupData): return resolveWaitForAnswer( byApplying: setupTOTPEvent, - with: signInTOTPSetupData) + with: signInTOTPSetupData + ) case .verifying(let signInTOTPSetupData, _): return resolveVerifyingState( - byApplying: setupTOTPEvent, with: signInTOTPSetupData) + byApplying: setupTOTPEvent, with: signInTOTPSetupData + ) case .error(let signInTOTPSetupData, _): - return resolveErrorState(byApplying: setupTOTPEvent, - with: signInTOTPSetupData) + return resolveErrorState( + byApplying: setupTOTPEvent, + with: signInTOTPSetupData + ) default: return .from(.notStarted) } @@ -49,7 +53,8 @@ extension SignInTOTPSetupState { case .setUpTOTP(let authResponse): let action = SetUpTOTP( authResponse: authResponse, - signInEventData: signInEventData) + signInEventData: signInEventData + ) return StateResolution( newState: SignInTOTPSetupState.setUpTOTP, actions: [action] @@ -78,17 +83,20 @@ extension SignInTOTPSetupState { private func resolveWaitForAnswer( byApplying signInEvent: SetUpTOTPEvent, - with signInTOTPSetupData: SignInTOTPSetupData) -> StateResolution { + with signInTOTPSetupData: SignInTOTPSetupData + ) -> StateResolution { switch signInEvent.eventType { case .verifyChallengeAnswer(let confirmSignInEventData): let action = VerifyTOTPSetup( session: signInTOTPSetupData.session, totpCode: confirmSignInEventData.answer, - friendlyDeviceName: confirmSignInEventData.friendlyDeviceName) + friendlyDeviceName: confirmSignInEventData.friendlyDeviceName + ) return StateResolution( newState: SignInTOTPSetupState.verifying( signInTOTPSetupData, - confirmSignInEventData), + confirmSignInEventData + ), actions: [action] ) case .throwError(let error): @@ -100,12 +108,14 @@ extension SignInTOTPSetupState { private func resolveVerifyingState( byApplying signInEvent: SetUpTOTPEvent, - with signInTOTPSetupData: SignInTOTPSetupData) -> StateResolution { + with signInTOTPSetupData: SignInTOTPSetupData + ) -> StateResolution { switch signInEvent.eventType { case .respondToAuthChallenge(let session): let action = CompleteTOTPSetup( userSession: session, - signInEventData: signInEventData) + signInEventData: signInEventData + ) return StateResolution( newState: SignInTOTPSetupState.respondingToAuthChallenge, actions: [action] @@ -119,21 +129,24 @@ extension SignInTOTPSetupState { private func resolveErrorState( byApplying signInEvent: SetUpTOTPEvent, - with signInTOTPSetupData: SignInTOTPSetupData?) -> StateResolution { + with signInTOTPSetupData: SignInTOTPSetupData? + ) -> StateResolution { switch signInEvent.eventType { case .verifyChallengeAnswer(let confirmSignInEventData): - guard let signInTOTPSetupData = signInTOTPSetupData else { + guard let signInTOTPSetupData else { return .from(.notStarted) } let action = VerifyTOTPSetup( session: signInTOTPSetupData.session, totpCode: confirmSignInEventData.answer, - friendlyDeviceName: confirmSignInEventData.friendlyDeviceName) + friendlyDeviceName: confirmSignInEventData.friendlyDeviceName + ) return StateResolution( newState: SignInTOTPSetupState.verifying( signInTOTPSetupData, - confirmSignInEventData), + confirmSignInEventData + ), actions: [action] ) default: diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/hierarchical-state-machine-swift/ConcurrentEffectExecutor.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/hierarchical-state-machine-swift/ConcurrentEffectExecutor.swift index 216c9bbde5..5f84a2f0db 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/hierarchical-state-machine-swift/ConcurrentEffectExecutor.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/hierarchical-state-machine-swift/ConcurrentEffectExecutor.swift @@ -12,8 +12,9 @@ enum ConcurrentEffectExecutor: EffectExecutor { static func execute( _ actions: [Action], dispatchingTo eventDispatcher: EventDispatcher, - environment: Environment) { - actions.forEach { action in + environment: Environment + ) { + for action in actions { Task.detached { await action.execute(withDispatcher: eventDispatcher, environment: environment) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginConstants.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginConstants.swift index 4edddb6d18..fe69142592 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginConstants.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginConstants.swift @@ -7,7 +7,7 @@ import Foundation -struct AuthPluginConstants { +enum AuthPluginConstants { /// The time interval under which the refresh of UserPool or awsCredentials tokens will happen static let sessionRefreshInterval: TimeInterval = 2 * 60 diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginErrorConstants.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginErrorConstants.swift index ab899e5682..cef09da5bc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginErrorConstants.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginErrorConstants.swift @@ -5,172 +5,213 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation typealias AuthPluginErrorString = (errorDescription: ErrorDescription, recoverySuggestion: RecoverySuggestion) -typealias AuthPluginValidationErrorString = (field: Field, +typealias AuthPluginValidationErrorString = ( + field: Field, errorDescription: ErrorDescription, - recoverySuggestion: RecoverySuggestion) + recoverySuggestion: RecoverySuggestion +) enum AuthPluginErrorConstants { static let decodeConfigurationError: AuthPluginErrorString = ( "Unable to decode configuration", - "Make sure the plugin configuration is JSONValue") + "Make sure the plugin configuration is JSONValue" + ) static let configurationObjectExpected: AuthPluginErrorString = ( "Configuration was not a dictionary literal", - "Make sure the value for the plugin is a dictionary literal") + "Make sure the value for the plugin is a dictionary literal" + ) static let hostedUISecurityFailedError: AuthPluginErrorString = ( "Found invalid parameter while parsing the webUI redirect URL", - "Make sure that the signIn URL has not been modified during the signIn flow") + "Make sure that the signIn URL has not been modified during the signIn flow" + ) static let hostedUIUserCancelledError: AuthPluginErrorString = ( "User cancelled the signIn flow and could not be completed.", - "Present the signIn UI again for the user to sign in") + "Present the signIn UI again for the user to sign in" + ) static let hostedUIUserCancelledSignOutError: AuthPluginErrorString = ( "User cancelled the signOut flow and could not be completed.", - "Present the signOut UI again for the user to sign out") + "Present the signOut UI again for the user to sign out" + ) static let hostedUIInvalidPresentation: AuthPluginErrorString = ( "Presentation context provided is invalid or not present", - "Retry by providing a presentation context to present the webUI") + "Retry by providing a presentation context to present the webUI" + ) static let hostedUIUnableToStartASWebAuthenticationSession: AuthPluginErrorString = ( "Unable to start a ASWebAuthenticationSession", - "Make sure that the app can present an ASWebAuthenticationSession") + "Make sure that the app can present an ASWebAuthenticationSession" + ) static let hostedUISignInURI: AuthPluginErrorString = ( "SignIn URI could not be created", - "Check the configuration to make sure that HostedUI related information are present") + "Check the configuration to make sure that HostedUI related information are present" + ) static let hostedUITokenURI: AuthPluginErrorString = ( "Token URI could not be created", - "Check the configuration to make sure that HostedUI related information are present") + "Check the configuration to make sure that HostedUI related information are present" + ) static let hostedUISignOutURI: AuthPluginErrorString = ( "SignOut URI could not be created", - "Check the configuration to make sure that HostedUI related information are present") + "Check the configuration to make sure that HostedUI related information are present" + ) static let hostedUISignOutRedirectURI: AuthPluginErrorString = ( "Callback URL could not be retrieved", - "Check the configuration to make sure that HostedUI related information are present") + "Check the configuration to make sure that HostedUI related information are present" + ) static let hostedUIProofCalculation: AuthPluginErrorString = ( "Proof calculation failed", - "Reach out with amplify team via github to raise an issue") + "Reach out with amplify team via github to raise an issue" + ) static let tokenParsingError: AuthPluginErrorString = ( "Token returned by service could not be parsed", - "Check if the the configuration provided are correct") + "Check if the the configuration provided are correct" + ) static let userInvalidError: AuthPluginErrorString = ( "Could not validate the user", - "Get the current user Auth.getCurrentUser() and make the request") - + "Get the current user Auth.getCurrentUser() and make the request" + ) + static let identityIdSignOutError: AuthPluginErrorString = ( "There is no user signed in to retreive identity id", - "Call Auth.signIn to sign in a user or enable unauthenticated access in AWS Cognito Identity Pool") + "Call Auth.signIn to sign in a user or enable unauthenticated access in AWS Cognito Identity Pool" + ) static let awsCredentialsSignOutError: AuthPluginErrorString = ( "There is no user signed in to retreive AWS credentials", - "Call Auth.signIn to sign in a user or enable unauthenticated access in AWS Cognito Identity Pool") + "Call Auth.signIn to sign in a user or enable unauthenticated access in AWS Cognito Identity Pool" + ) static let cognitoTokensSignOutError: AuthPluginErrorString = ( "There is no user signed in to retreive cognito tokens", - "Call Auth.signIn to sign in a user and then call Auth.fetchSession") + "Call Auth.signIn to sign in a user and then call Auth.fetchSession" + ) static let userSubSignOutError: AuthPluginErrorString = ( "There is no user signed in to retreive user sub", - "Call Auth.signIn to sign in a user and then call Auth.fetchSession") + "Call Auth.signIn to sign in a user and then call Auth.fetchSession" + ) static let identityIdOfflineError: AuthPluginErrorString = ( "A network error occured while trying to fetch identity id", - "Try again with exponential backoff") + "Try again with exponential backoff" + ) static let awsCredentialsOfflineError: AuthPluginErrorString = ( "A network error occured while trying to fetch AWS credentials", - "Try again with exponential backoff") + "Try again with exponential backoff" + ) static let usersubOfflineError: AuthPluginErrorString = ( "A network error occured while trying to fetch user sub", - "Try again with exponential backoff") + "Try again with exponential backoff" + ) static let cognitoTokenOfflineError: AuthPluginErrorString = ( "A network error occured while trying to fetch AWS Cognito Tokens", - "Try again with exponential backoff") + "Try again with exponential backoff" + ) static let identityIdServiceError: AuthPluginErrorString = ( "A serivce error occured while trying to fetch identity id", - "Try again with exponential backoff") + "Try again with exponential backoff" + ) static let awsCredentialsServiceError: AuthPluginErrorString = ( "A service error occured while trying to fetch AWS credentials", - "Try again with exponential backoff") + "Try again with exponential backoff" + ) static let identityIdSessionExpiredError: AuthPluginErrorString = ( "Session expired could not fetch identity id", - "Invoke Auth.signIn to re-authenticate the user") + "Invoke Auth.signIn to re-authenticate the user" + ) static let awsCredentialsSessionExpiredError: AuthPluginErrorString = ( "Session expired could not fetch AWS Credentials", - "Invoke Auth.signIn to re-authenticate the user") + "Invoke Auth.signIn to re-authenticate the user" + ) static let usersubSessionExpiredError: AuthPluginErrorString = ( "Session expired could not fetch user sub", - "Invoke Auth.signIn to re-authenticate the user") + "Invoke Auth.signIn to re-authenticate the user" + ) static let cognitoTokensSessionExpiredError: AuthPluginErrorString = ( "Session expired could not fetch cognito tokens", - "Invoke Auth.signIn to re-authenticate the user") + "Invoke Auth.signIn to re-authenticate the user" + ) static let cognitoTokenSignedInThroughCIDPError: AuthPluginErrorString = ( "User is not signed in through Cognito User pool", - "Tokens are not valid with user signed in through AWS Cognito Identity Pool") + "Tokens are not valid with user signed in through AWS Cognito Identity Pool" + ) static let userSubSignedInThroughCIDPError: AuthPluginErrorString = ( "User is not signed in through Cognito User pool", - "User sub are not valid with user signed in through AWS Cognito Identity Pool") + "User sub are not valid with user signed in through AWS Cognito Identity Pool" + ) static let signedInIdentityIdWithNoCIDPError: AuthPluginErrorString = ( "Could not fetch identity Id, AWS Cognito Identity Pool is not configured", - "Follow the steps to configure AWS Cognito Identity Pool and try again") + "Follow the steps to configure AWS Cognito Identity Pool and try again" + ) static let signedInAWSCredentialsWithNoCIDPError: AuthPluginErrorString = ( "Could not fetch AWS Credentials, AWS Cognito Identity Pool is not configured", - "Follow the steps to configure AWS Cognito Identity Pool and try again") + "Follow the steps to configure AWS Cognito Identity Pool and try again" + ) static let fetchAttributeSignedOutError: AuthPluginErrorString = ( - "Could not fetch attributes, there is no user signed in to the Auth category", - "SignIn to Auth category by using one of the sign in methods and then call user attributes apis") + "Could not fetch attributes, there is no user signed in to the Auth category", + "SignIn to Auth category by using one of the sign in methods and then call user attributes apis" + ) static let updateAttributeSignedOutError: AuthPluginErrorString = ( - "Could not update attributes, there is no user signed in to the Auth category", - "SignIn to Auth category by using one of the sign in methods and then call user attributes apis") + "Could not update attributes, there is no user signed in to the Auth category", + "SignIn to Auth category by using one of the sign in methods and then call user attributes apis" + ) static let resendAttributeCodeSignedOutError: AuthPluginErrorString = ( - "Could not resend attribute confirmation code, there is no user signed in to the Auth category", - "SignIn to Auth category by using one of the sign in methods and then call user attributes apis") + "Could not resend attribute confirmation code, there is no user signed in to the Auth category", + "SignIn to Auth category by using one of the sign in methods and then call user attributes apis" + ) static let confirmAttributeSignedOutError: AuthPluginErrorString = ( - "Could not confirm attribute, there is no user signed in to the Auth category", - "SignIn to Auth category by using one of the sign in methods and then call user attributes apis") + "Could not confirm attribute, there is no user signed in to the Auth category", + "SignIn to Auth category by using one of the sign in methods and then call user attributes apis" + ) static let changePasswordSignedOutError: AuthPluginErrorString = ( - "Could not change password, there is no user signed in to the Auth category", - "Change password require a user signed in to Auth category, use one of the signIn apis to signIn") + "Could not change password, there is no user signed in to the Auth category", + "Change password require a user signed in to Auth category, use one of the signIn apis to signIn" + ) static let changePasswordUnableToSignInError: AuthPluginErrorString = ( - "Could not change password, the user session is expired", - "Re-authenticate the user by using one of the signIn apis") + "Could not change password, the user session is expired", + "Re-authenticate the user by using one of the signIn apis" + ) static let userSignedOutError: AuthPluginErrorString = ( - "There is no user signed in to the Auth category", - "SignIn to Auth category by using one of the sign in methods and then try again") + "There is no user signed in to the Auth category", + "SignIn to Auth category by using one of the sign in methods and then try again" + ) } // Field validation errors diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/EndpointResolving+ValidationStep.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/EndpointResolving+ValidationStep.swift index 7f4f1c9de4..d8f02f1b63 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/EndpointResolving+ValidationStep.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/EndpointResolving+ValidationStep.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension EndpointResolving { struct ValidationStep { @@ -43,7 +43,7 @@ extension EndpointResolving.ValidationStep { /// Validate that the input `URLComponents` don't contain a path. static func pathIsEmpty() -> Self where Input == (URLComponents, String), Output == Void { - .init { (components, endpoint) in + .init { components, endpoint in guard components.path.isEmpty else { throw AuthError.invalidPath( endpoint: endpoint, @@ -55,8 +55,8 @@ extension EndpointResolving.ValidationStep { } // MARK: Fileprivate AuthError extensions thrown on invalid `Endpoint` input. -extension AuthError { - fileprivate static func invalidURL(_ endpoint: String) -> AuthError { +private extension AuthError { + static func invalidURL(_ endpoint: String) -> AuthError { .configuration( "Error configuring AWSCognitoAuthPlugin", """ @@ -67,7 +67,7 @@ extension AuthError { ) } - fileprivate static func invalidScheme(_ endpoint: String) -> AuthError { + static func invalidScheme(_ endpoint: String) -> AuthError { .configuration( "Error configuring AWSCognitoAuthPlugin", """ @@ -80,7 +80,7 @@ extension AuthError { ) } - fileprivate static func invalidPath( + static func invalidPath( endpoint: String, components: URLComponents ) -> AuthError { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedInSessionHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedInSessionHelper.swift index 2db23e0ce7..674331157d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedInSessionHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedInSessionHelper.swift @@ -7,28 +7,33 @@ import Amplify -struct AuthCognitoSignedInSessionHelper { +enum AuthCognitoSignedInSessionHelper { static func makeOfflineSignedInSession() -> AWSAuthCognitoSession { let identityIdError = AuthError.service( AuthPluginErrorConstants.identityIdOfflineError.errorDescription, AuthPluginErrorConstants.identityIdOfflineError.recoverySuggestion, - AWSCognitoAuthError.network) + AWSCognitoAuthError.network + ) let awsCredentialsError = AuthError.service( AuthPluginErrorConstants.awsCredentialsOfflineError.errorDescription, AuthPluginErrorConstants.awsCredentialsOfflineError.recoverySuggestion, - AWSCognitoAuthError.network) + AWSCognitoAuthError.network + ) let tokensError = AuthError.service( AuthPluginErrorConstants.cognitoTokenOfflineError.errorDescription, AuthPluginErrorConstants.cognitoTokenOfflineError.recoverySuggestion, - AWSCognitoAuthError.network) + AWSCognitoAuthError.network + ) - let authSession = AWSAuthCognitoSession(isSignedIn: true, - identityIdResult: .failure(identityIdError), - awsCredentialsResult: .failure(awsCredentialsError), - cognitoTokensResult: .failure(tokensError)) + let authSession = AWSAuthCognitoSession( + isSignedIn: true, + identityIdResult: .failure(identityIdError), + awsCredentialsResult: .failure(awsCredentialsError), + cognitoTokensResult: .failure(tokensError) + ) return authSession } @@ -36,22 +41,27 @@ struct AuthCognitoSignedInSessionHelper { let identityIdError = AuthError.sessionExpired( AuthPluginErrorConstants.identityIdSessionExpiredError.errorDescription, AuthPluginErrorConstants.identityIdSessionExpiredError.recoverySuggestion, - underlyingError) + underlyingError + ) let awsCredentialsError = AuthError.sessionExpired( AuthPluginErrorConstants.awsCredentialsSessionExpiredError.errorDescription, AuthPluginErrorConstants.awsCredentialsSessionExpiredError.recoverySuggestion, - underlyingError) + underlyingError + ) let tokensError = AuthError.sessionExpired( AuthPluginErrorConstants.cognitoTokensSessionExpiredError.errorDescription, AuthPluginErrorConstants.cognitoTokensSessionExpiredError.recoverySuggestion, - underlyingError) + underlyingError + ) - let authSession = AWSAuthCognitoSession(isSignedIn: true, - identityIdResult: .failure(identityIdError), - awsCredentialsResult: .failure(awsCredentialsError), - cognitoTokensResult: .failure(tokensError)) + let authSession = AWSAuthCognitoSession( + isSignedIn: true, + identityIdResult: .failure(identityIdError), + awsCredentialsResult: .failure(awsCredentialsError), + cognitoTokensResult: .failure(tokensError) + ) return authSession } @@ -59,7 +69,8 @@ struct AuthCognitoSignedInSessionHelper { let userSubError = AuthError.service( AuthPluginErrorConstants.userSubSignedInThroughCIDPError.errorDescription, AuthPluginErrorConstants.userSubSignedInThroughCIDPError.recoverySuggestion, - AWSCognitoAuthError.invalidAccountTypeException) + AWSCognitoAuthError.invalidAccountTypeException + ) return userSubError } @@ -67,7 +78,8 @@ struct AuthCognitoSignedInSessionHelper { let tokensError = AuthError.service( AuthPluginErrorConstants.cognitoTokenSignedInThroughCIDPError.errorDescription, AuthPluginErrorConstants.cognitoTokenSignedInThroughCIDPError.recoverySuggestion, - AWSCognitoAuthError.invalidAccountTypeException) + AWSCognitoAuthError.invalidAccountTypeException + ) return tokensError } @@ -75,7 +87,8 @@ struct AuthCognitoSignedInSessionHelper { let identityIdError = AuthError.service( AuthPluginErrorConstants.signedInIdentityIdWithNoCIDPError.errorDescription, AuthPluginErrorConstants.signedInIdentityIdWithNoCIDPError.recoverySuggestion, - AWSCognitoAuthError.invalidAccountTypeException) + AWSCognitoAuthError.invalidAccountTypeException + ) return identityIdError } @@ -83,7 +96,8 @@ struct AuthCognitoSignedInSessionHelper { let awsCredentialsError = AuthError.service( AuthPluginErrorConstants.signedInAWSCredentialsWithNoCIDPError.errorDescription, AuthPluginErrorConstants.signedInAWSCredentialsWithNoCIDPError.recoverySuggestion, - AWSCognitoAuthError.invalidAccountTypeException) + AWSCognitoAuthError.invalidAccountTypeException + ) return awsCredentialsError } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedOutSessionHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedOutSessionHelper.swift index 8e391355e5..ee923133c3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedOutSessionHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedOutSessionHelper.swift @@ -8,20 +8,24 @@ import Amplify import AWSPluginsCore -struct AuthCognitoSignedOutSessionHelper { +enum AuthCognitoSignedOutSessionHelper { /// Creates a signedOut session information with valid identityId and aws credentials. /// - Parameters: /// - identityId: Valid identity id for the current signedOut session /// - awsCredentials: Valid AWS Credentials for the current signedOut session /// - Returns: Returns a valid signedOut session - static func makeSignedOutSession(identityId: String, - awsCredentials: AWSCredentials) -> AWSAuthCognitoSession { + static func makeSignedOutSession( + identityId: String, + awsCredentials: AWSCredentials + ) -> AWSAuthCognitoSession { let tokensError = makeCognitoTokensSignedOutError() - let authSession = AWSAuthCognitoSession(isSignedIn: false, - identityIdResult: .success(identityId), - awsCredentialsResult: .success(awsCredentials), - cognitoTokensResult: .failure(tokensError)) + let authSession = AWSAuthCognitoSession( + isSignedIn: false, + identityIdResult: .success(identityId), + awsCredentialsResult: .success(awsCredentials), + cognitoTokensResult: .failure(tokensError) + ) return authSession } @@ -31,19 +35,23 @@ struct AuthCognitoSignedOutSessionHelper { let identityIdError = AuthError.service( AuthPluginErrorConstants.identityIdSignOutError.errorDescription, AuthPluginErrorConstants.identityIdSignOutError.recoverySuggestion, - AWSCognitoAuthError.invalidAccountTypeException) + AWSCognitoAuthError.invalidAccountTypeException + ) let awsCredentialsError = AuthError.service( AuthPluginErrorConstants.awsCredentialsSignOutError.errorDescription, AuthPluginErrorConstants.awsCredentialsSignOutError.recoverySuggestion, - AWSCognitoAuthError.invalidAccountTypeException) + AWSCognitoAuthError.invalidAccountTypeException + ) let tokensError = makeCognitoTokensSignedOutError() - let authSession = AWSAuthCognitoSession(isSignedIn: false, - identityIdResult: .failure(identityIdError), - awsCredentialsResult: .failure(awsCredentialsError), - cognitoTokensResult: .failure(tokensError)) + let authSession = AWSAuthCognitoSession( + isSignedIn: false, + identityIdResult: .failure(identityIdError), + awsCredentialsResult: .failure(awsCredentialsError), + cognitoTokensResult: .failure(tokensError) + ) return authSession } @@ -53,25 +61,30 @@ struct AuthCognitoSignedOutSessionHelper { let identityIdError = AuthError.service( AuthPluginErrorConstants.identityIdServiceError.errorDescription, - AuthPluginErrorConstants.identityIdServiceError.recoverySuggestion) + AuthPluginErrorConstants.identityIdServiceError.recoverySuggestion + ) let awsCredentialsError = AuthError.service( AuthPluginErrorConstants.awsCredentialsServiceError.errorDescription, - AuthPluginErrorConstants.awsCredentialsServiceError.recoverySuggestion) + AuthPluginErrorConstants.awsCredentialsServiceError.recoverySuggestion + ) let tokensError = makeCognitoTokensSignedOutError() - let authSession = AWSAuthCognitoSession(isSignedIn: false, - identityIdResult: .failure(identityIdError), - awsCredentialsResult: .failure(awsCredentialsError), - cognitoTokensResult: .failure(tokensError)) + let authSession = AWSAuthCognitoSession( + isSignedIn: false, + identityIdResult: .failure(identityIdError), + awsCredentialsResult: .failure(awsCredentialsError), + cognitoTokensResult: .failure(tokensError) + ) return authSession } private static func makeCognitoTokensSignedOutError() -> AuthError { let tokensError = AuthError.signedOut( AuthPluginErrorConstants.cognitoTokensSignOutError.errorDescription, - AuthPluginErrorConstants.cognitoTokensSignOutError.recoverySuggestion) + AuthPluginErrorConstants.cognitoTokensSignOutError.recoverySuggestion + ) return tokensError } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoTokens+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoTokens+Validation.swift index 9dde721c31..2879bc27d1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoTokens+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoTokens+Validation.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation /// Internal Helpers for managing session tokens extension AWSCognitoUserPoolTokens { @@ -17,7 +17,8 @@ extension AWSCognitoUserPoolTokens { guard let idTokenClaims = try? AWSAuthService().getTokenClaims(tokenString: idToken).get(), let accessTokenClaims = try? AWSAuthService().getTokenClaims(tokenString: accessToken).get(), let idTokenExpiration = idTokenClaims["exp"]?.doubleValue, - let accessTokenExpiration = accessTokenClaims["exp"]?.doubleValue else { + let accessTokenExpiration = accessTokenClaims["exp"]?.doubleValue + else { return currentTime > expiration } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthProvider+Cognito.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthProvider+Cognito.swift index 2efe44d5fc..23abb97de5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthProvider+Cognito.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthProvider+Cognito.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension AuthProvider { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift index 341ac58617..28eb37ac2b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CryptoKit +import Foundation enum ClientSecretHelper { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ConfigurationHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ConfigurationHelper.swift index ae6d367070..ffd36adf36 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ConfigurationHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ConfigurationHelper.swift @@ -46,16 +46,15 @@ struct ConfigurationHelper { }() // parse `authFlowType` - var authFlowType: AuthFlowType - if case .boolean(let isMigrationEnabled) = cognitoUserPoolJSON.value(at: "MigrationEnabled"), + var authFlowType: AuthFlowType = if case .boolean(let isMigrationEnabled) = cognitoUserPoolJSON.value(at: "MigrationEnabled"), isMigrationEnabled == true { - authFlowType = .userPassword + .userPassword } else if let authJson = config.value(at: "Auth.Default"), case .string(let authFlowTypeJSON) = authJson.value(at: "authenticationFlowType"), authFlowTypeJSON == "CUSTOM_AUTH" { - authFlowType = .customWithSRP + .customWithSRP } else { - authFlowType = .userSRP + .userSRP } // parse `clientSecret` @@ -68,25 +67,27 @@ struct ConfigurationHelper { let hostedUIConfig = parseHostedConfiguration( configuration: config.value(at: "Auth.Default.OAuth")) - return UserPoolConfigurationData(poolId: poolId, - clientId: appClientId, - region: region, - endpoint: endpoint, - clientSecret: clientSecret, - pinpointAppId: pinpointId, - authFlowType: authFlowType, - hostedUIConfig: hostedUIConfig, - passwordProtectionSettings: nil, - usernameAttributes: [], - signUpAttributes: [], - verificationMechanisms: []) + return UserPoolConfigurationData( + poolId: poolId, + clientId: appClientId, + region: region, + endpoint: endpoint, + clientSecret: clientSecret, + pinpointAppId: pinpointId, + authFlowType: authFlowType, + hostedUIConfig: hostedUIConfig, + passwordProtectionSettings: nil, + usernameAttributes: [], + signUpAttributes: [], + verificationMechanisms: [] + ) } static func parseUserPoolData(_ config: AmplifyOutputsData.Auth) -> UserPoolConfigurationData? { let hostedUIConfig = parseHostedConfiguration(configuration: config) // parse `passwordProtectionSettings` - var passwordProtectionSettings: UserPoolConfigurationData.PasswordProtectionSettings? = nil + var passwordProtectionSettings: UserPoolConfigurationData.PasswordProtectionSettings? if let passwordPolicy = config.passwordPolicy { passwordProtectionSettings = .init(from: passwordPolicy) } @@ -106,18 +107,20 @@ struct ConfigurationHelper { .userVerificationTypes? .compactMap { .init(from: $0) } ?? [] - return UserPoolConfigurationData(poolId: config.userPoolId, - clientId: config.userPoolClientId, - region: config.awsRegion, - endpoint: nil, // Gen2 does not support this field - clientSecret: nil, // Gen2 does not support this field - pinpointAppId: nil, // Gen2 does not support this field - authFlowType: .userSRP, - hostedUIConfig: hostedUIConfig, - passwordProtectionSettings: passwordProtectionSettings, - usernameAttributes: usernameAttributes, - signUpAttributes: signUpAttributes, - verificationMechanisms: verificationMechanisms) + return UserPoolConfigurationData( + poolId: config.userPoolId, + clientId: config.userPoolClientId, + region: config.awsRegion, + endpoint: nil, // Gen2 does not support this field + clientSecret: nil, // Gen2 does not support this field + pinpointAppId: nil, // Gen2 does not support this field + authFlowType: .userSRP, + hostedUIConfig: hostedUIConfig, + passwordProtectionSettings: passwordProtectionSettings, + usernameAttributes: usernameAttributes, + signUpAttributes: signUpAttributes, + verificationMechanisms: verificationMechanisms + ) } static func parseHostedConfiguration(configuration: JSONValue?) -> HostedUIConfigurationData? { @@ -142,44 +145,55 @@ struct ConfigurationHelper { clientSecret = appClientSecret } - return createHostedConfiguration(appClientId: appClientId, - clientSecret: clientSecret, - domain: domain, - scopes: scopesArray, - signInRedirectURI: signInRedirectURI, - signOutRedirectURI: signOutRedirectURI) + return createHostedConfiguration( + appClientId: appClientId, + clientSecret: clientSecret, + domain: domain, + scopes: scopesArray, + signInRedirectURI: signInRedirectURI, + signOutRedirectURI: signOutRedirectURI + ) } static func parseHostedConfiguration(configuration: AmplifyOutputsData.Auth) -> HostedUIConfigurationData? { guard let oauth = configuration.oauth, let signInRedirectURI = oauth.redirectSignInUri.first, - let signOutRedirectURI = oauth.redirectSignOutUri.first else { + let signOutRedirectURI = oauth.redirectSignOutUri.first + else { return nil } - return createHostedConfiguration(appClientId: configuration.userPoolClientId, - clientSecret: nil, - domain: oauth.domain, - scopes: oauth.scopes, - signInRedirectURI: signInRedirectURI, - signOutRedirectURI: signOutRedirectURI) + return createHostedConfiguration( + appClientId: configuration.userPoolClientId, + clientSecret: nil, + domain: oauth.domain, + scopes: oauth.scopes, + signInRedirectURI: signInRedirectURI, + signOutRedirectURI: signOutRedirectURI + ) } - static func createHostedConfiguration(appClientId: String, - clientSecret: String?, - domain: String, - scopes: [String], - signInRedirectURI: String, - signOutRedirectURI: String) -> HostedUIConfigurationData { - - let oauth = OAuthConfigurationData(domain: domain, - scopes: scopes, - signInRedirectURI: signInRedirectURI, - signOutRedirectURI: signOutRedirectURI) - - return HostedUIConfigurationData(clientId: appClientId, - oauth: oauth, - clientSecret: clientSecret) + static func createHostedConfiguration( + appClientId: String, + clientSecret: String?, + domain: String, + scopes: [String], + signInRedirectURI: String, + signOutRedirectURI: String + ) -> HostedUIConfigurationData { + + let oauth = OAuthConfigurationData( + domain: domain, + scopes: scopes, + signInRedirectURI: signInRedirectURI, + signOutRedirectURI: signOutRedirectURI + ) + + return HostedUIConfigurationData( + clientId: appClientId, + oauth: oauth, + clientSecret: clientSecret + ) } static func parseIdentityPoolData(_ config: JSONValue) -> IdentityPoolConfigurationData? { @@ -198,8 +212,10 @@ struct ConfigurationHelper { static func parseIdentityPoolData(_ config: AmplifyOutputsData.Auth) -> IdentityPoolConfigurationData? { if let identityPoolId = config.identityPoolId { - return IdentityPoolConfigurationData(poolId: identityPoolId, - region: config.awsRegion) + return IdentityPoolConfigurationData( + poolId: identityPoolId, + region: config.awsRegion + ) } else { return nil } @@ -209,8 +225,10 @@ struct ConfigurationHelper { let userPoolConfig = try parseUserPoolData(config) let identityPoolConfig = parseIdentityPoolData(config) - return try createAuthConfiguration(userPoolConfig: userPoolConfig, - identityPoolConfig: identityPoolConfig) + return try createAuthConfiguration( + userPoolConfig: userPoolConfig, + identityPoolConfig: identityPoolConfig + ) } static func authConfiguration(_ config: AmplifyOutputsData) throws -> AuthConfiguration { @@ -223,13 +241,17 @@ struct ConfigurationHelper { let userPoolConfig = parseUserPoolData(config) let identityPoolConfig = parseIdentityPoolData(config) - return try createAuthConfiguration(userPoolConfig: userPoolConfig, - identityPoolConfig: identityPoolConfig) + return try createAuthConfiguration( + userPoolConfig: userPoolConfig, + identityPoolConfig: identityPoolConfig + ) } - static func createAuthConfiguration(userPoolConfig: UserPoolConfigurationData?, - identityPoolConfig: IdentityPoolConfigurationData?) throws -> AuthConfiguration { + static func createAuthConfiguration( + userPoolConfig: UserPoolConfigurationData?, + identityPoolConfig: IdentityPoolConfigurationData? + ) throws -> AuthConfiguration { if let userPoolConfigNonNil = userPoolConfig, let identityPoolConfigNonNil = identityPoolConfig { return .userPoolsAndIdentityPools(userPoolConfigNonNil, identityPoolConfigNonNil) } @@ -268,17 +290,23 @@ struct ConfigurationHelper { let characterPolicy: [JSONValue] = passwordProtectionSettings.characterPolicy.map { .string($0.rawValue) } authConfigObject = .object( - ["usernameAttributes": .array(usernameAttributes), - "signupAttributes": .array(signUpAttributes), - "verificationMechanism": .array(verificationMechanisms), - "passwordProtectionSettings": .object( - ["passwordPolicyMinLength": .number(Double(minLength)), - "passwordPolicyCharacters": .array(characterPolicy)])]) + [ + "usernameAttributes": .array(usernameAttributes), + "signupAttributes": .array(signUpAttributes), + "verificationMechanism": .array(verificationMechanisms), + "passwordProtectionSettings": .object( + [ + "passwordPolicyMinLength": .number(Double(minLength)), + "passwordPolicyCharacters": .array(characterPolicy) + ]) + ]) } else { authConfigObject = .object( - ["usernameAttributes": .array(usernameAttributes), - "signupAttributes": .array(signUpAttributes), - "verificationMechanism": .array(verificationMechanisms)]) + [ + "usernameAttributes": .array(usernameAttributes), + "signupAttributes": .array(signUpAttributes), + "verificationMechanism": .array(verificationMechanisms) + ]) } return JSONValue.object([ diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/DeviceMetadataHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/DeviceMetadataHelper.swift index f53ae871c3..e85996927e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/DeviceMetadataHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/DeviceMetadataHelper.swift @@ -7,11 +7,12 @@ import AWSPluginsCore -struct DeviceMetadataHelper { +enum DeviceMetadataHelper { static func getDeviceMetadata( for username: String, - with environment: Environment) async -> DeviceMetadata { + with environment: Environment + ) async -> DeviceMetadata { let credentialStoreClient = (environment as? AuthEnvironment)?.credentialsClient do { let data = try await credentialStoreClient?.fetchData( @@ -32,7 +33,8 @@ struct DeviceMetadataHelper { static func removeDeviceMetaData( for username: String, - with environment: Environment) async { + with environment: Environment + ) async { let credentialStoreClient = (environment as? AuthEnvironment)?.credentialsClient do { try await credentialStoreClient?.deleteData( diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/String+Mask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/String+Mask.swift index 7ecbadb633..a95fef66df 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/String+Mask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/String+Mask.swift @@ -42,7 +42,7 @@ public extension String { } } -public extension Optional where Wrapped == String { +public extension String? { func masked( using character: Character = "*", interiorCount: Int = .max, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/TokenParserHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/TokenParserHelper.swift index a35478741c..af861154f1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/TokenParserHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/TokenParserHelper.swift @@ -7,7 +7,7 @@ import Foundation -struct TokenParserHelper { +enum TokenParserHelper { static func getAuthUser(accessToken: String) throws -> AWSAuthUser { let tokenSplit = accessToken.split(separator: ".") @@ -20,11 +20,14 @@ struct TokenParserHelper { let paddedLength = base64.count + (4 - (base64.count % 4)) % 4 let base64Padding = base64.padding(toLength: paddedLength, withPad: "=", startingAt: 0) - guard let encodedData = Data(base64Encoded: base64Padding, - options: .ignoreUnknownCharacters), + guard let encodedData = Data( + base64Encoded: base64Padding, + options: .ignoreUnknownCharacters + ), let jsonObject = try? JSONSerialization.jsonObject( - with: encodedData, - options: []) as? [String: Any] + with: encodedData, + options: [] + ) as? [String: Any] else { throw SignInError.hostedUI(.tokenParsing) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/UserPoolSignInHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/UserPoolSignInHelper.swift index 02a2d74f62..9f54c75924 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/UserPoolSignInHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/UserPoolSignInHelper.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoIdentityProvider +import Foundation struct UserPoolSignInHelper: DefaultLogger { @@ -56,8 +56,10 @@ struct UserPoolSignInHelper: DefaultLogger { return nil } - private static func validateResult(for challengeType: AuthChallengeType, - with challenge: RespondToAuthChallenge) + private static func validateResult( + for challengeType: AuthChallengeType, + with challenge: RespondToAuthChallenge + ) throws -> AuthSignInResult { switch challengeType { case .smsMfa: @@ -92,33 +94,38 @@ struct UserPoolSignInHelper: DefaultLogger { request: RespondToAuthChallengeInput, for username: String, signInMethod: SignInMethod, - environment: UserPoolEnvironment) async throws -> StateMachineEvent { + environment: UserPoolEnvironment + ) async throws -> StateMachineEvent { let client = try environment.cognitoUserPoolFactory() let response = try await client.respondToAuthChallenge(input: request) - let event = self.parseResponse(response, for: username, signInMethod: signInMethod) + let event = parseResponse(response, for: username, signInMethod: signInMethod) return event } static func parseResponse( _ response: SignInResponseBehavior, for username: String, - signInMethod: SignInMethod) -> StateMachineEvent { + signInMethod: SignInMethod + ) -> StateMachineEvent { if let authenticationResult = response.authenticationResult, let idToken = authenticationResult.idToken, let accessToken = authenticationResult.accessToken, let refreshToken = authenticationResult.refreshToken { - let userPoolTokens = AWSCognitoUserPoolTokens(idToken: idToken, - accessToken: accessToken, - refreshToken: refreshToken, - expiresIn: authenticationResult.expiresIn) + let userPoolTokens = AWSCognitoUserPoolTokens( + idToken: idToken, + accessToken: accessToken, + refreshToken: refreshToken, + expiresIn: authenticationResult.expiresIn + ) let signedInData = SignedInData( signedInDate: Date(), signInMethod: signInMethod, deviceMetadata: authenticationResult.deviceMetadata, - cognitoUserPoolTokens: userPoolTokens) + cognitoUserPoolTokens: userPoolTokens + ) switch signedInData.deviceMetadata { case .noData: @@ -133,7 +140,8 @@ struct UserPoolSignInHelper: DefaultLogger { challenge: challengeName, username: username, session: response.session, - parameters: parameters) + parameters: parameters + ) switch challengeName { case .smsMfa, .customChallenge, .newPasswordRequired, .softwareTokenMfa, .selectMfaType: diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/AuthUIPresentationAnchorPlaceholder.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/AuthUIPresentationAnchorPlaceholder.swift index c15d072b39..11eda7f1bb 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/AuthUIPresentationAnchorPlaceholder.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/AuthUIPresentationAnchorPlaceholder.swift @@ -18,8 +18,10 @@ class AuthUIPresentationAnchorPlaceholder: Equatable { private init() {} - public static func == (lhs: AuthUIPresentationAnchorPlaceholder, - rhs: AuthUIPresentationAnchorPlaceholder) -> Bool { + public static func == ( + lhs: AuthUIPresentationAnchorPlaceholder, + rhs: AuthUIPresentationAnchorPlaceholder + ) -> Bool { true } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIASWebAuthenticationSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIASWebAuthenticationSession.swift index 4e42a50c99..623cd85b7b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIASWebAuthenticationSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIASWebAuthenticationSession.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation #if os(iOS) || os(macOS) || os(visionOS) import AuthenticationServices #endif @@ -19,10 +19,11 @@ class HostedUIASWebAuthenticationSession: NSObject, HostedUISessionBehavior { url: URL, callbackScheme: String, inPrivate: Bool, - presentationAnchor: AuthUIPresentationAnchor?) async throws -> [URLQueryItem] { + presentationAnchor: AuthUIPresentationAnchor? + ) async throws -> [URLQueryItem] { #if os(iOS) || os(macOS) || os(visionOS) - self.webPresentation = presentationAnchor + webPresentation = presentationAnchor return try await withCheckedThrowingContinuation { [weak self] (continuation: CheckedContinuation<[URLQueryItem], Error>) in @@ -56,7 +57,8 @@ class HostedUIASWebAuthenticationSession: NSObject, HostedUISessionBehavior { return continuation.resume( throwing: HostedUIError.unknown) } - }) + } + ) aswebAuthenticationSession.presentationContextProvider = self aswebAuthenticationSession.prefersEphemeralWebBrowserSession = inPrivate diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift index 8976659779..aef9ae9671 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift @@ -5,16 +5,18 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CryptoKit +import Foundation -struct HostedUIRequestHelper { +enum HostedUIRequestHelper { - static func createSignInURL(state: String, - proofKey: String, - userContextData: String?, - configuration: HostedUIConfigurationData, - options: HostedUIOptions) throws -> URL { + static func createSignInURL( + state: String, + proofKey: String, + userContextData: String?, + configuration: HostedUIConfigurationData, + options: HostedUIOptions + ) throws -> URL { guard let proofData = proofKey.data(using: .ascii) else { throw HostedUIError.proofCalculation @@ -45,7 +47,7 @@ struct HostedUIRequestHelper { .init(name: "code_challenge", value: codeChallenge) ] - if let userContextData = userContextData { + if let userContextData { components.queryItems?.append( .init(name: "userContextData", value: userContextData)) } @@ -83,12 +85,15 @@ struct HostedUIRequestHelper { return logoutURL } - static func createTokenRequest(configuration: HostedUIConfigurationData, - result: HostedUIResult) throws -> URLRequest { + static func createTokenRequest( + configuration: HostedUIConfigurationData, + result: HostedUIResult + ) throws -> URLRequest { guard let signInRedirectURI = configuration.oauth .signInRedirectURI - .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { + .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) + else { throw HostedUIError.tokenURI } @@ -107,7 +112,8 @@ struct HostedUIRequestHelper { .init(name: "client_id", value: configuration.clientId), .init(name: "code", value: result.code), .init(name: "redirect_uri", value: signInRedirectURI), - .init(name: "code_verifier", value: result.codeVerifier)] + .init(name: "code_verifier", value: result.codeVerifier) + ] guard let body = queryComponents.query else { throw HostedUIError.tokenURI diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUISessionBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUISessionBehavior.swift index 016dd21038..5e08c75301 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUISessionBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUISessionBehavior.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AuthenticationServices import Amplify +import AuthenticationServices +import Foundation protocol HostedUISessionBehavior { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/RandomStringBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/RandomStringBehavior.swift index 259b464c87..9ff9f5adf6 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/RandomStringBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/RandomStringBehavior.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + import Foundation protocol RandomStringBehavior { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmResetPasswordRequest+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmResetPasswordRequest+Validation.swift index 946b5a4bfe..e3a49c1000 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmResetPasswordRequest+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmResetPasswordRequest+Validation.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify extension AuthConfirmResetPasswordRequest { @@ -13,19 +14,22 @@ extension AuthConfirmResetPasswordRequest { return AuthError.validation( AuthPluginErrorConstants.confirmResetPasswordUsernameError.field, AuthPluginErrorConstants.confirmResetPasswordUsernameError.errorDescription, - AuthPluginErrorConstants.confirmResetPasswordUsernameError.recoverySuggestion) + AuthPluginErrorConstants.confirmResetPasswordUsernameError.recoverySuggestion + ) } guard !newPassword.isEmpty else { return AuthError.validation( AuthPluginErrorConstants.confirmResetPasswordNewPasswordError.field, AuthPluginErrorConstants.confirmResetPasswordNewPasswordError.errorDescription, - AuthPluginErrorConstants.confirmResetPasswordNewPasswordError.recoverySuggestion) + AuthPluginErrorConstants.confirmResetPasswordNewPasswordError.recoverySuggestion + ) } guard !confirmationCode.isEmpty else { return AuthError.validation( AuthPluginErrorConstants.confirmResetPasswordCodeError.field, AuthPluginErrorConstants.confirmResetPasswordCodeError.errorDescription, - AuthPluginErrorConstants.confirmResetPasswordCodeError.recoverySuggestion) + AuthPluginErrorConstants.confirmResetPasswordCodeError.recoverySuggestion + ) } return nil } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignInRequest+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignInRequest+Validation.swift index c310f51bcc..ab032ff029 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignInRequest+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignInRequest+Validation.swift @@ -4,15 +4,18 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify extension AuthConfirmSignInRequest { func hasError() -> AuthError? { guard !challengeResponse.isEmpty else { - return AuthError.validation(AuthPluginErrorConstants.confirmSignInChallengeResponseError.field, - AuthPluginErrorConstants.confirmSignInChallengeResponseError.errorDescription, - AuthPluginErrorConstants.confirmSignInChallengeResponseError.recoverySuggestion) + return AuthError.validation( + AuthPluginErrorConstants.confirmSignInChallengeResponseError.field, + AuthPluginErrorConstants.confirmSignInChallengeResponseError.errorDescription, + AuthPluginErrorConstants.confirmSignInChallengeResponseError.recoverySuggestion + ) } return nil } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignUpRequest+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignUpRequest+Validation.swift index d53fe6c0f3..8a06538a7b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignUpRequest+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignUpRequest+Validation.swift @@ -15,15 +15,17 @@ extension AuthConfirmSignUpRequest { let error = AuthError.validation( AuthPluginErrorConstants.signUpUsernameError.field, AuthPluginErrorConstants.signUpUsernameError.errorDescription, - AuthPluginErrorConstants.signUpUsernameError.recoverySuggestion, nil) + AuthPluginErrorConstants.signUpUsernameError.recoverySuggestion, nil + ) throw error } guard !code.isEmpty else { let error = AuthError.validation( - AuthPluginErrorConstants.confirmSignUpCodeError.field, - AuthPluginErrorConstants.confirmSignUpCodeError.errorDescription, - AuthPluginErrorConstants.confirmSignUpCodeError.recoverySuggestion, nil) + AuthPluginErrorConstants.confirmSignUpCodeError.field, + AuthPluginErrorConstants.confirmSignUpCodeError.errorDescription, + AuthPluginErrorConstants.confirmSignUpCodeError.recoverySuggestion, nil + ) throw error } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResendSignUpCodeRequest+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResendSignUpCodeRequest+Validation.swift index 01f61e1f78..d476cf6b0a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResendSignUpCodeRequest+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResendSignUpCodeRequest+Validation.swift @@ -4,15 +4,18 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify extension AuthResendSignUpCodeRequest { func hasError() -> AuthError? { guard !username.isEmpty else { - return AuthError.validation(AuthPluginErrorConstants.resendSignUpCodeUsernameError.field, - AuthPluginErrorConstants.resendSignUpCodeUsernameError.errorDescription, - AuthPluginErrorConstants.resendSignUpCodeUsernameError.recoverySuggestion) + return AuthError.validation( + AuthPluginErrorConstants.resendSignUpCodeUsernameError.field, + AuthPluginErrorConstants.resendSignUpCodeUsernameError.errorDescription, + AuthPluginErrorConstants.resendSignUpCodeUsernameError.recoverySuggestion + ) } return nil } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResetPasswordRequest+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResetPasswordRequest+Validation.swift index 817d16c4fc..7ce3c9dfdc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResetPasswordRequest+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResetPasswordRequest+Validation.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify extension AuthResetPasswordRequest { @@ -13,7 +14,8 @@ extension AuthResetPasswordRequest { return AuthError.validation( AuthPluginErrorConstants.resetPasswordUsernameError.field, AuthPluginErrorConstants.resetPasswordUsernameError.errorDescription, - AuthPluginErrorConstants.resetPasswordUsernameError.recoverySuggestion) + AuthPluginErrorConstants.resetPasswordUsernameError.recoverySuggestion + ) } return nil } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthSignUpRequest+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthSignUpRequest+Validation.swift index 4ca839b39b..a9e57830b2 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthSignUpRequest+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthSignUpRequest+Validation.swift @@ -14,7 +14,8 @@ extension AuthSignUpRequest { let error = AuthError.validation( AuthPluginErrorConstants.signUpUsernameError.field, AuthPluginErrorConstants.signUpUsernameError.errorDescription, - AuthPluginErrorConstants.signUpUsernameError.recoverySuggestion, nil) + AuthPluginErrorConstants.signUpUsernameError.recoverySuggestion, nil + ) throw error } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/ConfirmSignUpInput+Amplify.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/ConfirmSignUpInput+Amplify.swift index 6d3fea6612..3db5c1d858 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/ConfirmSignUpInput+Amplify.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/ConfirmSignUpInput+Amplify.swift @@ -5,29 +5,32 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation extension ConfirmSignUpInput { - init(username: String, - confirmationCode: String, - clientMetadata: [String: String]?, - asfDeviceId: String?, - forceAliasCreation: Bool?, - environment: UserPoolEnvironment + init( + username: String, + confirmationCode: String, + clientMetadata: [String: String]?, + asfDeviceId: String?, + forceAliasCreation: Bool?, + environment: UserPoolEnvironment ) async { let configuration = environment.userPoolConfiguration let secretHash = ClientSecretHelper.calculateSecretHash( username: username, - userPoolConfiguration: configuration) + userPoolConfiguration: configuration + ) var userContextData: CognitoIdentityProviderClientTypes.UserContextDataType? - if let asfDeviceId = asfDeviceId, + if let asfDeviceId, let encodedData = await CognitoUserPoolASF.encodedContext( - username: username, - asfDeviceId: asfDeviceId, - asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: environment.userPoolConfiguration) { + username: username, + asfDeviceId: asfDeviceId, + asfClient: environment.cognitoUserPoolASFFactory(), + userPoolConfiguration: environment.userPoolConfiguration + ) { userContextData = .init(encodedData: encodedData) } let analyticsMetadata = environment @@ -41,6 +44,7 @@ extension ConfirmSignUpInput { forceAliasCreation: forceAliasCreation, secretHash: secretHash, userContextData: userContextData, - username: username) + username: username + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/HttpClientEngineProxy.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/HttpClientEngineProxy.swift index 2a2fe1153b..e836970857 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/HttpClientEngineProxy.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/HttpClientEngineProxy.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -@_spi(InternalHttpEngineProxy) @_spi(InternalAmplifyPluginExtension) import InternalAmplifyCredentials import Foundation +@_spi(InternalHttpEngineProxy) @_spi(InternalAmplifyPluginExtension) import InternalAmplifyCredentials import SmithyHTTPAPI protocol HttpClientEngineProxy: HTTPClient { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/InitiateAuthInput+Amplify.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/InitiateAuthInput+Amplify.swift index fbda1ffbc0..daf5077e44 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/InitiateAuthInput+Amplify.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/InitiateAuthInput+Amplify.swift @@ -5,18 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation extension InitiateAuthInput { - static func srpInput(username: String, - publicSRPAHexValue: String, - authFlowType: AuthFlowType, - clientMetadata: [String: String], - asfDeviceId: String, - deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> InitiateAuthInput { + static func srpInput( + username: String, + publicSRPAHexValue: String, + authFlowType: AuthFlowType, + clientMetadata: [String: String], + asfDeviceId: String, + deviceMetadata: DeviceMetadata, + environment: UserPoolEnvironment + ) async -> InitiateAuthInput { var authParameters = [ "USERNAME": username, "SRP_A": publicSRPAHexValue @@ -28,81 +30,97 @@ extension InitiateAuthInput { authParameters["CHALLENGE_NAME"] = "SRP_A" } - return await buildInput(username: username, - authFlowType: authFlowType.getClientFlowType(), - authParameters: authParameters, - clientMetadata: clientMetadata, - asfDeviceId: asfDeviceId, - deviceMetadata: deviceMetadata, - environment: environment) + return await buildInput( + username: username, + authFlowType: authFlowType.getClientFlowType(), + authParameters: authParameters, + clientMetadata: clientMetadata, + asfDeviceId: asfDeviceId, + deviceMetadata: deviceMetadata, + environment: environment + ) } - static func customAuth(username: String, - clientMetadata: [String: String], - asfDeviceId: String, - deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> InitiateAuthInput { + static func customAuth( + username: String, + clientMetadata: [String: String], + asfDeviceId: String, + deviceMetadata: DeviceMetadata, + environment: UserPoolEnvironment + ) async -> InitiateAuthInput { let authParameters = [ "USERNAME": username ] - return await buildInput(username: username, - authFlowType: .customAuth, - authParameters: authParameters, - clientMetadata: clientMetadata, - asfDeviceId: asfDeviceId, - deviceMetadata: deviceMetadata, - environment: environment) + return await buildInput( + username: username, + authFlowType: .customAuth, + authParameters: authParameters, + clientMetadata: clientMetadata, + asfDeviceId: asfDeviceId, + deviceMetadata: deviceMetadata, + environment: environment + ) } - static func migrateAuth(username: String, - password: String, - clientMetadata: [String: String], - asfDeviceId: String, - deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> InitiateAuthInput { + static func migrateAuth( + username: String, + password: String, + clientMetadata: [String: String], + asfDeviceId: String, + deviceMetadata: DeviceMetadata, + environment: UserPoolEnvironment + ) async -> InitiateAuthInput { let authParameters = [ "USERNAME": username, "PASSWORD": password ] - return await buildInput(username: username, - authFlowType: .userPasswordAuth, - authParameters: authParameters, - clientMetadata: clientMetadata, - asfDeviceId: asfDeviceId, - deviceMetadata: deviceMetadata, - environment: environment) + return await buildInput( + username: username, + authFlowType: .userPasswordAuth, + authParameters: authParameters, + clientMetadata: clientMetadata, + asfDeviceId: asfDeviceId, + deviceMetadata: deviceMetadata, + environment: environment + ) } - static func refreshAuthInput(username: String, - refreshToken: String, - clientMetadata: [String: String], - asfDeviceId: String, - deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> InitiateAuthInput { + static func refreshAuthInput( + username: String, + refreshToken: String, + clientMetadata: [String: String], + asfDeviceId: String, + deviceMetadata: DeviceMetadata, + environment: UserPoolEnvironment + ) async -> InitiateAuthInput { let authParameters = [ "REFRESH_TOKEN": refreshToken ] - return await buildInput(username: username, - authFlowType: .refreshTokenAuth, - authParameters: authParameters, - clientMetadata: clientMetadata, - asfDeviceId: asfDeviceId, - deviceMetadata: deviceMetadata, - environment: environment) + return await buildInput( + username: username, + authFlowType: .refreshTokenAuth, + authParameters: authParameters, + clientMetadata: clientMetadata, + asfDeviceId: asfDeviceId, + deviceMetadata: deviceMetadata, + environment: environment + ) } - static func buildInput(username: String, - authFlowType: CognitoIdentityProviderClientTypes.AuthFlowType, - authParameters: [String: String], - clientMetadata: [String: String], - asfDeviceId: String?, - deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> InitiateAuthInput { + static func buildInput( + username: String, + authFlowType: CognitoIdentityProviderClientTypes.AuthFlowType, + authParameters: [String: String], + clientMetadata: [String: String], + asfDeviceId: String?, + deviceMetadata: DeviceMetadata, + environment: UserPoolEnvironment + ) async -> InitiateAuthInput { var authParameters = authParameters let configuration = environment.userPoolConfiguration @@ -122,12 +140,13 @@ extension InitiateAuthInput { } var userContextData: CognitoIdentityProviderClientTypes.UserContextDataType? - if let asfDeviceId = asfDeviceId, + if let asfDeviceId, let encodedData = await CognitoUserPoolASF.encodedContext( - username: username, - asfDeviceId: asfDeviceId, - asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: environment.userPoolConfiguration) { + username: username, + asfDeviceId: asfDeviceId, + asfClient: environment.cognitoUserPoolASFFactory(), + userPoolConfiguration: environment.userPoolConfiguration + ) { userContextData = .init(encodedData: encodedData) } let analyticsMetadata = environment @@ -140,6 +159,7 @@ extension InitiateAuthInput { authParameters: authParameters, clientId: userPoolClientId, clientMetadata: clientMetadata, - userContextData: userContextData) + userContextData: userContextData + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/RespondToAuthChallengeInput+Amplify.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/RespondToAuthChallengeInput+Amplify.swift index 8132c97e28..d7fbea05ed 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/RespondToAuthChallengeInput+Amplify.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/RespondToAuthChallengeInput+Amplify.swift @@ -5,27 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation extension RespondToAuthChallengeInput { // swiftlint:disable:next function_parameter_count - static func passwordVerifier(username: String, - stateData: SRPStateData, - session: String?, - secretBlock: String, - signature: String, - clientMetadata: ClientMetadata, - deviceMetadata: DeviceMetadata, - asfDeviceId: String?, - environment: UserPoolEnvironment) async -> RespondToAuthChallengeInput { + static func passwordVerifier( + username: String, + stateData: SRPStateData, + session: String?, + secretBlock: String, + signature: String, + clientMetadata: ClientMetadata, + deviceMetadata: DeviceMetadata, + asfDeviceId: String?, + environment: UserPoolEnvironment + ) async -> RespondToAuthChallengeInput { let dateStr = stateData.clientTimestamp.utcString let challengeResponses = [ "USERNAME": username, "TIMESTAMP": dateStr, "PASSWORD_CLAIM_SECRET_BLOCK": secretBlock, - "PASSWORD_CLAIM_SIGNATURE": signature] + "PASSWORD_CLAIM_SIGNATURE": signature + ] return await buildInput( username: username, challengeType: .passwordVerifier, @@ -34,16 +37,19 @@ extension RespondToAuthChallengeInput { clientMetadata: clientMetadata, asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: environment) + environment: environment + ) } // swiftlint:disable:next function_parameter_count - static func deviceSRP(username: String, - environment: UserPoolEnvironment, - deviceMetadata: DeviceMetadata, - asfDeviceId: String?, - session: String?, - publicHexValue: String) async -> RespondToAuthChallengeInput { + static func deviceSRP( + username: String, + environment: UserPoolEnvironment, + deviceMetadata: DeviceMetadata, + asfDeviceId: String?, + session: String?, + publicHexValue: String + ) async -> RespondToAuthChallengeInput { let challengeResponses = [ "USERNAME": username, "SRP_A": publicHexValue @@ -56,24 +62,28 @@ extension RespondToAuthChallengeInput { clientMetadata: [:], asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: environment) + environment: environment + ) } - static func devicePasswordVerifier(username: String, - stateData: SRPStateData, - session: String?, - secretBlock: String, - signature: String, - deviceMetadata: DeviceMetadata, - asfDeviceId: String?, - environment: UserPoolEnvironment) async + static func devicePasswordVerifier( + username: String, + stateData: SRPStateData, + session: String?, + secretBlock: String, + signature: String, + deviceMetadata: DeviceMetadata, + asfDeviceId: String?, + environment: UserPoolEnvironment + ) async -> RespondToAuthChallengeInput { let dateStr = stateData.clientTimestamp.utcString let challengeResponses = [ "USERNAME": username, "TIMESTAMP": dateStr, "PASSWORD_CLAIM_SECRET_BLOCK": secretBlock, - "PASSWORD_CLAIM_SIGNATURE": signature] + "PASSWORD_CLAIM_SIGNATURE": signature + ] return await buildInput( username: username, challengeType: .devicePasswordVerifier, @@ -82,7 +92,8 @@ extension RespondToAuthChallengeInput { clientMetadata: [:], asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: environment) + environment: environment + ) } // swiftlint:disable:next function_parameter_count @@ -96,7 +107,8 @@ extension RespondToAuthChallengeInput { asfDeviceId: String?, attributes: [String: String], deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> RespondToAuthChallengeInput { + environment: UserPoolEnvironment + ) async -> RespondToAuthChallengeInput { var challengeResponses = [ "USERNAME": username, @@ -104,8 +116,8 @@ extension RespondToAuthChallengeInput { ] // Add the attributes to the challenge response - attributes.forEach { - challengeResponses[$0.key] = $0.value + for attribute in attributes { + challengeResponses[attribute.key] = attribute.value } return await buildInput( username: username, @@ -115,7 +127,8 @@ extension RespondToAuthChallengeInput { clientMetadata: clientMetadata ?? [:], asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: environment) + environment: environment + ) } static func buildInput( @@ -126,7 +139,8 @@ extension RespondToAuthChallengeInput { clientMetadata: ClientMetadata, asfDeviceId: String?, deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> RespondToAuthChallengeInput { + environment: UserPoolEnvironment + ) async -> RespondToAuthChallengeInput { var challengeResponses = challengeResponses let userPoolClientId = environment.userPoolConfiguration.clientId if let clientSecret = environment.userPoolConfiguration.clientSecret { @@ -144,12 +158,13 @@ extension RespondToAuthChallengeInput { } var userContextData: CognitoIdentityProviderClientTypes.UserContextDataType? - if let asfDeviceId = asfDeviceId, + if let asfDeviceId, let encodedData = await CognitoUserPoolASF.encodedContext( - username: username, - asfDeviceId: asfDeviceId, - asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: environment.userPoolConfiguration) { + username: username, + asfDeviceId: asfDeviceId, + asfClient: environment.cognitoUserPoolASFFactory(), + userPoolConfiguration: environment.userPoolConfiguration + ) { userContextData = .init(encodedData: encodedData) } @@ -164,7 +179,8 @@ extension RespondToAuthChallengeInput { clientId: userPoolClientId, clientMetadata: clientMetadata, session: session, - userContextData: userContextData) + userContextData: userContextData + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/SignUpInput+Amplify.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/SignUpInput+Amplify.swift index bec03bab9b..a0f90a991c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/SignUpInput+Amplify.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/SignUpInput+Amplify.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation #if canImport(WatchKit) import WatchKit #elseif canImport(UIKit) @@ -15,50 +15,59 @@ import UIKit extension SignUpInput { typealias CognitoAttributeType = CognitoIdentityProviderClientTypes.AttributeType - init(username: String, - password: String, - clientMetadata: [String: String]?, - validationData: [String: String]?, - attributes: [String: String], - asfDeviceId: String?, - environment: UserPoolEnvironment) async { + init( + username: String, + password: String, + clientMetadata: [String: String]?, + validationData: [String: String]?, + attributes: [String: String], + asfDeviceId: String?, + environment: UserPoolEnvironment + ) async { let configuration = environment.userPoolConfiguration - let secretHash = ClientSecretHelper.calculateSecretHash(username: username, - userPoolConfiguration: configuration) + let secretHash = ClientSecretHelper.calculateSecretHash( + username: username, + userPoolConfiguration: configuration + ) let validationData = await Self.getValidationData(with: validationData) let convertedAttributes = Self.convertAttributes(attributes) var userContextData: CognitoIdentityProviderClientTypes.UserContextDataType? - if let asfDeviceId = asfDeviceId, + if let asfDeviceId, let encodedData = await CognitoUserPoolASF.encodedContext( - username: username, - asfDeviceId: asfDeviceId, - asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: environment.userPoolConfiguration) { + username: username, + asfDeviceId: asfDeviceId, + asfClient: environment.cognitoUserPoolASFFactory(), + userPoolConfiguration: environment.userPoolConfiguration + ) { userContextData = .init(encodedData: encodedData) } let analyticsMetadata = environment .cognitoUserPoolAnalyticsHandlerFactory() .analyticsMetadata() - self.init(analyticsMetadata: analyticsMetadata, - clientId: configuration.clientId, - clientMetadata: clientMetadata, - password: password, - secretHash: secretHash, - userAttributes: convertedAttributes, - userContextData: userContextData, - username: username, - validationData: validationData) + self.init( + analyticsMetadata: analyticsMetadata, + clientId: configuration.clientId, + clientMetadata: clientMetadata, + password: password, + secretHash: secretHash, + userAttributes: convertedAttributes, + userContextData: userContextData, + username: username, + validationData: validationData + ) } private static func getValidationData(with devProvidedData: [String: String]?) async -> [CognitoIdentityProviderClientTypes.AttributeType]? { - if let devProvidedData = devProvidedData { - return devProvidedData.compactMap { (key, value) in + // swiftformat:disable all + if let devProvidedData { + return devProvidedData.compactMap { key, value in return CognitoIdentityProviderClientTypes.AttributeType(name: key, value: value) } + (await cognitoValidationData ?? []) } + // swiftformat:enable all return await cognitoValidationData } @@ -98,8 +107,10 @@ extension SignUpInput { private static func convertAttributes(_ attributes: [String: String]) -> [CognitoIdentityProviderClientTypes.AttributeType] { return attributes.reduce(into: [CognitoIdentityProviderClientTypes.AttributeType]()) { - $0.append(CognitoIdentityProviderClientTypes.AttributeType(name: $1.key, - value: $1.value)) + $0.append(CognitoIdentityProviderClientTypes.AttributeType( + name: $1.key, + value: $1.value + )) } } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift index 84921606c9..d1b4258389 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import Foundation class AWSAuthChangePasswordTask: AuthChangePasswordTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -22,9 +22,10 @@ class AWSAuthChangePasswordTask: AuthChangePasswordTask, DefaultLogger { HubPayload.EventName.Auth.changePasswordAPI } - init(_ request: AuthChangePasswordRequest, - authStateMachine: AuthStateMachine, - userPoolFactory: @escaping CognitoUserPoolFactory + init( + _ request: AuthChangePasswordRequest, + authStateMachine: AuthStateMachine, + userPoolFactory: @escaping CognitoUserPoolFactory ) { self.request = request self.authStateMachine = authStateMachine @@ -51,9 +52,11 @@ class AWSAuthChangePasswordTask: AuthChangePasswordTask, DefaultLogger { func changePassword(with accessToken: String) async throws { let userPoolService = try userPoolFactory() - let input = ChangePasswordInput(accessToken: accessToken, - previousPassword: request.oldPassword, - proposedPassword: request.newPassword) + let input = ChangePasswordInput( + accessToken: accessToken, + previousPassword: request.oldPassword, + proposedPassword: request.newPassword + ) _ = try await userPoolService.changePassword(input: input) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthClearFederationToIdentityPoolTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthClearFederationToIdentityPoolTask.swift index c42bbc3ff1..02e7987553 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthClearFederationToIdentityPoolTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthClearFederationToIdentityPoolTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthClearFederationToIdentityPoolTask: AmplifyAuthTask where Request == AuthClearFederationToIdentityPoolRequest, Success == Void, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift index ffa1750e4a..6a5f08ab90 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthConfirmResetPasswordTask: AuthConfirmResetPasswordTask, DefaultLogger { private let request: AuthConfirmResetPasswordRequest @@ -60,12 +60,14 @@ class AWSAuthConfirmResetPasswordTask: AuthConfirmResetPasswordTask, DefaultLogg let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: request.username, - credentialStoreClient: environment.credentialsClient) + credentialStoreClient: environment.credentialsClient + ) let encodedData = await CognitoUserPoolASF.encodedContext( username: request.username, asfDeviceId: asfDeviceId, asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: userPoolConfigurationData) + userPoolConfiguration: userPoolConfigurationData + ) let userContextData = CognitoIdentityProviderClientTypes.UserContextDataType( encodedData: encodedData) let analyticsMetadata = userPoolEnvironment @@ -83,7 +85,8 @@ class AWSAuthConfirmResetPasswordTask: AuthConfirmResetPasswordTask, DefaultLogg password: request.newPassword, secretHash: secretHash, userContextData: userContextData, - username: request.username) + username: request.username + ) _ = try await userPoolService.confirmForgotPassword(input: input) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignInTask.swift index cc824c6f25..70e1b8539b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignInTask.swift @@ -4,9 +4,10 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify import AWSPluginsCore +import Foundation class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { @@ -19,9 +20,11 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { HubPayload.EventName.Auth.confirmSignInAPI } - init(_ request: AuthConfirmSignInRequest, - stateMachine: AuthStateMachine, - configuration: AuthConfiguration) { + init( + _ request: AuthConfirmSignInRequest, + stateMachine: AuthStateMachine, + configuration: AuthConfiguration + ) { self.request = request self.authStateMachine = stateMachine self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine) @@ -36,7 +39,8 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { let message = AuthPluginErrorConstants.configurationError let authError = AuthError.configuration( "Could not find user pool configuration", - message) + message + ) throw authError } @@ -45,10 +49,12 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { } let invalidStateError = AuthError.invalidState( "User is not attempting signIn operation", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) guard case .configured(let authNState, _) = await authStateMachine.currentState, - case .signingIn(let signInState) = authNState else { + case .signingIn(let signInState) = authNState + else { throw invalidStateError } @@ -99,8 +105,9 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { return result case .notConfigured: throw AuthError.configuration( - "UserPool configuration is missing", - AuthPluginErrorConstants.configurationError) + "UserPool configuration is missing", + AuthPluginErrorConstants.configurationError + ) default: throw invalidStateError } @@ -115,7 +122,8 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { throw AuthError.validation( AuthPluginErrorConstants.confirmSignInMFASelectionResponseError.field, AuthPluginErrorConstants.confirmSignInMFASelectionResponseError.errorDescription, - AuthPluginErrorConstants.confirmSignInMFASelectionResponseError.recoverySuggestion) + AuthPluginErrorConstants.confirmSignInMFASelectionResponseError.recoverySuggestion + ) } } @@ -141,10 +149,11 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { $0[attributePrefix + $1.key.rawValue] = $1.value } ?? [:] return ConfirmSignInEventData( - answer: self.request.challengeResponse, + answer: request.challengeResponse, attributes: attributes, metadata: pluginOptions?.metadata, - friendlyDeviceName: pluginOptions?.friendlyDeviceName) + friendlyDeviceName: pluginOptions?.friendlyDeviceName + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift index a7b7124245..2ed662314d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoIdentityProvider +import Foundation class AWSAuthConfirmSignUpTask: AuthConfirmSignUpTask, DefaultLogger { @@ -30,16 +30,19 @@ class AWSAuthConfirmSignUpTask: AuthConfirmSignUpTask, DefaultLogger { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: request.username, - credentialStoreClient: authEnvironment.credentialsClient) + credentialStoreClient: authEnvironment.credentialsClient + ) let metadata = (request.options.pluginOptions as? AWSAuthConfirmSignUpOptions)?.metadata let forceAliasCreation = (request.options.pluginOptions as? AWSAuthConfirmSignUpOptions)?.forceAliasCreation let client = try userPoolEnvironment.cognitoUserPoolFactory() - let input = await ConfirmSignUpInput(username: request.username, - confirmationCode: request.code, - clientMetadata: metadata, - asfDeviceId: asfDeviceId, - forceAliasCreation: forceAliasCreation, - environment: userPoolEnvironment) + let input = await ConfirmSignUpInput( + username: request.username, + confirmationCode: request.code, + clientMetadata: metadata, + asfDeviceId: asfDeviceId, + forceAliasCreation: forceAliasCreation, + environment: userPoolEnvironment + ) _ = try await client.confirmSignUp(input: input) log.verbose("Received success") return AuthSignUpResult(.done, userID: nil) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthDeleteUserTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthDeleteUserTask.swift index 2a0fbf7323..398f8d12b3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthDeleteUserTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthDeleteUserTask.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation class AWSAuthDeleteUserTask: AuthDeleteUserTask, DefaultLogger { private let authStateMachine: AuthStateMachine @@ -18,8 +18,10 @@ class AWSAuthDeleteUserTask: AuthDeleteUserTask, DefaultLogger { HubPayload.EventName.Auth.deleteUserAPI } - init(authStateMachine: AuthStateMachine, - authConfiguraiton: AuthConfiguration) { + init( + authStateMachine: AuthStateMachine, + authConfiguraiton: AuthConfiguration + ) { self.authStateMachine = authStateMachine self.configuration = authConfiguraiton self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine) @@ -50,7 +52,8 @@ class AWSAuthDeleteUserTask: AuthDeleteUserTask, DefaultLogger { let error = AuthError.invalidState( "Auth state should be in configured state and authentication state should be in deleting user state", AuthPluginErrorConstants.invalidStateError, - nil) + nil + ) throw error } @@ -71,7 +74,8 @@ class AWSAuthDeleteUserTask: AuthDeleteUserTask, DefaultLogger { private func signOutIfUserWasNotFound(with error: Error) async { guard case AuthError.service(_, _, let underlyingError) = error, - case .userNotFound = (underlyingError as? AWSCognitoAuthError) else { + case .userNotFound = (underlyingError as? AWSCognitoAuthError) + else { return } log.verbose("User not found, signing out") diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFederateToIdentityPoolTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFederateToIdentityPoolTask.swift index 1770b532c9..b71a0d0892 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFederateToIdentityPoolTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFederateToIdentityPoolTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthFederateToIdentityPoolTask: AmplifyAuthTask where Request == AuthFederateToIdentityPoolRequest, Success == FederateToIdentityPoolResult, @@ -39,7 +39,8 @@ public class AWSAuthFederateToIdentityPoolTask: AuthFederateToIdentityPoolTask, guard case .configured(let authNState, let authZState) = state else { throw AuthError.invalidState( "Federation could not be completed.", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) } if isValidAuthNStateToStart(authNState) && isValidAuthZStateToStart(authZState) { @@ -47,7 +48,8 @@ public class AWSAuthFederateToIdentityPoolTask: AuthFederateToIdentityPoolTask, } else { throw AuthError.invalidState( "Federation could not be completed.", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) } } @@ -105,7 +107,8 @@ public class AWSAuthFederateToIdentityPoolTask: AuthFederateToIdentityPoolTask, case .identityPoolWithFederation(_, let identityId, let awsCredentials): let federatedResult = FederateToIdentityPoolResult( credentials: awsCredentials, - identityId: identityId) + identityId: identityId + ) return federatedResult default: throw AuthError.unknown("Unable to parse credentials to expected output", nil) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFetchSessionTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFetchSessionTask.swift index f39263578d..6aeb85949a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFetchSessionTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFetchSessionTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation class AWSAuthFetchSessionTask: AuthFetchSessionTask, DefaultLogger { private let request: AuthFetchSessionRequest @@ -28,8 +28,10 @@ class AWSAuthFetchSessionTask: AuthFetchSessionTask, DefaultLogger { func execute() async throws -> AuthSession { await taskHelper.didStateMachineConfigured() let doesNeedForceRefresh = request.options.forceRefresh - return try await fetchAuthSessionHelper.fetch(authStateMachine, - forceRefresh: doesNeedForceRefresh) + return try await fetchAuthSessionHelper.fetch( + authStateMachine, + forceRefresh: doesNeedForceRefresh + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift index ff81fc2a56..66b2dd243f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthResendSignUpCodeTask: AuthResendSignUpCodeTask, DefaultLogger { private let request: AuthResendSignUpCodeRequest @@ -60,12 +60,14 @@ class AWSAuthResendSignUpCodeTask: AuthResendSignUpCodeTask, DefaultLogger { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: request.username, - credentialStoreClient: environment.credentialsClient) + credentialStoreClient: environment.credentialsClient + ) let encodedData = await CognitoUserPoolASF.encodedContext( username: request.username, asfDeviceId: asfDeviceId, asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: userPoolConfigurationData) + userPoolConfiguration: userPoolConfigurationData + ) let userContextData = CognitoIdentityProviderClientTypes.UserContextDataType( encodedData: encodedData) let analyticsMetadata = userPoolEnvironment @@ -81,7 +83,8 @@ class AWSAuthResendSignUpCodeTask: AuthResendSignUpCodeTask, DefaultLogger { clientMetadata: clientMetaData, secretHash: secretHash, userContextData: userContextData, - username: request.username) + username: request.username + ) let result = try await userPoolService.resendConfirmationCode(input: input) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResetPasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResetPasswordTask.swift index 7f86e40f58..9d6e2c028a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResetPasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResetPasswordTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthResetPasswordTask: AuthResetPasswordTask, DefaultLogger { @@ -60,12 +60,14 @@ class AWSAuthResetPasswordTask: AuthResetPasswordTask, DefaultLogger { } let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: request.username, - credentialStoreClient: environment.credentialsClient) + credentialStoreClient: environment.credentialsClient + ) let encodedData = await CognitoUserPoolASF.encodedContext( username: request.username, asfDeviceId: asfDeviceId, asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: userPoolConfigurationData) + userPoolConfiguration: userPoolConfigurationData + ) let userContextData = CognitoIdentityProviderClientTypes.UserContextDataType( encodedData: encodedData) let analyticsMetadata = userPoolEnvironment @@ -81,7 +83,8 @@ class AWSAuthResetPasswordTask: AuthResetPasswordTask, DefaultLogger { clientMetadata: clientMetaData, secretHash: secretHash, userContextData: userContextData, - username: request.username) + username: request.username + ) let result = try await userPoolService.forgotPassword(input: input) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignInTask.swift index abfe5ec41b..965c423e3d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignInTask.swift @@ -4,9 +4,10 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify import AWSPluginsCore +import Foundation class AWSAuthSignInTask: AuthSignInTask, DefaultLogger { @@ -19,9 +20,11 @@ class AWSAuthSignInTask: AuthSignInTask, DefaultLogger { HubPayload.EventName.Auth.signInAPI } - init(_ request: AuthSignInRequest, - authStateMachine: AuthStateMachine, - configuration: AuthConfiguration) { + init( + _ request: AuthSignInRequest, + authStateMachine: AuthStateMachine, + configuration: AuthConfiguration + ) { self.request = request self.authStateMachine = authStateMachine self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine) @@ -35,7 +38,8 @@ class AWSAuthSignInTask: AuthSignInTask, DefaultLogger { let message = AuthPluginErrorConstants.configurationError let authError = AuthError.configuration( "Could not find user pool configuration", - message) + message + ) throw authError } @@ -66,7 +70,8 @@ class AWSAuthSignInTask: AuthSignInTask, DefaultLogger { case .signedIn: let error = AuthError.invalidState( "There is already a user in signedIn state. SignOut the user first before calling signIn", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) throw error case .signingIn: log.verbose("Cancelling existing signIn flow") @@ -84,8 +89,10 @@ class AWSAuthSignInTask: AuthSignInTask, DefaultLogger { await sendSignInEvent(authflowType: authflowType) log.verbose("Waiting for signin to complete") for await state in stateSequences { - guard case .configured(let authNState, - let authZState) = state else { continue } + guard case .configured( + let authNState, + let authZState + ) = state else { continue } switch authNState { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignOutTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignOutTask.swift index 5ac5e39295..9aeaca6145 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignOutTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignOutTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation class AWSAuthSignOutTask: AuthSignOutTask, DefaultLogger { @@ -38,7 +38,8 @@ class AWSAuthSignOutTask: AuthSignOutTask, DefaultLogger { } else if case .federatedToIdentityPool = authNState { let invalidStateError = AuthError.invalidState( "The user is currently federated to identity pool. You must call clearFederationToIdentityPool to clear credentials.", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) return AWSCognitoSignOutResult.failed(invalidStateError) } else { return invalidStateResult() diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignUpTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignUpTask.swift index 63194bcea9..1db9eb0b2d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignUpTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignUpTask.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AWSCognitoIdentityProvider import Amplify +import AWSCognitoIdentityProvider +import Foundation class AWSAuthSignUpTask: AuthSignUpTask, DefaultLogger { @@ -35,18 +35,21 @@ class AWSAuthSignUpTask: AuthSignUpTask, DefaultLogger { let client = try userPoolEnvironment.cognitoUserPoolFactory() let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: request.username, - credentialStoreClient: authEnvironment.credentialsClient) + credentialStoreClient: authEnvironment.credentialsClient + ) let attributes = request.options.userAttributes?.reduce( into: [String: String]()) { $0[$1.key.rawValue] = $1.value } ?? [:] - let input = await SignUpInput(username: request.username, - password: request.password!, - clientMetadata: metaData, - validationData: validationData, - attributes: attributes, - asfDeviceId: asfDeviceId, - environment: userPoolEnvironment) + let input = await SignUpInput( + username: request.username, + password: request.password!, + clientMetadata: metaData, + validationData: validationData, + attributes: attributes, + asfDeviceId: asfDeviceId, + environment: userPoolEnvironment + ) let response = try await client.signUp(input: input) log.verbose("Received result") diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift index fcf3601c13..c74bd48dc8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift @@ -6,9 +6,9 @@ // #if os(iOS) || os(macOS) || os(visionOS) -import Foundation import Amplify import AWSPluginsCore +import Foundation class AWSAuthWebUISignInTask: AuthWebUISignInTask, DefaultLogger { @@ -18,16 +18,19 @@ class AWSAuthWebUISignInTask: AuthWebUISignInTask, DefaultLogger { private let taskHelper: AWSAuthTaskHelper let eventName: HubPayloadEventName - init(_ request: AuthWebUISignInRequest, - authConfiguration: AuthConfiguration, - authStateMachine: AuthStateMachine, - eventName: String + init( + _ request: AuthWebUISignInRequest, + authConfiguration: AuthConfiguration, + authStateMachine: AuthStateMachine, + eventName: String ) { self.request = request self.authStateMachine = authStateMachine - self.helper = HostedUISignInHelper(request: request, - authstateMachine: authStateMachine, - configuration: authConfiguration) + self.helper = HostedUISignInHelper( + request: request, + authstateMachine: authStateMachine, + configuration: authConfiguration + ) self.eventName = eventName self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthFetchDevicesTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthFetchDevicesTask.swift index 5ba804b989..a041023091 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthFetchDevicesTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthFetchDevicesTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthFetchDevicesTask: AuthFetchDevicesTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -40,7 +40,7 @@ class AWSAuthFetchDevicesTask: AuthFetchDevicesTask, DefaultLogger { throw error.authError } catch let error as AuthError { throw error - } catch let error { + } catch { throw AuthError.unknown("Unable to execute auth task", error) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthForgetDeviceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthForgetDeviceTask.swift index 239b4f9eac..62a08cd75f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthForgetDeviceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthForgetDeviceTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthForgetDeviceTask: AuthForgetDeviceTask, DefaultLogger { @@ -22,9 +22,11 @@ class AWSAuthForgetDeviceTask: AuthForgetDeviceTask, DefaultLogger { HubPayload.EventName.Auth.forgetDeviceAPI } - init(_ request: AuthForgetDeviceRequest, - authStateMachine: AuthStateMachine, - environment: AuthEnvironment) { + init( + _ request: AuthForgetDeviceRequest, + authStateMachine: AuthStateMachine, + environment: AuthEnvironment + ) { self.request = request self.authStateMachine = authStateMachine @@ -42,7 +44,7 @@ class AWSAuthForgetDeviceTask: AuthForgetDeviceTask, DefaultLogger { throw error.authError } catch let error as AuthError { throw error - } catch let error { + } catch { throw AuthError.unknown("Unable to execute auth task", error) } } @@ -61,7 +63,8 @@ class AWSAuthForgetDeviceTask: AuthForgetDeviceTask, DefaultLogger { guard let device = request.device else { let deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) + with: environment + ) if case .metadata(let data) = deviceMetadata { let input = ForgetDeviceInput(accessToken: accessToken, deviceKey: data.deviceKey) _ = try await userPoolService.forgetDevice(input: input) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthRememberDeviceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthRememberDeviceTask.swift index 71eb26f3f7..15794bec58 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthRememberDeviceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthRememberDeviceTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthRememberDeviceTask: AuthRememberDeviceTask, DefaultLogger { @@ -22,9 +22,11 @@ class AWSAuthRememberDeviceTask: AuthRememberDeviceTask, DefaultLogger { HubPayload.EventName.Auth.rememberDeviceAPI } - init(_ request: AuthRememberDeviceRequest, - authStateMachine: AuthStateMachine, - environment: AuthEnvironment) { + init( + _ request: AuthRememberDeviceRequest, + authStateMachine: AuthStateMachine, + environment: AuthEnvironment + ) { self.request = request self.authStateMachine = authStateMachine self.environment = environment @@ -41,7 +43,7 @@ class AWSAuthRememberDeviceTask: AuthRememberDeviceTask, DefaultLogger { throw error.authError } catch let error as AuthError { throw error - } catch let error { + } catch { throw AuthError.unknown("Unable to execute auth task", error) } } @@ -59,11 +61,14 @@ class AWSAuthRememberDeviceTask: AuthRememberDeviceTask, DefaultLogger { let userPoolService = try environment.cognitoUserPoolFactory() let deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) + with: environment + ) if case .metadata(let data) = deviceMetadata { - let input = UpdateDeviceStatusInput(accessToken: accessToken, - deviceKey: data.deviceKey, - deviceRememberedStatus: .remembered) + let input = UpdateDeviceStatusInput( + accessToken: accessToken, + deviceKey: data.deviceKey, + deviceRememberedStatus: .remembered + ) _ = try await userPoolService.updateDeviceStatus(input: input) } else { throw AuthError.unknown("Unable to get device metadata") diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift index acb63eacec..1ed501d21b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation protocol AuthFetchMFAPreferenceTask: AmplifyAuthTask where Request == Never, Success == UserMFAPreference, @@ -32,8 +32,10 @@ class FetchMFAPreferenceTask: AuthFetchMFAPreferenceTask, DefaultLogger { HubPayload.EventName.Auth.fetchMFAPreferenceAPI } - init(authStateMachine: AuthStateMachine, - userPoolFactory: @escaping CognitoUserPoolFactory) { + init( + authStateMachine: AuthStateMachine, + userPoolFactory: @escaping CognitoUserPoolFactory + ) { self.authStateMachine = authStateMachine self.userPoolFactory = userPoolFactory self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Helpers/AWSAuthTaskHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Helpers/AWSAuthTaskHelper.swift index 44267909b1..2d58205262 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Helpers/AWSAuthTaskHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Helpers/AWSAuthTaskHelper.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import Foundation class AWSAuthTaskHelper: DefaultLogger { @@ -48,7 +48,8 @@ class AWSAuthTaskHelper: DefaultLogger { return AWSCognitoSignOutResult.partial( revokeTokenError: data.revokeTokenError, globalSignOutError: data.globalSignOutError, - hostedUIError: data.hostedUIError) + hostedUIError: data.hostedUIError + ) } return AWSCognitoSignOutResult.complete case .signingIn: @@ -89,7 +90,8 @@ class AWSAuthTaskHelper: DefaultLogger { guard case .configured(let authenticationState, _) = authState else { throw AuthError.configuration( "Plugin not configured", - AuthPluginErrorConstants.configurationError) + AuthPluginErrorConstants.configurationError + ) } switch authenticationState { @@ -101,7 +103,8 @@ class AWSAuthTaskHelper: DefaultLogger { case .signedOut, .configured: throw AuthError.signedOut( "There is no user signed in to retrieve current user", - "Call Auth.signIn to sign in a user and then call Auth.getCurrentUser", nil) + "Call Auth.signIn to sign in a user and then call Auth.getCurrentUser", nil + ) case .error(let authNError): throw authNError.authError default: diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTask.swift index de7fec46ff..e08fbdf630 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTask.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation protocol AmplifyAuthTask { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTaskNonThrowing.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTaskNonThrowing.swift index 9377e8707c..0c75a61bf5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTaskNonThrowing.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTaskNonThrowing.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AmplifyAuthTaskNonThrowing { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthChangePasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthChangePasswordTask.swift index c0067e6521..ca67519d4c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthChangePasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthChangePasswordTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthChangePasswordTask: AmplifyAuthTask where Request == AuthChangePasswordRequest, Success == Void, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmResetPasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmResetPasswordTask.swift index 4ae4b60d3e..d2c3541027 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmResetPasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmResetPasswordTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthConfirmResetPasswordTask: AmplifyAuthTask where Request == AuthConfirmResetPasswordRequest, Success == Void, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignInTask.swift index 3f61b154d8..ea5df579f0 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignInTask.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation protocol AuthConfirmSignInTask: AmplifyAuthTask where Request == AuthConfirmSignInRequest, Success == AuthSignInResult, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignUpTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignUpTask.swift index 65014f85f2..8466dd55d1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignUpTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignUpTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthConfirmSignUpTask: AmplifyAuthTask where Request == AuthConfirmSignUpRequest, Success == AuthSignUpResult, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthDeleteUserTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthDeleteUserTask.swift index 942873e618..c74e84f621 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthDeleteUserTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthDeleteUserTask.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation protocol AuthDeleteUserTask: AmplifyAuthTask where Request == Never, Success == Void, Failure == AuthError { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthFetchSessionTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthFetchSessionTask.swift index 670da24571..46efd03a36 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthFetchSessionTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthFetchSessionTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthFetchSessionTask: AmplifyAuthTask where Request == AuthFetchSessionRequest, Success == AuthSession, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResendSignUpCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResendSignUpCodeTask.swift index c6cd79a0a1..ffeeb80265 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResendSignUpCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResendSignUpCodeTask.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify protocol AuthResendSignUpCodeTask: AmplifyAuthTask where Request == AuthResendSignUpCodeRequest, Success == AuthCodeDeliveryDetails, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResetPasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResetPasswordTask.swift index abb6c54632..f9302bbacf 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResetPasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResetPasswordTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthResetPasswordTask: AmplifyAuthTask where Request == AuthResetPasswordRequest, Success == AuthResetPasswordResult, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSetUpTOTPTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSetUpTOTPTask.swift index 9a71406bbe..06c4f95282 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSetUpTOTPTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSetUpTOTPTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthSetUpTOTPTask: AmplifyAuthTask where Request == Never, Success == TOTPSetupDetails, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignInTask.swift index 509bae225f..c26824239c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignInTask.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation protocol AuthSignInTask: AmplifyAuthTask where Request == AuthSignInRequest, Success == AuthSignInResult, Failure == AuthError { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignOutTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignOutTask.swift index bcdd99ec77..c9a8136163 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignOutTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignOutTask.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation protocol AuthSignOutTask: AmplifyAuthTaskNonThrowing where Request == AuthSignOutRequest, Success == AuthSignOutResult { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignUpTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignUpTask.swift index 6ba40aeb49..12fd6e473f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignUpTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignUpTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthSignUpTask: AmplifyAuthTask where Request == AuthSignUpRequest, Success == AuthSignUpResult, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSocialWebUISignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSocialWebUISignInTask.swift index ac7b9d0284..a1c54b16aa 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSocialWebUISignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSocialWebUISignInTask.swift @@ -6,8 +6,8 @@ // #if os(iOS) || os(macOS) || os(visionOS) -import Foundation import Amplify +import Foundation protocol AuthSocialWebUISignInTask: AmplifyAuthTask where Request == AuthWebUISignInRequest, Success == AuthSignInResult, Failure == AuthError { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthVerifyTOTPSetupTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthVerifyTOTPSetupTask.swift index f0b54d5bcb..00505d7da7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthVerifyTOTPSetupTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthVerifyTOTPSetupTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthVerifyTOTPSetupTask: AmplifyAuthTask where Request == VerifyTOTPSetupRequest, Success == Void, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthWebUISignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthWebUISignInTask.swift index e154025a64..63c320dbd1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthWebUISignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthWebUISignInTask.swift @@ -6,8 +6,8 @@ // #if os(iOS) || os(macOS) || os(visionOS) -import Foundation import Amplify +import Foundation protocol AuthWebUISignInTask: AmplifyAuthTask where Request == AuthWebUISignInRequest, Success == AuthSignInResult, Failure == AuthError { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthFetchDevicesTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthFetchDevicesTask.swift index 19efd6e384..9801f0283b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthFetchDevicesTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthFetchDevicesTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthFetchDevicesTask: AmplifyAuthTask where Request == AuthFetchDevicesRequest, Success == [AuthDevice], Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthForgetDeviceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthForgetDeviceTask.swift index af27c94c79..27c537a977 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthForgetDeviceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthForgetDeviceTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthForgetDeviceTask: AmplifyAuthTask where Request == AuthForgetDeviceRequest, Success == Void, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthRememberDeviceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthRememberDeviceTask.swift index f4365c8797..6091dda8e4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthRememberDeviceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthRememberDeviceTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthRememberDeviceTask: AmplifyAuthTask where Request == AuthRememberDeviceRequest, Success == Void, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthConfirmUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthConfirmUserAttributeTask.swift index 22bd3525c0..561f84b127 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthConfirmUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthConfirmUserAttributeTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthConfirmUserAttributeTask: AmplifyAuthTask where Request == AuthConfirmUserAttributeRequest, Success == Void, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthFetchUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthFetchUserAttributeTask.swift index 49dd81815b..6bff56f037 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthFetchUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthFetchUserAttributeTask.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify protocol AuthFetchUserAttributeTask: AmplifyAuthTask where Request == AuthFetchUserAttributesRequest, Success == [AuthUserAttribute], Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributeTask.swift index eaadcd9e78..f444ef5dd8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributeTask.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify // swiftlint:disable:next line_length diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributesTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributesTask.swift index b16def3182..3678a251f7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributesTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributesTask.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify // swiftlint:disable:next line_length diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/SetUpTOTPTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/SetUpTOTPTask.swift index 6a7ab2b6ea..23f9ac8973 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/SetUpTOTPTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/SetUpTOTPTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class SetUpTOTPTask: AuthSetUpTOTPTask, DefaultLogger { @@ -23,8 +23,10 @@ class SetUpTOTPTask: AuthSetUpTOTPTask, DefaultLogger { HubPayload.EventName.Auth.setUpTOTPAPI } - init(authStateMachine: AuthStateMachine, - userPoolFactory: @escaping CognitoUserPoolFactory) { + init( + authStateMachine: AuthStateMachine, + userPoolFactory: @escaping CognitoUserPoolFactory + ) { self.authStateMachine = authStateMachine self.userPoolFactory = userPoolFactory self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine) @@ -62,10 +64,13 @@ class SetUpTOTPTask: AuthSetUpTOTPTask, DefaultLogger { throw AuthError.invalidState( "Auth State not in a valid state for the user", AuthPluginErrorConstants.invalidStateError, - nil) + nil + ) } - return .init(sharedSecret: secretCode, - username: authUser.username) + return .init( + sharedSecret: secretCode, + username: authUser.username + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UpdateMFAPreferenceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UpdateMFAPreferenceTask.swift index b9bedf4fe8..cbc42e7ba1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UpdateMFAPreferenceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UpdateMFAPreferenceTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation protocol AuthUpdateMFAPreferenceTask: AmplifyAuthTask where Request == Never, Success == Void, @@ -34,10 +34,12 @@ class UpdateMFAPreferenceTask: AuthUpdateMFAPreferenceTask, DefaultLogger { HubPayload.EventName.Auth.updateMFAPreferenceAPI } - init(smsPreference: MFAPreference?, - totpPreference: MFAPreference?, - authStateMachine: AuthStateMachine, - userPoolFactory: @escaping CognitoUserPoolFactory) { + init( + smsPreference: MFAPreference?, + totpPreference: MFAPreference?, + authStateMachine: AuthStateMachine, + userPoolFactory: @escaping CognitoUserPoolFactory + ) { self.smsPreference = smsPreference self.totpPreference = totpPreference self.authStateMachine = authStateMachine @@ -64,7 +66,8 @@ class UpdateMFAPreferenceTask: AuthUpdateMFAPreferenceTask, DefaultLogger { let input = SetUserMFAPreferenceInput( accessToken: accessToken, smsMfaSettings: smsPreference?.smsSetting(isCurrentlyPreferred: preferredMFAType == .sms), - softwareTokenMfaSettings: totpPreference?.softwareTokenSetting(isCurrentlyPreferred: preferredMFAType == .totp)) + softwareTokenMfaSettings: totpPreference?.softwareTokenSetting(isCurrentlyPreferred: preferredMFAType == .totp) + ) _ = try await userPoolService.setUserMFAPreference(input: input) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift index 763af3e80c..cfe2a2dac7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import Foundation class AWSAuthAttributeResendConfirmationCodeTask: AuthAttributeResendConfirmationCodeTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -53,7 +53,8 @@ class AWSAuthAttributeResendConfirmationCodeTask: AuthAttributeResendConfirmatio let input = GetUserAttributeVerificationCodeInput( accessToken: accessToken, attributeName: request.attributeKey.rawValue, - clientMetadata: clientMetaData) + clientMetadata: clientMetaData + ) let result = try await userPoolService.getUserAttributeVerificationCode(input: input) guard let deliveryDetails = result.codeDeliveryDetails?.toAuthCodeDeliveryDetails() else { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthConfirmUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthConfirmUserAttributeTask.swift index b9b6574201..b7f0e147dc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthConfirmUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthConfirmUserAttributeTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthConfirmUserAttributeTask: AuthConfirmUserAttributeTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -48,7 +48,8 @@ class AWSAuthConfirmUserAttributeTask: AuthConfirmUserAttributeTask, DefaultLogg let input = VerifyUserAttributeInput( accessToken: accessToken, attributeName: request.attributeKey.rawValue, - code: request.confirmationCode) + code: request.confirmationCode + ) _ = try await userPoolService.verifyUserAttribute(input: input) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthFetchUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthFetchUserAttributeTask.swift index c9e7a07727..5d5b3e70de 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthFetchUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthFetchUserAttributeTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthFetchUserAttributeTask: AuthFetchUserAttributeTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -54,11 +54,14 @@ class AWSAuthFetchUserAttributeTask: AuthFetchUserAttributeTask, DefaultLogger { let mappedAttributes: [AuthUserAttribute] = attributes.compactMap { oldAttribute in guard let attributeName = oldAttribute.name, - let attributeValue = oldAttribute.value else { + let attributeValue = oldAttribute.value + else { return nil } - return AuthUserAttribute(AuthUserAttributeKey(rawValue: attributeName), - value: attributeValue) + return AuthUserAttribute( + AuthUserAttributeKey(rawValue: attributeName), + value: attributeValue + ) } return mappedAttributes } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthSendUserAttributeVerificationCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthSendUserAttributeVerificationCodeTask.swift index 0d8d09f435..007887c6d3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthSendUserAttributeVerificationCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthSendUserAttributeVerificationCodeTask.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import Foundation class AWSAuthSendUserAttributeVerificationCodeTask: AuthSendUserAttributeVerificationCodeTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -22,9 +22,11 @@ class AWSAuthSendUserAttributeVerificationCodeTask: AuthSendUserAttributeVerific HubPayload.EventName.Auth.sendUserAttributeVerificationCodeAPI } - init(_ request: AuthSendUserAttributeVerificationCodeRequest, - authStateMachine: AuthStateMachine, - userPoolFactory: @escaping CognitoUserPoolFactory) { + init( + _ request: AuthSendUserAttributeVerificationCodeRequest, + authStateMachine: AuthStateMachine, + userPoolFactory: @escaping CognitoUserPoolFactory + ) { self.request = request self.authStateMachine = authStateMachine self.userPoolFactory = userPoolFactory @@ -55,7 +57,8 @@ class AWSAuthSendUserAttributeVerificationCodeTask: AuthSendUserAttributeVerific let input = GetUserAttributeVerificationCodeInput( accessToken: accessToken, attributeName: request.attributeKey.rawValue, - clientMetadata: clientMetaData) + clientMetadata: clientMetaData + ) let result = try await userPoolService.getUserAttributeVerificationCode(input: input) guard let deliveryDetails = result.codeDeliveryDetails?.toAuthCodeDeliveryDetails() else { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributeTask.swift index b6f318ddfd..eb4fbf7a23 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributeTask.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import Foundation class AWSAuthUpdateUserAttributeTask: AuthUpdateUserAttributeTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -48,7 +48,8 @@ class AWSAuthUpdateUserAttributeTask: AuthUpdateUserAttributeTask, DefaultLogger attributes: [request.userAttribute], accessToken: accessToken, userPoolFactory: userPoolFactory, - clientMetaData: clientMetaData) + clientMetaData: clientMetaData + ) guard let attributeResult = finalResult[request.userAttribute.key] else { let authError = AuthError.unknown("Attribute to be updated does not exist in the result", nil) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributesTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributesTask.swift index 187791614a..481567447b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributesTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributesTask.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import Foundation class AWSAuthUpdateUserAttributesTask: AuthUpdateUserAttributesTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -47,7 +47,8 @@ class AWSAuthUpdateUserAttributesTask: AuthUpdateUserAttributesTask, DefaultLogg attributes: request.userAttributes, accessToken: accessToken, userPoolFactory: userPoolFactory, - clientMetaData: clientMetaData) + clientMetaData: clientMetaData + ) return finalResult } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift index f5cf58d112..395a496ced 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class VerifyTOTPSetupTask: AuthVerifyTOTPSetupTask, DefaultLogger { @@ -24,9 +24,11 @@ class VerifyTOTPSetupTask: AuthVerifyTOTPSetupTask, DefaultLogger { HubPayload.EventName.Auth.verifyTOTPSetupAPI } - init(_ request: VerifyTOTPSetupRequest, - authStateMachine: AuthStateMachine, - userPoolFactory: @escaping CognitoUserPoolFactory) { + init( + _ request: VerifyTOTPSetupRequest, + authStateMachine: AuthStateMachine, + userPoolFactory: @escaping CognitoUserPoolFactory + ) { self.request = request self.authStateMachine = authStateMachine self.userPoolFactory = userPoolFactory @@ -38,7 +40,8 @@ class VerifyTOTPSetupTask: AuthVerifyTOTPSetupTask, DefaultLogger { await taskHelper.didStateMachineConfigured() let accessToken = try await taskHelper.getAccessToken() try await verifyTOTPSetup( - with: accessToken, userCode: request.code) + with: accessToken, userCode: request.code + ) } catch let error as AuthErrorConvertible { throw error.authError } catch { @@ -52,7 +55,8 @@ class VerifyTOTPSetupTask: AuthVerifyTOTPSetupTask, DefaultLogger { let input = VerifySoftwareTokenInput( accessToken: accessToken, friendlyDeviceName: friendlyDeviceName, - userCode: userCode) + userCode: userCode + ) let result = try await userPoolService.verifySoftwareToken(input: input) guard let output = result.status else { @@ -61,14 +65,17 @@ class VerifyTOTPSetupTask: AuthVerifyTOTPSetupTask, DefaultLogger { switch output { case .error: - throw AuthError.service("Unknown service error occurred", - AmplifyErrorMessages.reportBugToAWS()) + throw AuthError.service( + "Unknown service error occurred", + AmplifyErrorMessages.reportBugToAWS() + ) case .success: return case .sdkUnknown(let error): throw AuthError.service( error, - AmplifyErrorMessages.reportBugToAWS()) + AmplifyErrorMessages.reportBugToAWS() + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Bytes.swift b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Bytes.swift index f28509ce8e..c9c14d017f 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Bytes.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Bytes.swift @@ -15,7 +15,7 @@ public extension AmplifyBigInt { } var byteArray: [UInt8] { - let bytesCount = self.bytesCount + let bytesCount = bytesCount var buffer = [UInt8](repeating: 0, count: bytesCount) var written = size_t() let error = amplify_mp_to_sbin(&value, &buffer, bytesCount, &written) diff --git a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Comparable.swift b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Comparable.swift index d53b1884b4..1a0dca0fb0 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Comparable.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Comparable.swift @@ -11,23 +11,23 @@ import libtommathAmplify extension AmplifyBigInt: Equatable, Comparable { public static func == (lhs: AmplifyBigInt, rhs: AmplifyBigInt) -> Bool { - return (lhs.compare(rhs) == .orderedSame) + return lhs.compare(rhs) == .orderedSame } public static func <= (lhs: AmplifyBigInt, rhs: AmplifyBigInt) -> Bool { - return (lhs.compare(rhs) != .orderedAscending) + return lhs.compare(rhs) != .orderedAscending } public static func >= (lhs: AmplifyBigInt, rhs: AmplifyBigInt) -> Bool { - return (lhs.compare(rhs) != .orderedDescending) + return lhs.compare(rhs) != .orderedDescending } public static func > (lhs: AmplifyBigInt, rhs: AmplifyBigInt) -> Bool { - return (lhs.compare(rhs) == .orderedAscending) + return lhs.compare(rhs) == .orderedAscending } public static func < (lhs: AmplifyBigInt, rhs: AmplifyBigInt) -> Bool { - return (lhs.compare(rhs) == .orderedDescending) + return lhs.compare(rhs) == .orderedDescending } func compare(_ againstValue: AmplifyBigInt) -> ComparisonResult { diff --git a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Operations.swift b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Operations.swift index 5995ac75c8..dbdaa63dba 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Operations.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Operations.swift @@ -118,8 +118,10 @@ public extension AmplifyBigInt { // MARK: - Exponentional - func pow(_ power: AmplifyBigInt, - modulus: AmplifyBigInt) -> AmplifyBigInt { + func pow( + _ power: AmplifyBigInt, + modulus: AmplifyBigInt + ) -> AmplifyBigInt { let exponentialModulus = AmplifyBigInt() let result = amplify_mp_exptmod(&value, &power.value, &modulus.value, &exponentialModulus.value) guard result == AMPLIFY_MP_OKAY else { diff --git a/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift b/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift index 26aebf4545..905c2fb8d3 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift @@ -5,23 +5,27 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CommonCrypto import CryptoKit +import Foundation // swiftlint:disable identifier_name // https://tools.ietf.org/html/rfc5869 public enum HMACKeyDerivationFunction { - public static func generateDerivedKey(keyingMaterial: Data, - salt: Data, - info: String?, - outputLength: Int) -> Data { + public static func generateDerivedKey( + keyingMaterial: Data, + salt: Data, + info: String?, + outputLength: Int + ) -> Data { if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) { - return generateHKDF(keyingMaterial: keyingMaterial, - salt: salt, - info: info, - outputLength: outputLength) + return generateHKDF( + keyingMaterial: keyingMaterial, + salt: salt, + info: info, + outputLength: outputLength + ) } else { let pseudoRandomKey = extractPseudoRandomKey(salt: salt, inputKeyMaterial: keyingMaterial) return expand(pseudoRandomKey: pseudoRandomKey, info: info.map { Data($0.utf8) }, outputLength: outputLength) @@ -38,13 +42,18 @@ public enum HMACKeyDerivationFunction { let key = SymmetricKey(data: keyingMaterial) var hkdf: SymmetricKey if let info { - hkdf = HKDF.deriveKey(inputKeyMaterial: key, - salt: salt, info: Data(info.utf8), - outputByteCount: outputLength) + hkdf = HKDF.deriveKey( + inputKeyMaterial: key, + salt: salt, + info: Data(info.utf8), + outputByteCount: outputLength + ) } else { - hkdf = HKDF.deriveKey(inputKeyMaterial: key, - salt: salt, - outputByteCount: outputLength) + hkdf = HKDF.deriveKey( + inputKeyMaterial: key, + salt: salt, + outputByteCount: outputLength + ) } return hkdf.withUnsafeBytes { buffPointer in return Data(Array(buffPointer)) @@ -63,10 +72,12 @@ public enum HMACKeyDerivationFunction { var outputKeyMaterial = Data() var previousT = Data() for index in 1 ... n { - let t = calculateT(pseudoRandomKey: pseudoRandomKey, - previousT: previousT, - info: info, - i: UInt8(index)) + let t = calculateT( + pseudoRandomKey: pseudoRandomKey, + previousT: previousT, + info: info, + i: UInt8(index) + ) outputKeyMaterial.append(t) previousT = t } diff --git a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPClientState.swift b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPClientState.swift index 2bc92a7583..33a3ed5d10 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPClientState.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPClientState.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import CryptoKit import AmplifyBigInteger +import CryptoKit +import Foundation public typealias BigInt = AmplifyBigInt @@ -19,9 +19,11 @@ public struct SRPClientState { public init(commonState: SRPCommonState) { self.privateA = SRPClientState.calculatePrivateA(prime: commonState.prime) - self.publicA = SRPClientState.calculatePublicA(privateA: privateA, - generator: commonState.generator, - prime: commonState.prime) + self.publicA = SRPClientState.calculatePublicA( + privateA: privateA, + generator: commonState.generator, + prime: commonState.prime + ) } private static func calculatePrivateA(prime N: BigInt) -> BigInt { @@ -29,13 +31,15 @@ public struct SRPClientState { var randomInt: BigInt repeat { randomInt = generateRandomUnsigned(of: byteSize) - } while (randomInt >= N) + } while randomInt >= N return randomInt } - private static func calculatePublicA(privateA: BigInt, - generator: BigInt, - prime: BigInt) -> BigInt { + private static func calculatePublicA( + privateA: BigInt, + generator: BigInt, + prime: BigInt + ) -> BigInt { return generator.pow(privateA, modulus: prime) } @@ -56,13 +60,15 @@ public struct SRPClientState { return BigInt(unsignedData: hashBytes) } - public static func calculateSessionKey(username: String, - password: String, - publicClientKey: BigInt, - privateClientKey: BigInt, - publicServerKey: BigInt, - salt: BigInt, - commonState: SRPCommonState) -> BigInt { + public static func calculateSessionKey( + username: String, + password: String, + publicClientKey: BigInt, + privateClientKey: BigInt, + publicServerKey: BigInt, + salt: BigInt, + commonState: SRPCommonState + ) -> BigInt { // Calculations are detailed in RFC - https://datatracker.ietf.org/doc/html/rfc2945 // Calculate x = SHA( | SHA( | ":" | )) @@ -88,7 +94,8 @@ public struct SRPClientState { deviceGroupKey: String, deviceKey: String, password: String, - commonState: SRPCommonState) -> (salt: BigInt, passwordVerifier: BigInt) { + commonState: SRPCommonState + ) -> (salt: BigInt, passwordVerifier: BigInt) { // Salt (16 random bytes) let salt = generateRandomUnsigned(of: 16) diff --git a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPCommonState.swift b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPCommonState.swift index 524e96106a..1430cab4f6 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPCommonState.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPCommonState.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import CryptoKit import AmplifyBigInteger +import CryptoKit +import Foundation // swiftlint:disable identifier_name public struct SRPCommonState { diff --git a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPServerResponse.swift b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPServerResponse.swift index 15ec075974..e99530be9e 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPServerResponse.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPServerResponse.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AmplifyBigInteger +import Foundation struct SRPServerResponse { let publicKey: BigInt diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/ClearCredentialsTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/ClearCredentialsTests.swift index 8f3f2a6899..9720713aa6 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/ClearCredentialsTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/ClearCredentialsTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import AWSPluginsCore import Amplify +import AWSPluginsCore +import XCTest @testable import AWSCognitoAuthPlugin class ClearCredentialsTests: XCTestCase { @@ -35,20 +35,27 @@ class ClearCredentialsTests: XCTestCase { let amplifyCredentialStoreFactory: BasicCredentialStoreEnvironment.AmplifyAuthCredentialStoreFactory = { return mockAmplifyCredentialStoreBehavior } - let authConfig = AuthConfiguration.userPoolsAndIdentityPools(Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + let authConfig = AuthConfiguration.userPoolsAndIdentityPools( + Defaults.makeDefaultUserPoolConfigData(), + Defaults.makeIdentityConfigData() + ) - let credentialStoreEnv = BasicCredentialStoreEnvironment(amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + let credentialStoreEnv = BasicCredentialStoreEnvironment( + amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = ClearCredentialStore(dataStoreType: .amplifyCredentials) - await action.execute(withDispatcher: MockDispatcher { _ in }, - environment: environment) + await action.execute( + withDispatcher: MockDispatcher { _ in }, + environment: environment + ) await fulfillment( of: [expectation], @@ -116,16 +123,21 @@ class ClearCredentialsTests: XCTestCase { let amplifyCredentialStoreFactory: BasicCredentialStoreEnvironment.AmplifyAuthCredentialStoreFactory = { return mockAmplifyCredentialStoreBehavior } - let authConfig = AuthConfiguration.userPoolsAndIdentityPools(Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + let authConfig = AuthConfiguration.userPoolsAndIdentityPools( + Defaults.makeDefaultUserPoolConfigData(), + Defaults.makeIdentityConfigData() + ) - let credentialStoreEnv = BasicCredentialStoreEnvironment(amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + let credentialStoreEnv = BasicCredentialStoreEnvironment( + amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = ClearCredentialStore(dataStoreType: .amplifyCredentials) await action.execute(withDispatcher: MockDispatcher { event in @@ -174,16 +186,21 @@ class ClearCredentialsTests: XCTestCase { let amplifyCredentialStoreFactory: BasicCredentialStoreEnvironment.AmplifyAuthCredentialStoreFactory = { return mockAmplifyCredentialStoreBehavior } - let authConfig = AuthConfiguration.userPoolsAndIdentityPools(Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + let authConfig = AuthConfiguration.userPoolsAndIdentityPools( + Defaults.makeDefaultUserPoolConfigData(), + Defaults.makeIdentityConfigData() + ) - let credentialStoreEnv = BasicCredentialStoreEnvironment(amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + let credentialStoreEnv = BasicCredentialStoreEnvironment( + amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = ClearCredentialStore(dataStoreType: .amplifyCredentials) await action.execute(withDispatcher: MockDispatcher { event in diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/LoadCredentialsTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/LoadCredentialsTests.swift index 2375daf8a6..9c783bdd41 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/LoadCredentialsTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/LoadCredentialsTests.swift @@ -7,9 +7,9 @@ import XCTest -@testable import AWSCognitoAuthPlugin -import AWSPluginsCore import Amplify +import AWSPluginsCore +@testable import AWSCognitoAuthPlugin class LoadCredentialsTests: XCTestCase { @@ -37,16 +37,21 @@ class LoadCredentialsTests: XCTestCase { let amplifyCredentialStoreFactory: BasicCredentialStoreEnvironment.AmplifyAuthCredentialStoreFactory = { return mockAmplifyCredentialStoreBehavior } - let authConfig = AuthConfiguration.userPoolsAndIdentityPools(Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + let authConfig = AuthConfiguration.userPoolsAndIdentityPools( + Defaults.makeDefaultUserPoolConfigData(), + Defaults.makeIdentityConfigData() + ) - let credentialStoreEnv = BasicCredentialStoreEnvironment(amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + let credentialStoreEnv = BasicCredentialStoreEnvironment( + amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = LoadCredentialStore(credentialStoreType: .amplifyCredentials) await action.execute(withDispatcher: MockDispatcher { event in @@ -133,16 +138,21 @@ class LoadCredentialsTests: XCTestCase { let amplifyCredentialStoreFactory: BasicCredentialStoreEnvironment.AmplifyAuthCredentialStoreFactory = { return mockAmplifyCredentialStoreBehavior } - let authConfig = AuthConfiguration.userPoolsAndIdentityPools(Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + let authConfig = AuthConfiguration.userPoolsAndIdentityPools( + Defaults.makeDefaultUserPoolConfigData(), + Defaults.makeIdentityConfigData() + ) - let credentialStoreEnv = BasicCredentialStoreEnvironment(amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + let credentialStoreEnv = BasicCredentialStoreEnvironment( + amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = LoadCredentialStore(credentialStoreType: .amplifyCredentials) await action.execute(withDispatcher: MockDispatcher { event in @@ -193,16 +203,19 @@ class LoadCredentialsTests: XCTestCase { } let authConfig = AuthConfiguration.userPoolsAndIdentityPools( Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + Defaults.makeIdentityConfigData() + ) let credentialStoreEnv = BasicCredentialStoreEnvironment( amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = LoadCredentialStore(credentialStoreType: .amplifyCredentials) await action.execute(withDispatcher: MockDispatcher { event in diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MigrateLegacyCredentialStoreTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MigrateLegacyCredentialStoreTests.swift index 1252888632..20538cf4a9 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MigrateLegacyCredentialStoreTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MigrateLegacyCredentialStoreTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest @testable import AWSCognitoAuthPlugin class MigrateLegacyCredentialStoreTests: XCTestCase { @@ -31,9 +31,10 @@ class MigrateLegacyCredentialStoreTests: XCTestCase { saveCredentialHandler: { codableCredentials in guard let credentials = codableCredentials as? AmplifyCredentials, case .userPoolAndIdentityPool( - signedInData: let signedInData, - identityID: let identityID, - credentials: let awsCredentials) = credentials else { + signedInData: let signedInData, + identityID: let identityID, + credentials: let awsCredentials + ) = credentials else { XCTFail("The credentials saved should be of type AmplifyCredentials") return } @@ -58,16 +59,19 @@ class MigrateLegacyCredentialStoreTests: XCTestCase { } let authConfig = AuthConfiguration.userPoolsAndIdentityPools( Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + Defaults.makeIdentityConfigData() + ) let credentialStoreEnv = BasicCredentialStoreEnvironment( amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = MigrateLegacyCredentialStore() await action.execute(withDispatcher: MockDispatcher { _ in }, environment: environment) @@ -105,23 +109,26 @@ class MigrateLegacyCredentialStoreTests: XCTestCase { } let authConfig = AuthConfiguration.userPoolsAndIdentityPools( Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + Defaults.makeIdentityConfigData() + ) let credentialStoreEnv = BasicCredentialStoreEnvironment( amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = MigrateLegacyCredentialStore() await action.execute(withDispatcher: MockDispatcher { _ in }, environment: environment) await fulfillment( of: [migrationCompletionInvoked], - + timeout: 0.1 ) } @@ -147,10 +154,10 @@ class MigrateLegacyCredentialStoreTests: XCTestCase { ) await fulfillment(of: [expectation], timeout: 1) } - + /// - Given: A credential store with an environment that only has identity pool /// - When: The migration legacy store action is executed - /// - Then: + /// - Then: /// - A .loadCredentialStore event with type .amplifyCredentials is dispatched /// - An .identityPoolOnly credential is saved func testExecute_withoutUserPool_andWithoutLoginsTokens_shouldDispatchLoadEvent() async { @@ -184,13 +191,14 @@ class MigrateLegacyCredentialStoreTests: XCTestCase { }, legacyKeychainStoreFactory: { _ in MockKeychainStoreBehavior(data: "hostedUI") - }), + } + ), logger: MigrateLegacyCredentialStore.log ) ) await fulfillment(of: [expectation], timeout: 1) } - + /// - Given: A credential store with an environment that only has identity pool /// - When: The migration legacy store action is executed /// - A .loadCredentialStore event with type .amplifyCredentials is dispatched @@ -233,7 +241,8 @@ class MigrateLegacyCredentialStoreTests: XCTestCase { return MockKeychainStoreBehavior( data: String(decoding: data, as: UTF8.self) ) - }), + } + ), logger: action.log ) ) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockAmplifyCredentialStoreBehavior.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockAmplifyCredentialStoreBehavior.swift index 06e5fe9f25..9b11427816 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockAmplifyCredentialStoreBehavior.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockAmplifyCredentialStoreBehavior.swift @@ -7,8 +7,8 @@ import Foundation -@testable import AWSCognitoAuthPlugin import AWSPluginsCore +@testable import AWSCognitoAuthPlugin class MockAmplifyCredentialStoreBehavior: AmplifyAuthCredentialStoreBehavior { @@ -22,10 +22,12 @@ class MockAmplifyCredentialStoreBehavior: AmplifyAuthCredentialStoreBehavior { let getCredentialHandler: GetCredentialHandler? let clearCredentialHandler: ClearCredentialHandler? - init(migrationCompleteHandler: Migrationhandler? = nil, - saveCredentialHandler: SaveCredentialHandler? = nil, - getCredentialHandler: GetCredentialHandler? = nil, - clearCredentialHandler: ClearCredentialHandler? = nil) { + init( + migrationCompleteHandler: Migrationhandler? = nil, + saveCredentialHandler: SaveCredentialHandler? = nil, + getCredentialHandler: GetCredentialHandler? = nil, + clearCredentialHandler: ClearCredentialHandler? = nil + ) { self.migrationCompleteHandler = migrationCompleteHandler self.saveCredentialHandler = saveCredentialHandler self.getCredentialHandler = getCredentialHandler diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift index 97b9201818..a0ec266dfa 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift @@ -7,8 +7,8 @@ import Foundation -@testable import AWSCognitoAuthPlugin import AWSPluginsCore +@testable import AWSCognitoAuthPlugin class MockKeychainStoreBehavior: KeychainStoreBehavior { @@ -17,8 +17,10 @@ class MockKeychainStoreBehavior: KeychainStoreBehavior { let data: String let removeAllHandler: VoidHandler? - init(data: String, - removeAllHandler: VoidHandler? = nil) { + init( + data: String, + removeAllHandler: VoidHandler? = nil + ) { self.data = data self.removeAllHandler = removeAllHandler } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchAWSCredentials/FetchAuthAWSCredentialsTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchAWSCredentials/FetchAuthAWSCredentialsTests.swift index bb05912e17..b16f91ea2b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchAWSCredentials/FetchAuthAWSCredentialsTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchAWSCredentials/FetchAuthAWSCredentialsTests.swift @@ -7,8 +7,8 @@ import XCTest -import AWSCognitoIdentity import Amplify +import AWSCognitoIdentity @testable import AWSCognitoAuthPlugin @@ -47,7 +47,8 @@ class FetchAuthAWSCredentialsTests: XCTestCase { } let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: IdentityPoolConfigurationData.testData, - cognitoIdentityFactory: identityProviderFactory) + cognitoIdentityFactory: identityProviderFactory + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( authZEnvironment: authorizationEnvironment) @@ -80,7 +81,8 @@ class FetchAuthAWSCredentialsTests: XCTestCase { } let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: IdentityPoolConfigurationData.testData, - cognitoIdentityFactory: identityProviderFactory) + cognitoIdentityFactory: identityProviderFactory + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( authZEnvironment: authorizationEnvironment) @@ -122,13 +124,16 @@ class FetchAuthAWSCredentialsTests: XCTestCase { accessKeyId: expectedAccessKey, expiration: Date(), secretKey: expectedSecretKey, - sessionToken: expectedSessionToken), - identityId: expectedIdentityId) + sessionToken: expectedSessionToken + ), + identityId: expectedIdentityId + ) }) } let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: IdentityPoolConfigurationData.testData, - cognitoIdentityFactory: identityProviderFactory) + cognitoIdentityFactory: identityProviderFactory + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( authZEnvironment: authorizationEnvironment) @@ -162,7 +167,8 @@ class FetchAuthAWSCredentialsTests: XCTestCase { } let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: IdentityPoolConfigurationData.testData, - cognitoIdentityFactory: identityProviderFactory) + cognitoIdentityFactory: identityProviderFactory + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( authZEnvironment: authorizationEnvironment) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchUserPoolTokens/RefreshUserPoolTokensTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchUserPoolTokens/RefreshUserPoolTokensTests.swift index 1dbc164dff..668fe71bd0 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchUserPoolTokens/RefreshUserPoolTokensTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchUserPoolTokens/RefreshUserPoolTokensTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import XCTest @testable import AWSCognitoAuthPlugin @@ -20,7 +20,8 @@ class RefreshUserPoolTokensTests: XCTestCase { let action = RefreshUserPoolTokens(existingSignedIndata: .testData) - await action.execute(withDispatcher: MockDispatcher { event in + await action.execute( + withDispatcher: MockDispatcher { event in guard let event = event as? RefreshSessionEvent else { return @@ -31,7 +32,8 @@ class RefreshUserPoolTokensTests: XCTestCase { XCTAssertEqual(error, .noUserPool) expectation.fulfill() } - }, environment: MockInvalidEnvironment() + }, + environment: MockInvalidEnvironment() ) await fulfillment( @@ -53,7 +55,8 @@ class RefreshUserPoolTokensTests: XCTestCase { let action = RefreshUserPoolTokens(existingSignedIndata: .testData) - await action.execute(withDispatcher: MockDispatcher { event in + await action.execute( + withDispatcher: MockDispatcher { event in guard let event = event as? RefreshSessionEvent else { return } @@ -62,7 +65,8 @@ class RefreshUserPoolTokensTests: XCTestCase { XCTAssertEqual(error, .invalidTokens) expectation.fulfill() } - }, environment: Defaults.makeDefaultAuthEnvironment( + }, + environment: Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) ) @@ -83,20 +87,23 @@ class RefreshUserPoolTokensTests: XCTestCase { accessToken: "accessTokenNew", expiresIn: 100, idToken: "idTokenNew", - refreshToken: "refreshTokenNew")) + refreshToken: "refreshTokenNew" + )) } ) } let action = RefreshUserPoolTokens(existingSignedIndata: .testData) - await action.execute(withDispatcher: MockDispatcher { event in + await action.execute( + withDispatcher: MockDispatcher { event in if let userPoolEvent = event as? RefreshSessionEvent, case .refreshIdentityInfo = userPoolEvent.eventType { expectation.fulfill() } - }, environment: Defaults.makeDefaultAuthEnvironment( + }, + environment: Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) ) @@ -124,7 +131,8 @@ class RefreshUserPoolTokensTests: XCTestCase { userPoolConfiguration: UserPoolConfigurationData.testData, cognitoUserPoolFactory: identityProviderFactory, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let action = RefreshUserPoolTokens(existingSignedIndata: .testData) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/InitializeFetchAuthSessionTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/InitializeFetchAuthSessionTests.swift index 4976285b0e..6799a9032b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/InitializeFetchAuthSessionTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/InitializeFetchAuthSessionTests.swift @@ -17,7 +17,8 @@ class InitializeFetchAuthSessionTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment() - await action.execute(withDispatcher: MockDispatcher { event in + await action.execute( + withDispatcher: MockDispatcher { event in guard let event = event as? FetchAuthSessionEvent else { XCTFail("Expected event to be FetchAuthSessionEvent") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/InitiateAuthSRPTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/InitiateAuthSRPTests.swift index c3ef575d95..e536300655 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/InitiateAuthSRPTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/InitiateAuthSRPTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentityProvider +import XCTest @testable import AWSCognitoAuthPlugin diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyDevicePasswordSRPSignatureTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyDevicePasswordSRPSignatureTests.swift index d33a7f05c0..1ad44ac2b7 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyDevicePasswordSRPSignatureTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyDevicePasswordSRPSignatureTests.swift @@ -5,19 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider -@testable import AWSPluginsTestCommon import XCTest +@testable import AWSCognitoAuthPlugin +@testable import AWSPluginsTestCommon class VerifyDevicePasswordSRPSignatureTests: XCTestCase { private var srpClient: MockSRPClientBehavior! - + override func setUp() async throws { MockSRPClientBehavior.reset() srpClient = MockSRPClientBehavior() } - + override func tearDown() { MockSRPClientBehavior.reset() srpClient = nil @@ -34,7 +34,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { XCTFail("Should not throw error: \(error)") } } - + /// Given: A VerifyDevicePasswordSRP /// When: signature is invoked and the srpClient throws an SRPError error when generating a shared secret /// Then: a .calculation error is thrown @@ -52,7 +52,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { XCTAssertEqual(srpError, .numberConversion) } } - + /// Given: A VerifyDevicePasswordSRP /// When: signature is invoked and the srpClient throws a non-SRPError error when generating a shared secret /// Then: a .configuration error is thrown @@ -70,7 +70,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { XCTAssertEqual(message, "Could not calculate shared secret") } } - + /// Given: A VerifyDevicePasswordSRP /// When: signature is invoked and the srpClient throws a SRPError error when generating an authentication key /// Then: a .calculation error is thrown @@ -88,7 +88,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { XCTAssertEqual(srpError, .numberConversion) } } - + /// Given: A VerifyDevicePasswordSRP /// When: signature is invoked and the srpClient throws a non-SRPError error when generating an authentication key /// Then: a .configuration error is thrown @@ -106,7 +106,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { XCTAssertEqual(message, "Could not calculate signature") } } - + @discardableResult private func signature() throws -> String { let action = VerifyDevicePasswordSRP( @@ -128,7 +128,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { private class MockSRPClientBehavior: SRPClientBehavior { var kHexValue: String = "kHexValue" - + static func calculateUHexValue( clientPublicKeyHexValue: String, serverPublicKeyHexValue: String @@ -143,18 +143,18 @@ private class MockSRPClientBehavior: SRPClientBehavior { ) throws -> Data { return try authenticationKey.get() } - + static func reset() { authenticationKey = .success(Data("AuthenticationKey".utf8)) } - + func generateClientKeyPair() -> SRPKeys { return .init( publicKeyHexValue: "publicKeyHexValue", privateKeyHexValue: "privateKeyHexValue" ) } - + var sharedSecret: Result = .success("SharedSecret") func calculateSharedSecret( username: String, @@ -166,7 +166,7 @@ private class MockSRPClientBehavior: SRPClientBehavior { ) throws -> String { return try sharedSecret.get() } - + func generateDevicePasswordVerifier( deviceGroupKey: String, deviceKey: String, diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift index 062fa9b7bb..c97d5b1618 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentityProvider +import XCTest @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime -@testable import AWSPluginsTestCommon @testable import AWSCognitoAuthPlugin +@testable import AWSPluginsTestCommon class VerifyPasswordSRPTests: XCTestCase { @@ -39,9 +39,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) await action.execute( withDispatcher: MockDispatcher { _ in }, @@ -75,9 +77,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation(description: "passwordVerifierError") @@ -126,9 +130,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.invalidChallenge - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -177,9 +183,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.invalidTestDataWithNoSalt - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -228,9 +236,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.invalidTestDataWithNoSecretBlock - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -279,9 +289,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.invalidTestDataWithNoSRPB - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -330,9 +342,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.invalidTestDataForException - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -380,9 +394,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierCompletion = expectation( description: "passwordVerifierCompletion" @@ -433,9 +449,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -484,9 +502,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation(description: "passwordVerifierError") @@ -532,9 +552,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierCompletion = expectation( description: "passwordVerifierCompletion") @@ -578,9 +600,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierCompletion = expectation( description: "passwordVerifierCompletion") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/RevokeTokenTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/RevokeTokenTests.swift index cc6ae2290d..697e0b3b03 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/RevokeTokenTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/RevokeTokenTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentityProvider -@testable import AWSPluginsTestCommon +import XCTest @testable import AWSCognitoAuthPlugin +@testable import AWSPluginsTestCommon class RevokeTokenTests: XCTestCase { @@ -29,9 +29,11 @@ class RevokeTokenTests: XCTestCase { cognitoUserPoolASFFactory: Defaults.makeDefaultASF, cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics ) - let action = RevokeToken(signedInData: .testData, - hostedUIError: nil, - globalSignOutError: nil) + let action = RevokeToken( + signedInData: .testData, + hostedUIError: nil, + globalSignOutError: nil + ) await action.execute( withDispatcher: MockDispatcher { _ in }, @@ -60,9 +62,11 @@ class RevokeTokenTests: XCTestCase { cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics ) - let action = RevokeToken(signedInData: .testData, - hostedUIError: nil, - globalSignOutError: nil) + let action = RevokeToken( + signedInData: .testData, + hostedUIError: nil, + globalSignOutError: nil + ) let clearCredentialStoreEventSent = expectation(description: "clearCredentialStoreEventSent") let dispatcher = MockDispatcher { event in @@ -104,9 +108,11 @@ class RevokeTokenTests: XCTestCase { cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics ) - let action = RevokeToken(signedInData: .testData, - hostedUIError: nil, - globalSignOutError: nil) + let action = RevokeToken( + signedInData: .testData, + hostedUIError: nil, + globalSignOutError: nil + ) let clearCredentialStoreEventSent = expectation(description: "clearCredentialStoreEventSent") let dispatcher = MockDispatcher { event in diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/ShowHostedUISignOutTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/ShowHostedUISignOutTests.swift index af2129ad19..067d145579 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/ShowHostedUISignOutTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/ShowHostedUISignOutTests.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import AWSPluginsCore import XCTest +@testable import AWSCognitoAuthPlugin class ShowHostedUISignOutTests: XCTestCase { private var mockHostedUIResult: Result<[URLQueryItem], HostedUIError>! private var signOutRedirectURI: String! - + override func setUp() { signOutRedirectURI = "myapp://" mockHostedUIResult = .success([.init(name: "key", value: "value")]) } - + override func tearDown() { signOutRedirectURI = nil mockHostedUIResult = nil @@ -38,7 +38,8 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .signOutGlobally(let data, let error) = event.eventType else { + case .signOutGlobally(let data, let error) = event.eventType + else { XCTFail("Expected SignOutEvent.signOutGlobally, got \(event)") expectation.fulfill() return @@ -47,7 +48,7 @@ class ShowHostedUISignOutTests: XCTestCase { XCTAssertNil(error) XCTAssertEqual(data, signInData) self.validateDebugInformation(signInData: signInData, action: action) - + expectation.fulfill() }, environment: Defaults.makeDefaultAuthEnvironment( @@ -58,7 +59,7 @@ class ShowHostedUISignOutTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } - + /// Given: A ShowHostedUISignOut action with global sign out set to false /// When: execute is invoked with a success result /// Then: A .revokeToken event is dispatched @@ -73,7 +74,8 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .revokeToken(let data, let error, let globalSignOutError) = event.eventType else { + case .revokeToken(let data, let error, let globalSignOutError) = event.eventType + else { XCTFail("Expected SignOutEvent.revokeToken, got \(event)") expectation.fulfill() return @@ -92,14 +94,14 @@ class ShowHostedUISignOutTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } - + /// Given: A ShowHostedUISignOut action /// When: execute is invoked but fails to create a HostedUI session /// Then: A .userCancelled event is dispatched func testExecute_withInvalidResult_shouldDispatchUserCancelledEvent() async { mockHostedUIResult = .failure(.cancelled) let signInData = SignedInData.testData - + let action = ShowHostedUISignOut( signOutEvent: .testData, signInData: signInData @@ -132,7 +134,7 @@ class ShowHostedUISignOutTests: XCTestCase { func testExecute_withSignOutURIError_shouldThrowConfigurationError() async { mockHostedUIResult = .failure(HostedUIError.signOutURI) let signInData = SignedInData.testData - + let action = ShowHostedUISignOut( signOutEvent: .testData, signInData: signInData @@ -142,7 +144,8 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .hostedUISignOutError(let hostedUIError) = event.eventType else { + case .hostedUISignOutError(let hostedUIError) = event.eventType + else { XCTFail("Expected SignOutEvent.signOutGlobally, got \(event)") expectation.fulfill() return @@ -166,14 +169,14 @@ class ShowHostedUISignOutTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } - + /// Given: A ShowHostedUISignOut action /// When: execute is invoked but fails to create a HostedUI session with a HostedUIError.invalidContext /// Then: A .signOutGlobally event is dispatched with a HosterUIError.invalidState error func testExecute_withInvalidContext_shouldThrowInvalidStateError() async { mockHostedUIResult = .failure(HostedUIError.invalidContext) let signInData = SignedInData.testData - + let action = ShowHostedUISignOut( signOutEvent: .testData, signInData: signInData @@ -183,7 +186,8 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .hostedUISignOutError(let hostedUIError) = event.eventType else { + case .hostedUISignOutError(let hostedUIError) = event.eventType + else { XCTFail("Expected SignOutEvent.hostedUISignOutError, got \(event)") expectation.fulfill() return @@ -208,14 +212,14 @@ class ShowHostedUISignOutTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } - + /// Given: A ShowHostedUISignOut action with an invalid SignOutRedirectURI /// When: execute is invoked /// Then: A .signOutGlobally event is dispatched with a HosterUIError.configuration error func testExecute_withInvalidSignOutURI_shouldThrowConfigurationError() async { signOutRedirectURI = "invalidURI" let signInData = SignedInData.testData - + let action = ShowHostedUISignOut( signOutEvent: .testData, signInData: signInData @@ -225,7 +229,8 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .hostedUISignOutError(let hostedUIError) = event.eventType else { + case .hostedUISignOutError(let hostedUIError) = event.eventType + else { XCTFail("Expected SignOutEvent.signOutGlobally, got \(event)") expectation.fulfill() return @@ -263,12 +268,13 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .hostedUISignOutError(let hostedUIError) = event.eventType else { + case .hostedUISignOutError(let hostedUIError) = event.eventType + else { XCTFail("Expected SignOutEvent.signOutGlobally, got \(event)") expectation.fulfill() return } - + guard case .configuration(let errorDescription, _, let serviceError) = hostedUIError.authError else { XCTFail("Expected AuthError.configuration") expectation.fulfill() @@ -287,7 +293,7 @@ class ShowHostedUISignOutTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } - + /// Given: A ShowHostedUISignOut action /// When: execute is invoked with an invalid environment /// Then: A .signOutGlobally event is dispatched with a HosterUIError.configuration error @@ -301,12 +307,13 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .hostedUISignOutError(let hostedUIError) = event.eventType else { + case .hostedUISignOutError(let hostedUIError) = event.eventType + else { XCTFail("Expected SignOutEvent.signOutGlobally, got \(event)") expectation.fulfill() return } - + guard case .configuration(let errorDescription, _, let serviceError) = hostedUIError.authError else { XCTFail("Expected AuthError.configuration") expectation.fulfill() @@ -322,7 +329,7 @@ class ShowHostedUISignOutTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } - + private func validateDebugInformation(signInData: SignedInData, action: ShowHostedUISignOut) { XCTAssertFalse(action.debugDescription.isEmpty) guard let signInDataDictionary = action.debugDictionary["signInData"] as? [String: Any] else { @@ -333,13 +340,14 @@ class ShowHostedUISignOutTests: XCTestCase { for key in signInDataDictionary.keys { guard let left = signInDataDictionary[key] as? any Equatable, - let right = signInData.debugDictionary[key] as? any Equatable else { + let right = signInData.debugDictionary[key] as? any Equatable + else { continue } XCTAssertTrue(left.isEqual(to: right)) } } - + private var hostedUIEnvironment: HostedUIEnvironment { BasicHostedUIEnvironment( configuration: .init( @@ -365,7 +373,7 @@ class ShowHostedUISignOutTests: XCTestCase { } ) } - + private func identityProviderFactory() throws -> CognitoUserPoolBehavior { return MockIdentityProvider( mockInitiateAuthResponse: { _ in @@ -374,7 +382,8 @@ class ShowHostedUISignOutTests: XCTestCase { accessToken: "accessTokenNew", expiresIn: 100, idToken: "idTokenNew", - refreshToken: "refreshTokenNew") + refreshToken: "refreshTokenNew" + ) ) } ) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/SignOutGloballyTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/SignOutGloballyTests.swift index 92ab3956e4..523d573801 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/SignOutGloballyTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/SignOutGloballyTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentityProvider +import XCTest @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/VerifySignInChallenge/VerifySignInChallengeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/VerifySignInChallenge/VerifySignInChallengeTests.swift index ba635f3463..f3b9be35b3 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/VerifySignInChallenge/VerifySignInChallengeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/VerifySignInChallenge/VerifySignInChallengeTests.swift @@ -5,25 +5,28 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentityProvider +import XCTest @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime -@testable import AWSPluginsTestCommon @testable import AWSCognitoAuthPlugin +@testable import AWSPluginsTestCommon class VerifySignInChallengeTests: XCTestCase { typealias CognitoFactory = BasicSRPAuthEnvironment.CognitoUserPoolFactory - let mockRespondAuthChallenge = RespondToAuthChallenge(challenge: .smsMfa, - username: "usernameMock", - session: "mockSession", - parameters: [:]) + let mockRespondAuthChallenge = RespondToAuthChallenge( + challenge: .smsMfa, + username: "usernameMock", + session: "mockSession", + parameters: [:] + ) let mockConfirmEvent = ConfirmSignInEventData( answer: "1233", attributes: [:], metadata: [:], - friendlyDeviceName: nil) + friendlyDeviceName: nil + ) /// Test if valid input are given the service call is made /// @@ -47,9 +50,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) await action.execute( withDispatcher: MockDispatcher { _ in }, @@ -82,9 +87,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) let passwordVerifierError = expectation(description: "passwordVerifierError") @@ -131,9 +138,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) let verifyChallengeComplete = expectation(description: "verifyChallengeComplete") @@ -181,9 +190,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -231,9 +242,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) let passwordVerifierError = expectation(description: "passwordVerifierError") let dispatcher = MockDispatcher { event in @@ -277,9 +290,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) let verifyChallengeComplete = expectation(description: "verifyChallengeComplete") @@ -321,9 +336,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) let verifyChallengeComplete = expectation(description: "verifyChallengeComplete") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ClientBehaviorTests/AuthGetCurrentUserTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ClientBehaviorTests/AuthGetCurrentUserTests.swift index 4b18e2071d..9ac9488fc6 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ClientBehaviorTests/AuthGetCurrentUserTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ClientBehaviorTests/AuthGetCurrentUserTests.swift @@ -33,8 +33,7 @@ class AuthGetCurrentUserTests: XCTestCase { do { _ = try await plugin.getCurrentUser() XCTFail("Should throw AuthError.signedOut") - } - catch AuthError.signedOut { } + } catch AuthError.signedOut { } catch { XCTFail("Should throw AuthError.signedOut") } @@ -49,8 +48,7 @@ class AuthGetCurrentUserTests: XCTestCase { do { _ = try await plugin.getCurrentUser() XCTFail("Should throw AuthError.configuration") - } - catch AuthError.configuration { } + } catch AuthError.configuration { } catch { XCTFail("Should throw AuthError.configuration") } @@ -65,8 +63,7 @@ class AuthGetCurrentUserTests: XCTestCase { do { _ = try await plugin.getCurrentUser() XCTFail("Should throw AuthError.invalidState") - } - catch AuthError.invalidState { } + } catch AuthError.invalidState { } catch { XCTFail("Should throw AuthError.invalidState") } @@ -75,9 +72,11 @@ class AuthGetCurrentUserTests: XCTestCase { - private func createPlugin(authState: AuthState, - file: StaticString = #filePath, - line: UInt = #line) throws -> AWSCognitoAuthPlugin { + private func createPlugin( + authState: AuthState, + file: StaticString = #filePath, + line: UInt = #line + ) throws -> AWSCognitoAuthPlugin { let plugin = AWSCognitoAuthPlugin() plugin.authStateMachine = Defaults.makeDefaultAuthStateMachine(initialState: authState) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/ASFCognitoTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/ASFCognitoTests.swift index 395ab17f39..81512fc99e 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/ASFCognitoTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/ASFCognitoTests.swift @@ -12,13 +12,13 @@ class ASFCognitoTests: XCTestCase { func testTimeZoneOffetNegative() { let asf = CognitoUserPoolASF() - let timezoneOffet = asf.timeZoneOffet(seconds: -25200) + let timezoneOffet = asf.timeZoneOffet(seconds: -25_200) XCTAssertEqual("-07:00", timezoneOffet) } func testTimeZoneOffetPositive() { let asf = CognitoUserPoolASF() - let timezoneOffet = asf.timeZoneOffet(seconds: 25200) + let timezoneOffet = asf.timeZoneOffet(seconds: 25_200) XCTAssertEqual("+07:00", timezoneOffet) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/CognitoUserPoolASFTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/CognitoUserPoolASFTests.swift index b5dbf122cf..382e13c3e0 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/CognitoUserPoolASFTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/CognitoUserPoolASFTests.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import XCTest +@testable import AWSCognitoAuthPlugin class CognitoUserPoolASFTests: XCTestCase { private var userPool: CognitoUserPoolASF! - + override func setUp() { userPool = CognitoUserPoolASF() } - + override func tearDown() { userPool = nil } - + /// Given: A CognitoUserPoolASF /// When: userContextData is invoked /// Then: A non-empty string is returned @@ -32,7 +32,7 @@ class CognitoUserPoolASFTests: XCTestCase { ) XCTAssertFalse(result.isEmpty) } - + /// Given: A CognitoUserPoolASF /// When: calculateSecretHash is invoked /// Then: A non-empty string is returned @@ -43,7 +43,7 @@ class CognitoUserPoolASFTests: XCTestCase { ) XCTAssertFalse(result.isEmpty) } - + /// Given: A CognitoUserPoolASF /// When: calculateSecretHash is invoked with a clientId that cannot be parsed /// Then: A ASFError.hashKey is thrown diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginAmplifyOutputsConfigTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginAmplifyOutputsConfigTests.swift index 85eba053d7..29cb5086b8 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginAmplifyOutputsConfigTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginAmplifyOutputsConfigTests.swift @@ -52,10 +52,11 @@ class AWSCognitoAuthPluginAmplifyOutputsConfigTests: XCTestCase { try Amplify.add(plugin: plugin) let amplifyConfig = AmplifyOutputsData(auth: .init( - awsRegion: "us-east-1", - userPoolId: "xx", - userPoolClientId: "xx", - identityPoolId: "xx")) + awsRegion: "us-east-1", + userPoolId: "xx", + userPoolClientId: "xx", + identityPoolId: "xx" + )) do { try Amplify.configure(amplifyConfig) } catch { @@ -76,9 +77,10 @@ class AWSCognitoAuthPluginAmplifyOutputsConfigTests: XCTestCase { try Amplify.add(plugin: plugin) let amplifyConfig = AmplifyOutputsData(auth: .init( - awsRegion: "us-east-1", - userPoolId: "xx", - userPoolClientId: "xx")) + awsRegion: "us-east-1", + userPoolId: "xx", + userPoolClientId: "xx" + )) do { try Amplify.configure(amplifyConfig) } catch { @@ -99,14 +101,16 @@ class AWSCognitoAuthPluginAmplifyOutputsConfigTests: XCTestCase { networkPreferences: .init( maxRetryCount: 2, timeoutIntervalForRequest: 60, - timeoutIntervalForResource: 60)) + timeoutIntervalForResource: 60 + )) try Amplify.add(plugin: plugin) let amplifyConfig = AmplifyOutputsData(auth: .init( - awsRegion: "us-east-1", - userPoolId: "xx", - userPoolClientId: "xx", - identityPoolId: "xx")) + awsRegion: "us-east-1", + userPoolId: "xx", + userPoolClientId: "xx", + identityPoolId: "xx" + )) do { try Amplify.configure(amplifyConfig) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginConfigTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginConfigTests.swift index 553406fbe6..514ec6828d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginConfigTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginConfigTests.swift @@ -56,8 +56,10 @@ class AWSCognitoAuthPluginConfigTests: XCTestCase { let categoryConfig = AuthCategoryConfiguration(plugins: [ "awsCognitoAuthPlugin": [ "CredentialsProvider": ["CognitoIdentity": ["Default": - ["PoolId": "xx", - "Region": "us-east-1"] + [ + "PoolId": "xx", + "Region": "us-east-1" + ] ]], "CognitoUserPool": ["Default": [ "PoolId": "xx", @@ -89,8 +91,10 @@ class AWSCognitoAuthPluginConfigTests: XCTestCase { let categoryConfig = AuthCategoryConfiguration(plugins: [ "awsCognitoAuthPlugin": [ "CredentialsProvider": ["CognitoIdentity": ["Default": - ["PoolId": "cc", - "Region": "us-east-1"] + [ + "PoolId": "cc", + "Region": "us-east-1" + ] ]] ] ]) @@ -146,8 +150,10 @@ class AWSCognitoAuthPluginConfigTests: XCTestCase { let categoryConfig = AuthCategoryConfiguration(plugins: [ "awsCognitoAuthPlugin": [ "CredentialsProvider": ["CognitoIdentity": ["Default": - ["xx": "xx", - "xx2": "us-east-1"] + [ + "xx": "xx", + "xx2": "us-east-1" + ] ]], "CognitoUserPool": ["Default": [ "xx": "xx", @@ -203,14 +209,17 @@ class AWSCognitoAuthPluginConfigTests: XCTestCase { networkPreferences: .init( maxRetryCount: 2, timeoutIntervalForRequest: 60, - timeoutIntervalForResource: 60)) + timeoutIntervalForResource: 60 + )) try Amplify.add(plugin: plugin) let categoryConfig = AuthCategoryConfiguration(plugins: [ "awsCognitoAuthPlugin": [ "CredentialsProvider": ["CognitoIdentity": ["Default": - ["PoolId": "xx", - "Region": "us-east-1"] + [ + "PoolId": "xx", + "Region": "us-east-1" + ] ]], "CognitoUserPool": ["Default": [ "PoolId": "xx", @@ -222,7 +231,7 @@ class AWSCognitoAuthPluginConfigTests: XCTestCase { let amplifyConfig = AmplifyConfiguration(auth: categoryConfig) do { try Amplify.configure(amplifyConfig) - + let escapeHatch = plugin.getEscapeHatch() guard case .userPoolAndIdentityPool(let userPoolClient, let identityPoolClient) = escapeHatch else { XCTFail("Expected .userPool, got \(escapeHatch)") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/ClientSecretConfigurationTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/ClientSecretConfigurationTests.swift index 47c0b7c6f1..9445b11ec6 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/ClientSecretConfigurationTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/ClientSecretConfigurationTests.swift @@ -7,27 +7,29 @@ import Foundation -import XCTest import AWSCognitoIdentity +import AWSCognitoIdentityProvider +import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import AWSCognitoIdentityProvider class ClientSecretConfigurationTests: XCTestCase { let networkTimeout = TimeInterval(2) var mockIdentityProvider: CognitoUserPoolBehavior! var plugin: AWSCognitoAuthPlugin! - + var initialState: AuthState { AuthState.configured( AuthenticationState.signedIn( SignedInData( signedInDate: Date(), signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData)), - AuthorizationState.sessionEstablished(AmplifyCredentials.testData)) + cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData + )), + AuthorizationState.sessionEstablished(AmplifyCredentials.testData) + ) } override func setUp() { @@ -38,25 +40,30 @@ class ClientSecretConfigurationTests: XCTestCase { } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } let mockIdentity = MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: { mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) let statemachine = Defaults.makeDefaultAuthStateMachine( initialState: initialState, identityPoolFactory: { mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) plugin?.configure( authConfiguration: Defaults.makeDefaultAuthConfigData(), @@ -64,7 +71,8 @@ class ClientSecretConfigurationTests: XCTestCase { authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) } @@ -156,23 +164,26 @@ class ClientSecretConfigurationTests: XCTestCase { /// func testClientSecretWithSignUp() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { request in XCTAssertNotNil(request.secretHash) return .init( codeDeliveryDetails: .init( attributeName: "some attribute", deliveryMedium: .email, - destination: "random@random.com"), + destination: "random@random.com" + ), userConfirmed: false, - userSub: "userId") + userSub: "userId" + ) } ) - let result = try await self.plugin.signUp( + let result = try await plugin.signUp( username: "jeffb", password: "Valid&99", - options: nil) + options: nil + ) guard case .confirmUser = result.nextStep else { XCTFail("Result should be .confirmUser for next step") @@ -190,14 +201,14 @@ class ClientSecretConfigurationTests: XCTestCase { /// func testClientSecretWithConfirmSignUp() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { request in XCTAssertNotNil(request.secretHash) return .init() } ) - _ = try await self.plugin.confirmSignUp( + _ = try await plugin.confirmSignUp( for: "someuser", confirmationCode: "code", options: nil @@ -213,15 +224,17 @@ class ClientSecretConfigurationTests: XCTestCase { /// - Plugin should pass the secret hash created with client secret /// func testClientSecretWithRevokeToken() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { request in XCTAssertNotNil(request.clientSecret) return .testData }, mockGlobalSignOutResponse: { _ in return .testData - }) + } + ) guard let result = await plugin.signOut() as? AWSCognitoSignOutResult, - case .complete = result else { + case .complete = result + else { XCTFail("Did not return complete signOut") return } @@ -237,7 +250,7 @@ class ClientSecretConfigurationTests: XCTestCase { /// func testClientSecretWithInitiateAuth() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { request in XCTAssertNotNil(request.clientSecret) return .testData @@ -247,7 +260,8 @@ class ClientSecretConfigurationTests: XCTestCase { authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockGlobalSignOutResponse: { _ in return .testData @@ -261,23 +275,29 @@ class ClientSecretConfigurationTests: XCTestCase { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") - }) + session: "session" + ) + } + ) _ = await plugin.signOut() - - let pluginOptions = AWSAuthSignInOptions(validationData: ["somekey": "somevalue"], - metadata: ["somekey": "somevalue"]) + + let pluginOptions = AWSAuthSignInOptions( + validationData: ["somekey": "somevalue"], + metadata: ["somekey": "somevalue"] + ) let options = AuthSignInRequest.Options(pluginOptions: pluginOptions) do { let result = try await plugin.signIn( username: "username", password: "password", - options: options) + options: options + ) guard case .done = result.nextStep else { XCTFail("Result should be .done for next step") return diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/EscapeHatchTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/EscapeHatchTests.swift index acf3ec1c0d..6c8b53084d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/EscapeHatchTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/EscapeHatchTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import enum Amplify.JSONValue import XCTest @testable import func AmplifyTestCommon.XCTAssertThrowFatalError -import enum Amplify.JSONValue @testable import AWSCognitoAuthPlugin @@ -103,7 +103,7 @@ class EscapeHatchTests: XCTestCase { return } } - + /// Test escape hatch without a valid configuration /// /// - Given: A AWSCognitoAuthPlugin plugin without being configured diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CredentialStore/CredentialStoreOperationClientTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CredentialStore/CredentialStoreOperationClientTests.swift index a5587e1f95..b74336fbc2 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CredentialStore/CredentialStoreOperationClientTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CredentialStore/CredentialStoreOperationClientTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation import XCTest -import Amplify @testable import AWSCognitoAuthPlugin class CredentialStoreOperationClientTests: XCTestCase { @@ -27,7 +27,8 @@ class CredentialStoreOperationClientTests: XCTestCase { let credentialStateMachine = CredentialStoreStateMachine( resolver: CredentialStoreState.Resolver(), environment: credentialEnvironment, - initialState: .idle) + initialState: .idle + ) credentialClient = CredentialStoreOperationClient( credentialStoreStateMachine: credentialStateMachine) @@ -50,7 +51,7 @@ class CredentialStoreOperationClientTests: XCTestCase { func testMultipleSuccess() async throws { await withThrowingTaskGroup(of: Void.self, body: { group in - for _ in 1...100 { + for _ in 1 ... 100 { group.addTask { let deviceId = "someDeviceID-\(UUID().uuidString)" let username = "someUsername-\(UUID().uuidString)" @@ -84,7 +85,7 @@ class CredentialStoreOperationClientTests: XCTestCase { func testMultipleFailuresDuringFetch() async throws { await withThrowingTaskGroup(of: Void.self, body: { group in - for _ in 1...100 { + for _ in 1 ... 100 { group.addTask { let deviceId = "someDeviceID-\(UUID().uuidString)" let username = "someUsername-\(UUID().uuidString)" diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/HubEventTests/AuthHubEventHandlerTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/HubEventTests/AuthHubEventHandlerTests.swift index 5dc7ee016a..59d57245e0 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/HubEventTests/AuthHubEventHandlerTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/HubEventTests/AuthHubEventHandlerTests.swift @@ -4,13 +4,14 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Foundation +import AWSCognitoIdentity +import AWSCognitoIdentityProvider import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentity -import AWSCognitoIdentityProvider class AuthHubEventHandlerTests: XCTestCase { @@ -312,7 +313,8 @@ class AuthHubEventHandlerTests: XCTestCase { authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -321,10 +323,12 @@ class AuthHubEventHandlerTests: XCTestCase { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) let initialState = AuthState.configured(.signedOut(.init(lastKnownUserName: nil)), .configured) @@ -337,8 +341,10 @@ class AuthHubEventHandlerTests: XCTestCase { AuthenticationState.signingIn(.resolvingChallenge( .waitingForAnswer(.testData(), .apiBased(.userSRP)), .smsMfa, - .apiBased(.userSRP))), - AuthorizationState.sessionEstablished(.testData)) + .apiBased(.userSRP) + )), + AuthorizationState.sessionEstablished(.testData) + ) let mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in @@ -351,10 +357,13 @@ class AuthHubEventHandlerTests: XCTestCase { private func configurePluginForDeleteUserEvent() { let initialState = AuthState.configured( AuthenticationState.signedIn( - SignedInData(signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData)), - AuthorizationState.sessionEstablished(AmplifyCredentials.testData)) + SignedInData( + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData + )), + AuthorizationState.sessionEstablished(AmplifyCredentials.testData) + ) let mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in @@ -373,10 +382,13 @@ class AuthHubEventHandlerTests: XCTestCase { private func configurePluginForSignOutEvent() { let initialState = AuthState.configured( AuthenticationState.signedIn( - SignedInData(signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData)), - AuthorizationState.sessionEstablished(AmplifyCredentials.testData)) + SignedInData( + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData + )), + AuthorizationState.sessionEstablished(AmplifyCredentials.testData) + ) let mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in @@ -393,7 +405,8 @@ class AuthHubEventHandlerTests: XCTestCase { private func configurePluginForFederationEvent() { let initialState = AuthState.configured( AuthenticationState.signedOut(.testData), - AuthorizationState.configured) + AuthorizationState.configured + ) let mockIdentityProvider = MockIdentityProvider() @@ -403,7 +416,8 @@ class AuthHubEventHandlerTests: XCTestCase { private func configurePluginForClearedFederationEvent() { let initialState = AuthState.configured( AuthenticationState.federatedToIdentityPool, - AuthorizationState.sessionEstablished(AmplifyCredentials.testData)) + AuthorizationState.sessionEstablished(AmplifyCredentials.testData) + ) let mockIdentityProvider = MockIdentityProvider() @@ -414,7 +428,8 @@ class AuthHubEventHandlerTests: XCTestCase { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let mockIdentityProvider = MockIdentityProvider( mockInitiateAuthResponse: { _ in @@ -433,10 +448,12 @@ class AuthHubEventHandlerTests: XCTestCase { private func configurePlugin(initialState: AuthState, userPoolFactory: CognitoUserPoolBehavior) { plugin = AWSCognitoAuthPlugin() - let mockTokenResult = ["id_token": AWSCognitoUserPoolTokens.testData.idToken, - "access_token": AWSCognitoUserPoolTokens.testData.accessToken, - "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken, - "expires_in": 10] as [String: Any] + let mockTokenResult = [ + "id_token": AWSCognitoUserPoolTokens.testData.idToken, + "access_token": AWSCognitoUserPoolTokens.testData.accessToken, + "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken, + "expires_in": 10 + ] as [String: Any] let mockJson = try! JSONSerialization.data(withJSONObject: mockTokenResult) let mockState = "someState" let mockProof = "someProof" @@ -461,37 +478,44 @@ class AuthHubEventHandlerTests: XCTestCase { return MockRandomStringGenerator(mockString: mockState, mockUUID: mockState) } - let hostedUIEnv = BasicHostedUIEnvironment(configuration: hostedUIconfig, - hostedUISessionFactory: sessionFactory, - urlSessionFactory: urlSessionMock, - randomStringFactory: mockRandomString) + let hostedUIEnv = BasicHostedUIEnvironment( + configuration: hostedUIconfig, + hostedUISessionFactory: sessionFactory, + urlSessionFactory: urlSessionMock, + randomStringFactory: mockRandomString + ) let getId: MockIdentity.MockGetIdResponse = { _ in return .init(identityId: "mockIdentityId") } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } let mockIdentity = MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: { mockIdentity }, userPoolFactory: { userPoolFactory }, - hostedUIEnvironment: hostedUIEnv) + hostedUIEnvironment: hostedUIEnv + ) let statemachine = Defaults.makeDefaultAuthStateMachine( initialState: initialState, identityPoolFactory: { mockIdentity }, userPoolFactory: { userPoolFactory }, - hostedUIEnvironment: hostedUIEnv) + hostedUIEnvironment: hostedUIEnv + ) let authHandler = AuthHubEventHandler() @@ -501,7 +525,8 @@ class AuthHubEventHandlerTests: XCTestCase { authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: authHandler, - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) } override func tearDown() async throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockAnalyticsHandler.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockAnalyticsHandler.swift index bf141098ef..36cd42f3c9 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockAnalyticsHandler.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockAnalyticsHandler.swift @@ -6,8 +6,8 @@ // import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +@testable import AWSCognitoAuthPlugin struct MockAnalyticsHandler: UserPoolAnalyticsBehavior { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/AWSCognitoUserPoolTokens+Mock.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/AWSCognitoUserPoolTokens+Mock.swift index 3bdd67555c..6047c6af84 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/AWSCognitoUserPoolTokens+Mock.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/AWSCognitoUserPoolTokens+Mock.swift @@ -21,11 +21,13 @@ extension AWSCognitoUserPoolTokens { idToken: CognitoAuthTestHelper.buildToken(for: tokenData), accessToken: CognitoAuthTestHelper.buildToken(for: tokenData), refreshToken: "refreshToken", - expiresIn: Int(Date(timeIntervalSinceNow: 121).timeIntervalSince1970)) + expiresIn: Int(Date(timeIntervalSinceNow: 121).timeIntervalSince1970) + ) } static let expiredTestData = AWSCognitoUserPoolTokens( - idToken: "XX", accessToken: "XX", refreshToken: "XX", expiresIn: -10000) + idToken: "XX", accessToken: "XX", refreshToken: "XX", expiresIn: -10_000 + ) static func testData(username: String, sub: String) -> AWSCognitoUserPoolTokens { let tokenData = [ @@ -38,7 +40,8 @@ extension AWSCognitoUserPoolTokens { idToken: CognitoAuthTestHelper.buildToken(for: tokenData), accessToken: CognitoAuthTestHelper.buildToken(for: tokenData), refreshToken: "refreshToken", - expiresIn: 121) + expiresIn: 121 + ) } static var testDataWithoutExp: AWSCognitoUserPoolTokens { @@ -51,6 +54,7 @@ extension AWSCognitoUserPoolTokens { idToken: CognitoAuthTestHelper.buildToken(for: tokenDataWithoutExp), accessToken: CognitoAuthTestHelper.buildToken(for: tokenDataWithoutExp), refreshToken: "refreshToken", - expiresIn: nil) + expiresIn: nil + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/GlobalSignOutOutputResponse+Mock.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/GlobalSignOutOutputResponse+Mock.swift index 18affcafee..c4a6b2f4fd 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/GlobalSignOutOutputResponse+Mock.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/GlobalSignOutOutputResponse+Mock.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation extension GlobalSignOutOutput { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/RevokeTokenOutputResponse+Mock.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/RevokeTokenOutputResponse+Mock.swift index 81b5296c34..e42ff8f5b7 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/RevokeTokenOutputResponse+Mock.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/RevokeTokenOutputResponse+Mock.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation extension RevokeTokenOutput { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/SignedInData+Mock.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/SignedInData+Mock.swift index e5520078d6..19d5c6d200 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/SignedInData+Mock.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/SignedInData+Mock.swift @@ -12,26 +12,33 @@ extension SignedInData { static var testData: SignedInData { let tokens = AWSCognitoUserPoolTokens.testData - return SignedInData(signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: tokens) + return SignedInData( + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: tokens + ) } static var expiredTestData: SignedInData { let tokens = AWSCognitoUserPoolTokens.expiredTestData - return SignedInData(signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: tokens) + return SignedInData( + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: tokens + ) } static var hostedUISignInData: SignedInData { let tokens = AWSCognitoUserPoolTokens.testData - return SignedInData(signedInDate: Date(), - signInMethod: .hostedUI(.init( - scopes: [], - providerInfo: .init(authProvider: .google, idpIdentifier: ""), - presentationAnchor: nil, - preferPrivateSession: false)), - cognitoUserPoolTokens: tokens) + return SignedInData( + signedInDate: Date(), + signInMethod: .hostedUI(.init( + scopes: [], + providerInfo: .init(authProvider: .google, idpIdentifier: ""), + presentationAnchor: nil, + preferPrivateSession: false + )), + cognitoUserPoolTokens: tokens + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateConfiguringTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateConfiguringTests.swift index 21db49f383..f62c949b3d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateConfiguringTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateConfiguringTests.swift @@ -19,7 +19,8 @@ class AuthStateConfiguringTests: XCTestCase { let expected = AuthState.validatingCredentialsAndConfiguration let resolution = resolver.resolve( oldState: oldState, - byApplying: AuthEvent.validateCredentialAndConfiguration) + byApplying: AuthEvent.validateCredentialAndConfiguration + ) XCTAssertEqual(resolution.newState, expected) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateTestData.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateTestData.swift index ab3552121d..c3b7e6b485 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateTestData.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateTestData.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoIdentityProvider import Foundation @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider extension AuthEvent { @@ -22,26 +22,32 @@ extension AuthEvent { static let configureAuth = AuthEvent( id: "configureAuth", - eventType: .configureAuth(.testData)) + eventType: .configureAuth(.testData) + ) static let configureAuthentication = AuthEvent( id: "configureAuthentication", - eventType: .configureAuthentication(.testData, .testData)) + eventType: .configureAuthentication(.testData, .testData) + ) static let configureAuthorization = AuthEvent( id: "configureAuthorization", - eventType: .configureAuthorization(.testData, .testData)) + eventType: .configureAuthorization(.testData, .testData) + ) static let authenticationConfigured = AuthEvent( id: "authenticationConfigured", - eventType: .authenticationConfigured(.testData, .testData)) + eventType: .authenticationConfigured(.testData, .testData) + ) static let authorizationConfigured = AuthEvent( id: "authorizationConfigured", - eventType: .authorizationConfigured) + eventType: .authorizationConfigured + ) static let validateCredentialAndConfiguration = AuthEvent( id: "validateCredentialAndConfiguration", - eventType: .validateCredentialAndConfiguration(.testData, .testData)) + eventType: .validateCredentialAndConfiguration(.testData, .testData) + ) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthTestData.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthTestData.swift index 01a4bff480..e942ba00fc 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthTestData.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthTestData.swift @@ -65,9 +65,11 @@ extension AuthenticationError { } extension SignInEventData { - static let testData = SignInEventData(username: "testUserName", - password: "testPassword", - signInMethod: .apiBased(.userSRP)) + static let testData = SignInEventData( + username: "testUserName", + password: "testPassword", + signInMethod: .apiBased(.userSRP) + ) } extension SignOutEventData { @@ -84,7 +86,8 @@ extension SignInState { static let testData = SignInState.signingInWithSRP(.notStarted, SignInEventData( username: "", password: "", - signInMethod:.apiBased(.userSRP))) + signInMethod: .apiBased(.userSRP) + )) } extension UserPoolConfigurationData { @@ -98,8 +101,10 @@ extension UserPoolConfigurationData { } extension IdentityPoolConfigurationData { - static let testData = IdentityPoolConfigurationData(poolId: "poolId", - region: "regionId") + static let testData = IdentityPoolConfigurationData( + poolId: "poolId", + region: "regionId" + ) } struct MockInvalidEnvironment: Environment { } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationStateResolverTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationStateResolverTests.swift index b2d9f55c5a..e8389d786d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationStateResolverTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationStateResolverTests.swift @@ -12,9 +12,10 @@ import XCTest typealias AuthorizationStateSequence = StateSequence extension AuthorizationStateSequence { - init(oldState: MyState, - event: MyEvent, - expected: MyState + init( + oldState: MyState, + event: MyEvent, + expected: MyState ) { self.resolver = AuthorizationState.Resolver().logging().eraseToAnyResolver() self.oldState = oldState @@ -28,17 +29,23 @@ class AuthorizationStateResolverTests: XCTestCase { let authorizationError = AuthorizationError.configuration(message: "someError") let testCredentials = AmplifyCredentials.testData let validSequences: [AuthorizationStateSequence] = [ - AuthorizationStateSequence(oldState: .notConfigured, - event: AuthorizationEvent(eventType: .configure), - expected: .configured), - AuthorizationStateSequence(oldState: .notConfigured, - event: AuthorizationEvent( + AuthorizationStateSequence( + oldState: .notConfigured, + event: AuthorizationEvent(eventType: .configure), + expected: .configured + ), + AuthorizationStateSequence( + oldState: .notConfigured, + event: AuthorizationEvent( eventType: .cachedCredentialsAvailable(testCredentials)), - expected: .sessionEstablished(testCredentials)), - AuthorizationStateSequence(oldState: .notConfigured, - event: AuthorizationEvent( + expected: .sessionEstablished(testCredentials) + ), + AuthorizationStateSequence( + oldState: .notConfigured, + event: AuthorizationEvent( eventType: .throwError(authorizationError)), - expected: .error(authorizationError)) + expected: .error(authorizationError) + ) ] @@ -51,12 +58,16 @@ class AuthorizationStateResolverTests: XCTestCase { let authorizationError = AuthorizationError.configuration(message: "someError") let invalidSequences: [AuthorizationStateSequence] = [ - AuthorizationStateSequence(oldState: .notConfigured, - event: AuthorizationEvent(eventType: .throwError(authorizationError)), - expected: .configured), - AuthorizationStateSequence(oldState: .configured, - event: AuthorizationEvent(eventType: .throwError(authorizationError)), - expected: .notConfigured) + AuthorizationStateSequence( + oldState: .notConfigured, + event: AuthorizationEvent(eventType: .throwError(authorizationError)), + expected: .configured + ), + AuthorizationStateSequence( + oldState: .configured, + event: AuthorizationEvent(eventType: .throwError(authorizationError)), + expected: .notConfigured + ) ] for sequence in invalidSequences { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationTestData.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationTestData.swift index 0eb909095e..fb49ce7412 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationTestData.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationTestData.swift @@ -12,26 +12,32 @@ import Foundation extension AWSAuthCognitoSession { static var testData: AWSAuthCognitoSession { - AWSAuthCognitoSession(isSignedIn: true, - identityIdResult: .success("identityId"), - awsCredentialsResult: .success(AuthAWSCognitoCredentials.testData), - cognitoTokensResult: .success(AWSCognitoUserPoolTokens.testData)) + AWSAuthCognitoSession( + isSignedIn: true, + identityIdResult: .success("identityId"), + awsCredentialsResult: .success(AuthAWSCognitoCredentials.testData), + cognitoTokensResult: .success(AWSCognitoUserPoolTokens.testData) + ) } } extension AuthAWSCognitoCredentials { static var testData: AuthAWSCognitoCredentials { - AuthAWSCognitoCredentials(accessKeyId: "accessKey", - secretAccessKey: "secretAccessKey", - sessionToken: "sessionToken", - expiration: Date() + 121) + AuthAWSCognitoCredentials( + accessKeyId: "accessKey", + secretAccessKey: "secretAccessKey", + sessionToken: "sessionToken", + expiration: Date() + 121 + ) } static var expiredTestData: AuthAWSCognitoCredentials { - AuthAWSCognitoCredentials(accessKeyId: "accessKey", - secretAccessKey: "secretAccessKey", - sessionToken: "sessionToken", - expiration: Date() - 10000) + AuthAWSCognitoCredentials( + accessKeyId: "accessKey", + secretAccessKey: "secretAccessKey", + sessionToken: "sessionToken", + expiration: Date() - 10_000 + ) } } @@ -43,36 +49,48 @@ extension FederatedToken { extension AmplifyCredentials { static var testData: AmplifyCredentials { - AmplifyCredentials.userPoolAndIdentityPool(signedInData: .testData, - identityID: "identityId", - credentials: AuthAWSCognitoCredentials.testData) + AmplifyCredentials.userPoolAndIdentityPool( + signedInData: .testData, + identityID: "identityId", + credentials: AuthAWSCognitoCredentials.testData + ) } static var testDataIdentityPool: AmplifyCredentials { - AmplifyCredentials.identityPoolOnly(identityID: "someId", - credentials: .testData) + AmplifyCredentials.identityPoolOnly( + identityID: "someId", + credentials: .testData + ) } static var hostedUITestData: AmplifyCredentials { - AmplifyCredentials.userPoolAndIdentityPool(signedInData: .hostedUISignInData, - identityID: "identityId", - credentials: AuthAWSCognitoCredentials.testData) + AmplifyCredentials.userPoolAndIdentityPool( + signedInData: .hostedUISignInData, + identityID: "identityId", + credentials: AuthAWSCognitoCredentials.testData + ) } static var testDataWithExpiredTokens: AmplifyCredentials { - AmplifyCredentials.userPoolAndIdentityPool(signedInData: .expiredTestData, - identityID: "identityId", - credentials: AuthAWSCognitoCredentials.testData) + AmplifyCredentials.userPoolAndIdentityPool( + signedInData: .expiredTestData, + identityID: "identityId", + credentials: AuthAWSCognitoCredentials.testData + ) } static var testDataWithExpiredAWSCredentials: AmplifyCredentials { - AmplifyCredentials.userPoolAndIdentityPool(signedInData: .testData, - identityID: "identityId", - credentials: AuthAWSCognitoCredentials.expiredTestData) + AmplifyCredentials.userPoolAndIdentityPool( + signedInData: .testData, + identityID: "identityId", + credentials: AuthAWSCognitoCredentials.expiredTestData + ) } static var testDataIdentityPoolWithExpiredTokens: AmplifyCredentials { - AmplifyCredentials.identityPoolOnly(identityID: "identityId", - credentials: AuthAWSCognitoCredentials.testData) + AmplifyCredentials.identityPoolOnly( + identityID: "identityId", + credentials: AuthAWSCognitoCredentials.testData + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/FetchAuthSessionStateResolverTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/FetchAuthSessionStateResolverTests.swift index 43a8f7b9e0..9d7c7c7e82 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/FetchAuthSessionStateResolverTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/FetchAuthSessionStateResolverTests.swift @@ -5,17 +5,18 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest @testable import AWSCognitoAuthPlugin typealias FetchAuthSessionStateSequence = StateSequence extension FetchAuthSessionStateSequence { - init(oldState: MyState, - event: MyEvent, - expected: MyState + init( + oldState: MyState, + event: MyEvent, + expected: MyState ) { self.resolver = FetchAuthSessionState.Resolver().logging().eraseToAnyResolver() self.oldState = oldState @@ -27,25 +28,8 @@ extension FetchAuthSessionStateSequence { class FetchAuthSessionStateResolverTests: XCTestCase { func testValidFetchAuthSessionStateSequences() throws { -// let cognitoSession = AWSAuthCognitoSession.testData - - let validSequences: [FetchAuthSessionStateSequence] = [ -// StateSequence(oldState: .initializingFetchAuthSession, -// event: FetchAuthSessionEvent(eventType: .fetchIdentity(cognitoSession)), -// expected: .fetchingIdentity(FetchIdentityState.configuring)), -// StateSequence(oldState: .initializingFetchAuthSession, -// event: FetchAuthSessionEvent(eventType: .fetchUserPoolTokens(cognitoSession)), -// expected: .fetchingUserPoolTokens(FetchUserPoolTokensState.configuring)), -// StateSequence(oldState: .fetchingUserPoolTokens(FetchUserPoolTokensState.configuring), -// event: FetchAuthSessionEvent(eventType: .fetchIdentity(cognitoSession)), -// expected: .fetchingIdentity(FetchIdentityState.configuring)), -// StateSequence(oldState: .fetchingIdentity(FetchIdentityState.configuring), -// event: FetchAuthSessionEvent(eventType: .fetchAWSCredentials(cognitoSession)), -// expected: .fetchingAWSCredentials(FetchAWSCredentialsState.configuring)), -// StateSequence(oldState: .fetchingAWSCredentials(FetchAWSCredentialsState.fetched), -// event: FetchAuthSessionEvent(eventType: .fetchedAuthSession(cognitoSession)), -// expected: .sessionEstablished) - ] + + let validSequences: [FetchAuthSessionStateSequence] = [] for sequence in validSequences { sequence.assertResolvesToExpected() diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/CredentialStoreState/CredentialStoreStateResolverTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/CredentialStoreState/CredentialStoreStateResolverTests.swift index 6316967d01..cedf486bfc 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/CredentialStoreState/CredentialStoreStateResolverTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/CredentialStoreState/CredentialStoreStateResolverTests.swift @@ -5,16 +5,17 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore +import XCTest @testable import AWSCognitoAuthPlugin typealias CredentialStoreStateSequence = StateSequence extension CredentialStoreStateSequence { - init(oldState: MyState, - event: MyEvent, - expected: MyState + init( + oldState: MyState, + event: MyEvent, + expected: MyState ) { self.resolver = CredentialStoreState.Resolver().logging().eraseToAnyResolver() self.oldState = oldState @@ -32,71 +33,88 @@ class CredentialStoreStateResolverTests: XCTestCase { CredentialStoreStateSequence( oldState: .notConfigured, event: CredentialStoreEvent(eventType: .migrateLegacyCredentialStore), - expected: .migratingLegacyStore), + expected: .migratingLegacyStore + ), CredentialStoreStateSequence( oldState: .migratingLegacyStore, event: CredentialStoreEvent(eventType: .loadCredentialStore(.amplifyCredentials)), - expected: .loadingStoredCredentials), + expected: .loadingStoredCredentials + ), CredentialStoreStateSequence( oldState: .loadingStoredCredentials, event: CredentialStoreEvent(eventType: .completedOperation(.amplifyCredentials(testData))), - expected: .success(.amplifyCredentials(testData))), + expected: .success(.amplifyCredentials(testData)) + ), CredentialStoreStateSequence( oldState: .loadingStoredCredentials, event: CredentialStoreEvent(eventType: .throwError(credentialStoreError)), - expected: .error(credentialStoreError)), + expected: .error(credentialStoreError) + ), CredentialStoreStateSequence( oldState: .clearingCredentials, event: CredentialStoreEvent(eventType: .credentialCleared(.amplifyCredentials)), - expected: .clearedCredential(.amplifyCredentials)), + expected: .clearedCredential(.amplifyCredentials) + ), CredentialStoreStateSequence( oldState: .clearingCredentials, event: CredentialStoreEvent(eventType: .throwError(credentialStoreError)), - expected: .error(credentialStoreError)), + expected: .error(credentialStoreError) + ), CredentialStoreStateSequence( oldState: .storingCredentials, event: CredentialStoreEvent(eventType: .completedOperation(.amplifyCredentials(testData))), - expected: .success(.amplifyCredentials(testData))), + expected: .success(.amplifyCredentials(testData)) + ), CredentialStoreStateSequence( oldState: .storingCredentials, event: CredentialStoreEvent(eventType: .throwError(credentialStoreError)), - expected: .error(credentialStoreError)), + expected: .error(credentialStoreError) + ), CredentialStoreStateSequence( oldState: .success(.amplifyCredentials(testData)), event: CredentialStoreEvent(eventType: .loadCredentialStore(.amplifyCredentials)), - expected: .success(.amplifyCredentials(testData))), + expected: .success(.amplifyCredentials(testData)) + ), CredentialStoreStateSequence( oldState: .success(.amplifyCredentials(testData)), event: CredentialStoreEvent(eventType: .storeCredentials(.amplifyCredentials(testData))), - expected: .success(.amplifyCredentials(testData))), + expected: .success(.amplifyCredentials(testData)) + ), CredentialStoreStateSequence( oldState: .success(.amplifyCredentials(testData)), event: CredentialStoreEvent(eventType: .clearCredentialStore(.amplifyCredentials)), - expected: .success(.amplifyCredentials(testData))), + expected: .success(.amplifyCredentials(testData)) + ), CredentialStoreStateSequence( oldState: .error(credentialStoreError), event: CredentialStoreEvent(eventType: .loadCredentialStore(.amplifyCredentials)), - expected: .error(credentialStoreError)), + expected: .error(credentialStoreError) + ), CredentialStoreStateSequence( oldState: .error(credentialStoreError), event: CredentialStoreEvent(eventType: .storeCredentials(.amplifyCredentials(testData))), - expected: .error(credentialStoreError)), + expected: .error(credentialStoreError) + ), CredentialStoreStateSequence( oldState: .error(credentialStoreError), event: CredentialStoreEvent(eventType: .clearCredentialStore(.amplifyCredentials)), - expected: .error(credentialStoreError)), + expected: .error(credentialStoreError) + ), CredentialStoreStateSequence( oldState: .idle, event: CredentialStoreEvent(eventType: .loadCredentialStore(.amplifyCredentials)), - expected: .loadingStoredCredentials), + expected: .loadingStoredCredentials + ), CredentialStoreStateSequence( oldState: .idle, event: CredentialStoreEvent(eventType: .storeCredentials(.amplifyCredentials(testData))), - expected: .storingCredentials), + expected: .storingCredentials + ), CredentialStoreStateSequence( oldState: .idle, event: CredentialStoreEvent(eventType: .clearCredentialStore(.amplifyCredentials)), - expected: .clearingCredentials) + expected: .clearingCredentials + ) ] for sequence in validSequences { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SRPSignInState/SRPTestData.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SRPSignInState/SRPTestData.swift index 4ecd257a5d..dfab6d1aee 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SRPSignInState/SRPTestData.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SRPSignInState/SRPTestData.swift @@ -7,8 +7,8 @@ import Foundation -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +@testable import AWSCognitoAuthPlugin // MARK: - Test Data @@ -28,43 +28,50 @@ extension InitiateAuthOutput { authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: nil, - session: nil) + session: nil + ) static let validTestData = InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "session") + session: "session" + ) static let invalidChallenge = InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: [:], - session: nil) + session: nil + ) static let invalidTestDataWithNoSalt = InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.invalidChalengeParamsNoSalt, - session: "session") + session: "session" + ) static let invalidTestDataWithNoSecretBlock = InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.invalidChalengeParamsNoSecretBlock, - session: "session") + session: "session" + ) static let invalidTestDataWithNoSRPB = InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.invalidChalengeParamsNoSRPB, - session: "session") + session: "session" + ) static let invalidTestDataForException = InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.invalidChalengeParamsForException, - session: "session") + session: "session" + ) } extension RespondToAuthChallengeOutput { @@ -75,13 +82,15 @@ extension RespondToAuthChallengeOutput { idToken: "idTokenXXX", newDeviceMetadata: nil, refreshToken: "refreshTokenXXX", - tokenType: "Bearer") + tokenType: "Bearer" + ) return RespondToAuthChallengeOutput( authenticationResult: result, challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) } static func testDataWithNewDevice() -> RespondToAuthChallengeOutput { @@ -91,13 +100,15 @@ extension RespondToAuthChallengeOutput { idToken: "idTokenXXX", newDeviceMetadata: .init(deviceGroupKey: "mockGroupKey", deviceKey: "mockKey"), refreshToken: "refreshTokenXXX", - tokenType: "Bearer") + tokenType: "Bearer" + ) return RespondToAuthChallengeOutput( authenticationResult: result, challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) } static func testDataWithVerifyDevice() -> RespondToAuthChallengeOutput { @@ -105,17 +116,20 @@ extension RespondToAuthChallengeOutput { authenticationResult: nil, challengeName: .deviceSrpAuth, challengeParameters: [:], - session: "session") + session: "session" + ) } static func testData( challenge: CognitoIdentityProviderClientTypes.ChallengeNameType = .smsMfa, - challengeParameters: [String: String] = [:]) -> RespondToAuthChallengeOutput { + challengeParameters: [String: String] = [:] + ) -> RespondToAuthChallengeOutput { return RespondToAuthChallengeOutput( authenticationResult: nil, challengeName: challenge, challengeParameters: challengeParameters, - session: "session") + session: "session" + ) } } @@ -126,12 +140,14 @@ extension RespondToAuthChallenge { challenge: CognitoIdentityProviderClientTypes.ChallengeNameType = .smsMfa, username: String = "username", session: String = "session", - parameters: [String: String] = [:]) -> RespondToAuthChallenge { + parameters: [String: String] = [:] + ) -> RespondToAuthChallenge { RespondToAuthChallenge( challenge: challenge, username: username, session: session, - parameters: parameters) + parameters: parameters + ) } } @@ -212,7 +228,8 @@ extension SRPStateData { "1739014fed1802170702c5a034b2ff47d5a8d871db7e5bf51cb3ad29553101ed4cbd" + "98bab9079c01ab6acd0e75518d0cda640b9a1f011c9a7cefab68b6ddce666c874659" + "8a502c0e6adef0722bac", - privateKeyHexValue: "c142c2d2471fd53bca99c2fdec84e522adec8ee2dcda0d9fff9dbea52ac4a65f"), + privateKeyHexValue: "c142c2d2471fd53bca99c2fdec84e522adec8ee2dcda0d9fff9dbea52ac4a65f" + ), clientTimestamp: Date(timeIntervalSinceReferenceDate: 656_187_908.969623) ) } @@ -230,14 +247,16 @@ extension InitiateAuthOutput { "SALT": "a", "USER_ID_FOR_SRP": "royji2", "SRP_B": "a", - "USERNAME": "a"] + "USERNAME": "a" + ] static let invalidChalengeParamsForException: [String: String] = [ "SALT": "a", "SECRET_BLOCK": "", "USER_ID_FOR_SRP": "royji2", "SRP_B": "za", - "USERNAME": "a"] + "USERNAME": "a" + ] static let invalidChalengeParamsNoSRPB: [String: String] = [ "SALT": "a", @@ -267,7 +286,8 @@ extension InitiateAuthOutput { "bA7jMS0q3ld4sAAw8YfRNf0KggdA9Iolz9qdI/8xVLTLWsdvv1NA1JIPb8lPtlkqTlFYDp" + "inYbJk4W/1BOS85TSWPBwadRpVhEIDeH42hIgnvEPA==", "USER_ID_FOR_SRP": "royji2", - "USERNAME": "a"] + "USERNAME": "a" + ] static let validChalengeParams: [String: String] = [ "SALT": "79b00c90ebb6221ab4cad530f41441ed", @@ -308,7 +328,8 @@ extension InitiateAuthOutput { "96eec45283edfc75060a4bd0dc31544eb424cd25939626c014199ad433079b26a0ecab" + "129c2eef61d22994ad70c96d286e6e8c1abc65e7060ba69cb0d8c4a31cc08cc7d76ef9" + "2f757b2a34e7ae236aadbced9bb7a4a06e67da3a084833e0f3a0b903af0a74816031", - "USERNAME": "royji2"] + "USERNAME": "royji2" + ] static let validSMSChallengeParams: [String: String] = [ "CODE_DELIVERY_DELIVERY_MEDIUM": "SMS", diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateResolverTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateResolverTests.swift index f660e7e837..32f135b3ee 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateResolverTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateResolverTests.swift @@ -12,9 +12,10 @@ import XCTest typealias SignOutStateSequence = StateSequence extension SignOutStateSequence { - init(oldState: MyState, - event: MyEvent, - expected: MyState + init( + oldState: MyState, + event: MyEvent, + expected: MyState ) { self.resolver = SignOutState.Resolver().logging().eraseToAnyResolver() self.oldState = oldState @@ -29,25 +30,31 @@ class SignOutStateResolverTests: XCTestCase { SignOutStateSequence( oldState: .notStarted, event: SignOutEvent(eventType: .signOutGlobally(.testData)), - expected: .signingOutGlobally), + expected: .signingOutGlobally + ), SignOutStateSequence( oldState: .notStarted, event: SignOutEvent(eventType: .revokeToken(.testData)), - expected: .revokingToken), + expected: .revokingToken + ), SignOutStateSequence( oldState: .signingOutGlobally, event: SignOutEvent(eventType: .revokeToken(.testData)), - expected: .revokingToken), + expected: .revokingToken + ), SignOutStateSequence( oldState: .signingOutGlobally, event: SignOutEvent(eventType: .globalSignOutError( .testData, - globalSignOutError: .init(accessToken: "", error: .service("", "", nil)))), - expected: .buildingRevokeTokenError), + globalSignOutError: .init(accessToken: "", error: .service("", "", nil)) + )), + expected: .buildingRevokeTokenError + ), SignOutStateSequence( oldState: .revokingToken, event: SignOutEvent(eventType: .signOutLocally(.testData)), - expected: .signingOutLocally(.testData)) + expected: .signingOutLocally(.testData) + ) ] for sequence in validSequences { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateTestData.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateTestData.swift index 2036eb387f..fff84bb7b1 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateTestData.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateTestData.swift @@ -7,8 +7,8 @@ import Foundation -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +@testable import AWSCognitoAuthPlugin // MARK: - Test Data diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/ConfirmSignUpInputTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/ConfirmSignUpInputTests.swift index 406b48a76c..2b790c6c38 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/ConfirmSignUpInputTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/ConfirmSignUpInputTests.swift @@ -16,15 +16,18 @@ class ConfirmSignUpInputTests: XCTestCase { func testConfirmSignUpInputWithClientSecretAndAsfDeviceId() async throws { let username = "jeff" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let confirmSignUpInput = await ConfirmSignUpInput( username: username, @@ -32,7 +35,8 @@ class ConfirmSignUpInputTests: XCTestCase { clientMetadata: [:], asfDeviceId: "asdfDeviceId", forceAliasCreation: nil, - environment: environment) + environment: environment + ) XCTAssertNotNil(confirmSignUpInput.secretHash) XCTAssertNotNil(confirmSignUpInput.userContextData) @@ -41,15 +45,18 @@ class ConfirmSignUpInputTests: XCTestCase { func testConfirmSignUpInputWithoutClientSecretAndAsfDeviceId() async throws { let username = "jeff" - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: nil) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: nil + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let confirmSignUpInput = await ConfirmSignUpInput( username: username, @@ -57,7 +64,8 @@ class ConfirmSignUpInputTests: XCTestCase { clientMetadata: [:], asfDeviceId: nil, forceAliasCreation: nil, - environment: environment) + environment: environment + ) XCTAssertNil(confirmSignUpInput.secretHash) XCTAssertNil(confirmSignUpInput.userContextData) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/RespondToAuthInputTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/RespondToAuthInputTests.swift index 4bcbe80f42..698dd2a06b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/RespondToAuthInputTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/RespondToAuthInputTests.swift @@ -16,15 +16,18 @@ class RespondToAuthInputTests: XCTestCase { func testDevicePasswordVerifierInput() async throws { let username = "jeff" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let respondToAuthChallengeInput = await RespondToAuthChallengeInput.devicePasswordVerifier( username: username, @@ -34,7 +37,8 @@ class RespondToAuthInputTests: XCTestCase { signature: "signature", deviceMetadata: .metadata(.init(deviceKey: "", deviceGroupKey: "")), asfDeviceId: "asfDeviceId", - environment: environment) + environment: environment + ) XCTAssertNotNil(respondToAuthChallengeInput.challengeResponses?["SECRET_HASH"]) XCTAssertNotNil(respondToAuthChallengeInput.userContextData) @@ -43,15 +47,18 @@ class RespondToAuthInputTests: XCTestCase { func testVerifyChallengeInput() async throws { let username = "jeff" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let respondToAuthChallengeInput = await RespondToAuthChallengeInput.verifyChallenge( username: username, @@ -63,7 +70,8 @@ class RespondToAuthInputTests: XCTestCase { asfDeviceId: "asfDeviceId", attributes: [:], deviceMetadata: .metadata(.init(deviceKey: "", deviceGroupKey: "")), - environment: environment) + environment: environment + ) XCTAssertEqual(respondToAuthChallengeInput.challengeResponses?["CODE"], "1234") XCTAssertNotNil(respondToAuthChallengeInput.userContextData) @@ -72,15 +80,18 @@ class RespondToAuthInputTests: XCTestCase { func testPasswordVerifierInput() async throws { let username = "jeff" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let respondToAuthChallengeInput = await RespondToAuthChallengeInput.passwordVerifier( username: username, @@ -91,7 +102,8 @@ class RespondToAuthInputTests: XCTestCase { clientMetadata: ["test": "test"], deviceMetadata: .metadata(.init(deviceKey: "", deviceGroupKey: "")), asfDeviceId: "asfDeviceId", - environment: environment) + environment: environment + ) XCTAssertNotNil(respondToAuthChallengeInput.challengeResponses?["PASSWORD_CLAIM_SECRET_BLOCK"]) XCTAssertNotNil(respondToAuthChallengeInput.challengeResponses?["PASSWORD_CLAIM_SIGNATURE"]) @@ -101,15 +113,18 @@ class RespondToAuthInputTests: XCTestCase { func testDeviceSrpInput() async throws { let username = "jeff" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let respondToAuthChallengeInput = await RespondToAuthChallengeInput.deviceSRP( username: username, @@ -117,7 +132,8 @@ class RespondToAuthInputTests: XCTestCase { deviceMetadata: .metadata(.init(deviceKey: "", deviceGroupKey: "")), asfDeviceId: "asfDeviceId", session: "session", - publicHexValue: "somehexValue") + publicHexValue: "somehexValue" + ) XCTAssertEqual(respondToAuthChallengeInput.challengeResponses?["SRP_A"], "somehexValue") XCTAssertNotNil(respondToAuthChallengeInput.userContextData) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/SignUpInputTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/SignUpInputTests.swift index 2e834c6d32..7fbfdce705 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/SignUpInputTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/SignUpInputTests.swift @@ -17,22 +17,27 @@ class SignUpInputTests: XCTestCase { let username = "jeff" let password = "a2z" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) - let input = await SignUpInput(username: username, - password: password, - clientMetadata: [:], - validationData: [:], - attributes: [:], - asfDeviceId: "asFDeviceId", - environment: environment) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) + let input = await SignUpInput( + username: username, + password: password, + clientMetadata: [:], + validationData: [:], + attributes: [:], + asfDeviceId: "asFDeviceId", + environment: environment + ) XCTAssertNotNil(input.secretHash) XCTAssertNotNil(input.userContextData) @@ -42,22 +47,27 @@ class SignUpInputTests: XCTestCase { let username = "jeff" let password = "a2z" - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: nil) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: nil + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) - let input = await SignUpInput(username: username, - password: password, - clientMetadata: [:], - validationData: [:], - attributes: [:], - asfDeviceId: nil, - environment: environment) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) + let input = await SignUpInput( + username: username, + password: password, + clientMetadata: [:], + validationData: [:], + attributes: [:], + asfDeviceId: nil, + environment: environment + ) XCTAssertNil(input.secretHash) XCTAssertNil(input.userContextData) @@ -68,22 +78,27 @@ class SignUpInputTests: XCTestCase { let username = "jeff" let password = "a2z" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) - let input = await SignUpInput(username: username, - password: password, - clientMetadata: [:], - validationData: [:], - attributes: [:], - asfDeviceId: "asFDeviceId", - environment: environment) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) + let input = await SignUpInput( + username: username, + password: password, + clientMetadata: [:], + validationData: [:], + attributes: [:], + asfDeviceId: "asFDeviceId", + environment: environment + ) XCTAssertNotNil(input.validationData) XCTAssertNotNil(input.userContextData) @@ -98,10 +113,12 @@ class SignUpInputTests: XCTestCase { } #endif - func assertHasAttributeType(name: String, - validationData: [CognitoIdentityProviderClientTypes.AttributeType], - file: StaticString = #file, line: UInt = #line) - { + func assertHasAttributeType( + name: String, + validationData: [CognitoIdentityProviderClientTypes.AttributeType], + file: StaticString = #file, + line: UInt = #line + ) { let attribute = validationData.first(where: { $0.name == name }) XCTAssertNotNil(attribute, "Attribute not found for name: \(name)", file: file, line: line) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/SRPTests/SRPClientTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/SRPTests/SRPClientTests.swift index 4da92d4fe7..6ec9655cd2 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/SRPTests/SRPClientTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/SRPTests/SRPClientTests.swift @@ -70,8 +70,10 @@ class SRPClientTests: XCTestCase { "05b324629b160935d15cdb18d1f8dfe55f2d84afaef0f761bec33eba21" + "78b426a7bf2985" - let u = try srpClientType().calculateUHexValue(clientPublicKeyHexValue: clientPublicKey, - serverPublicKeyHexValue: serverPublicKey) + let u = try srpClientType().calculateUHexValue( + clientPublicKeyHexValue: clientPublicKey, + serverPublicKeyHexValue: serverPublicKey + ) XCTAssertEqual(u, "c3a1193f8683863acc9c1d9532105c589696e3347b860080853435906b61342a".uppercased()) } @@ -108,8 +110,10 @@ class SRPClientTests: XCTestCase { "36d9644b1bf9a84deb0f8c99c208d4aa4095c8f7e95ecdba0e651562d0" + "d80ac6272a0785" - let u = try srpClientType().calculateUHexValue(clientPublicKeyHexValue: clientPublicKey, - serverPublicKeyHexValue: serverPublicKey) + let u = try srpClientType().calculateUHexValue( + clientPublicKeyHexValue: clientPublicKey, + serverPublicKeyHexValue: serverPublicKey + ) XCTAssertEqual(u, "bf078ed83130247cc16c6e07d646e39dda9362f5b1c6eb4f6368723b55f728e7".uppercased()) } @@ -144,8 +148,10 @@ class SRPClientTests: XCTestCase { "35aaab2db72fe322cd6d1cdd2eb8e8620726a6781a2890830c1f597c50798" + "8525156cbc17f39621a8e1963fa7cb6ac048" - let u = try srpClientType().calculateUHexValue(clientPublicKeyHexValue: clientPublicKey, - serverPublicKeyHexValue: serverPublicKey) + let u = try srpClientType().calculateUHexValue( + clientPublicKeyHexValue: clientPublicKey, + serverPublicKeyHexValue: serverPublicKey + ) XCTAssertEqual(u, "4aa339a24ed483e6058e9e7afdc001409a4586af2f08ff009e4c3f8d12a0bce4".uppercased()) } @@ -205,12 +211,14 @@ class SRPClientTests: XCTestCase { "3edf54d1f2b24e4afcd40d69888" let srpClient = try srpClient(NHexValue: validNHexValue, gHexValue: "2") - let S = try srpClient.calculateSharedSecret(username: "VEUHc88gProyji7", - password: "dummy123@", - saltHexValue: "8bb7dcf905f418bf27b6623aa4d2f58f", - clientPrivateKeyHexValue: clientPrivateKey, - clientPublicKeyHexValue: clientPublicKey, - serverPublicKeyHexValue: serverPublicKey) + let S = try srpClient.calculateSharedSecret( + username: "VEUHc88gProyji7", + password: "dummy123@", + saltHexValue: "8bb7dcf905f418bf27b6623aa4d2f58f", + clientPrivateKeyHexValue: clientPrivateKey, + clientPublicKeyHexValue: clientPublicKey, + serverPublicKeyHexValue: serverPublicKey + ) XCTAssertEqual(S, expectedSharedSecret.uppercased()) } @@ -267,12 +275,14 @@ class SRPClientTests: XCTestCase { "81ec6baefe0b389ee7248a7d58fdf523c1f1ebc3" let srpClient = try srpClient(NHexValue: validNHexValue, gHexValue: "2") - let S = try srpClient.calculateSharedSecret(username: "baTBpG5tZroyji7", - password: "dummy123@", - saltHexValue: "d1c1181916afc59efe7eb71674d627c", - clientPrivateKeyHexValue: clientPrivateKey, - clientPublicKeyHexValue: clientPublicKey, - serverPublicKeyHexValue: serverPublicKey) + let S = try srpClient.calculateSharedSecret( + username: "baTBpG5tZroyji7", + password: "dummy123@", + saltHexValue: "d1c1181916afc59efe7eb71674d627c", + clientPrivateKeyHexValue: clientPrivateKey, + clientPublicKeyHexValue: clientPublicKey, + serverPublicKeyHexValue: serverPublicKey + ) XCTAssertEqual(S, expectedSharedSecret.uppercased()) } @@ -322,7 +332,8 @@ class SRPClientTests: XCTestCase { saltHexValue: "8bb7dcf905f418bf27b6623aa4d2f58f", clientPrivateKeyHexValue: clientPrivateKey, clientPublicKeyHexValue: clientPublicKey, - serverPublicKeyHexValue: illegalServerPublicKey) + serverPublicKeyHexValue: illegalServerPublicKey + ) ) { error in guard let srpError = error as? SRPError else { XCTFail("Should return SRPError") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/AWSAuthCognitoSessionTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/AWSAuthCognitoSessionTests.swift index 43db976492..b375fa3664 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/AWSAuthCognitoSessionTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/AWSAuthCognitoSessionTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin -import AWSPluginsCore import Amplify +import AWSPluginsCore import XCTest +@testable import AWSCognitoAuthPlugin class AWSAuthCognitoSessionTests: XCTestCase { @@ -24,14 +24,18 @@ class AWSAuthCognitoSessionTests: XCTestCase { "exp": String(Date(timeIntervalSinceNow: 121).timeIntervalSince1970) ] let error = AuthError.unknown("", nil) - let tokens = AWSCognitoUserPoolTokens(idToken: CognitoAuthTestHelper.buildToken(for: tokenData), - accessToken: CognitoAuthTestHelper.buildToken(for: tokenData), - refreshToken: "refreshToken") - - let session = AWSAuthCognitoSession(isSignedIn: true, - identityIdResult: .failure(error), - awsCredentialsResult: .failure(error), - cognitoTokensResult: .success(tokens)) + let tokens = AWSCognitoUserPoolTokens( + idToken: CognitoAuthTestHelper.buildToken(for: tokenData), + accessToken: CognitoAuthTestHelper.buildToken(for: tokenData), + refreshToken: "refreshToken" + ) + + let session = AWSAuthCognitoSession( + isSignedIn: true, + identityIdResult: .failure(error), + awsCredentialsResult: .failure(error), + cognitoTokensResult: .success(tokens) + ) let cognitoTokens = try! session.getCognitoTokens().get() as! AWSCognitoUserPoolTokens XCTAssertFalse(cognitoTokens.doesExpire(in: 120)) XCTAssertTrue(cognitoTokens.doesExpire(in: 122)) @@ -50,14 +54,18 @@ class AWSAuthCognitoSessionTests: XCTestCase { "exp": String(Date(timeIntervalSinceNow: 1).timeIntervalSince1970) ] let error = AuthError.unknown("", nil) - let tokens = AWSCognitoUserPoolTokens(idToken: CognitoAuthTestHelper.buildToken(for: tokenData), - accessToken: CognitoAuthTestHelper.buildToken(for: tokenData), - refreshToken: "refreshToken") + let tokens = AWSCognitoUserPoolTokens( + idToken: CognitoAuthTestHelper.buildToken(for: tokenData), + accessToken: CognitoAuthTestHelper.buildToken(for: tokenData), + refreshToken: "refreshToken" + ) - let session = AWSAuthCognitoSession(isSignedIn: true, - identityIdResult: .failure(error), - awsCredentialsResult: .failure(error), - cognitoTokensResult: .success(tokens)) + let session = AWSAuthCognitoSession( + isSignedIn: true, + identityIdResult: .failure(error), + awsCredentialsResult: .failure(error), + cognitoTokensResult: .success(tokens) + ) let cognitoTokens = try! session.getCognitoTokens().get() as! AWSCognitoUserPoolTokens XCTAssertFalse(cognitoTokens.doesExpire()) @@ -120,14 +128,15 @@ class AWSAuthCognitoSessionTests: XCTestCase { ) guard case .failure(let error) = session.getUserSub(), - case .unknown(let errorDescription, _) = error else { + case .unknown(let errorDescription, _) = error + else { XCTFail("Expected AuthError.unknown") return } XCTAssertEqual(errorDescription, "Could not retreive user sub from the fetched Cognito tokens.") } - + /// Given: An AWSAuthCognitoSession that is signed out /// When: getUserSub is invoked /// Then: A .failure with AuthError.signedOut error is returned @@ -141,7 +150,8 @@ class AWSAuthCognitoSessionTests: XCTestCase { ) guard case .failure(let error) = session.getUserSub(), - case .signedOut(let errorDescription, let recoverySuggestion, _) = error else { + case .signedOut(let errorDescription, let recoverySuggestion, _) = error + else { XCTFail("Expected AuthError.signedOut") return } @@ -149,7 +159,7 @@ class AWSAuthCognitoSessionTests: XCTestCase { XCTAssertEqual(errorDescription, AuthPluginErrorConstants.userSubSignOutError.errorDescription) XCTAssertEqual(recoverySuggestion, AuthPluginErrorConstants.userSubSignOutError.recoverySuggestion) } - + /// Given: An AWSAuthCognitoSession that has a service error /// When: getUserSub is invoked /// Then: A .failure with AuthError.signedOut error is returned @@ -169,7 +179,7 @@ class AWSAuthCognitoSessionTests: XCTestCase { XCTAssertEqual(error, serviceError) } - + /// Given: An AuthAWSCognitoCredentials and an AWSCognitoUserPoolTokens instance /// When: Two AWSAuthCognitoSession are created from the same values /// Then: The two AWSAuthCognitoSession are considered equal @@ -211,7 +221,7 @@ class AWSAuthCognitoSessionTests: XCTestCase { XCTAssertEqual(session1, session2) XCTAssertEqual(session1.debugDictionary.count, session2.debugDictionary.count) - for key in session1.debugDictionary.keys where (key != "AWS Credentials" && key != "cognitoTokens") { + for key in session1.debugDictionary.keys where key != "AWS Credentials" && key != "cognitoTokens" { XCTAssertEqual(session1.debugDictionary[key] as? String, session2.debugDictionary[key] as? String) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CognitoAuthTestHelper.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CognitoAuthTestHelper.swift index b7fc80f7f4..2113047534 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CognitoAuthTestHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CognitoAuthTestHelper.swift @@ -8,7 +8,7 @@ import CryptoKit import Foundation -struct CognitoAuthTestHelper { +enum CognitoAuthTestHelper { /// Helper to build a JWT Token static func buildToken(for payload: [String: String]) -> String { @@ -38,7 +38,7 @@ struct CognitoAuthTestHelper { } } -fileprivate extension Data { +private extension Data { func urlSafeBase64EncodedString() -> String { return base64EncodedString() .replacingOccurrences(of: "+", with: "-") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/ConfigurationHelperTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/ConfigurationHelperTests.swift index ee6ea93a1e..e59541cc1f 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/ConfigurationHelperTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/ConfigurationHelperTests.swift @@ -23,7 +23,8 @@ final class ConfigurationHelperTests: XCTestCase { userVerificationTypes: [.email], unauthenticatedIdentitiesEnabled: true, mfaConfiguration: nil, - mfaMethods: nil) + mfaMethods: nil + ) guard let result = ConfigurationHelper.parseUserPoolData(config) else { XCTFail("Expected to parse UserPoolData into object") @@ -45,19 +46,23 @@ final class ConfigurationHelperTests: XCTestCase { awsRegion: "us-east-1", userPoolId: "poolId", userPoolClientId: "clientId", - oauth: AmplifyOutputsData.Auth.OAuth(identityProviders: ["provider1", "provider2"], - domain: "domain", - scopes: ["scope1", "scope2"], - redirectSignInUri: ["redirect1", "redirect2"], - redirectSignOutUri: ["signOut1", "signOut2"], - responseType: "responseType")) + oauth: AmplifyOutputsData.Auth.OAuth( + identityProviders: ["provider1", "provider2"], + domain: "domain", + scopes: ["scope1", "scope2"], + redirectSignInUri: ["redirect1", "redirect2"], + redirectSignOutUri: ["signOut1", "signOut2"], + responseType: "responseType" + ) + ) guard let config = ConfigurationHelper.parseUserPoolData(config), - let hostedUIConfig = config.hostedUIConfig else { + let hostedUIConfig = config.hostedUIConfig + else { XCTFail("Expected to parse UserPoolData into object") return } - + XCTAssertEqual(hostedUIConfig.clientId, "clientId") XCTAssertNil(hostedUIConfig.clientSecret, "Client secret should be nil as its not supported in Gen2") XCTAssertEqual(hostedUIConfig.oauth.scopes, ["scope1", "scope2"]) @@ -72,14 +77,18 @@ final class ConfigurationHelperTests: XCTestCase { awsRegion: "us-east-1", userPoolId: "poolId", userPoolClientId: "clientId", - passwordPolicy: .init(minLength: 5, - requireNumbers: true, - requireLowercase: true, - requireUppercase: true, - requireSymbols: true)) + passwordPolicy: .init( + minLength: 5, + requireNumbers: true, + requireLowercase: true, + requireUppercase: true, + requireSymbols: true + ) + ) guard let config = ConfigurationHelper.parseUserPoolData(config), - let result = config.passwordProtectionSettings else { + let result = config.passwordProtectionSettings + else { XCTFail("Expected to parse UserPoolData into object") return } @@ -97,7 +106,8 @@ final class ConfigurationHelperTests: XCTestCase { awsRegion: "us-east-1", userPoolId: "poolId", userPoolClientId: "clientId", - usernameAttributes: [.email, .phoneNumber]) + usernameAttributes: [.email, .phoneNumber] + ) guard let result = ConfigurationHelper.parseUserPoolData(config) else { XCTFail("Expected to parse UserPoolData into object") @@ -126,7 +136,8 @@ final class ConfigurationHelperTests: XCTestCase { .preferredUsername, .profile, .website - ]) + ] + ) guard let result = ConfigurationHelper.parseUserPoolData(config) else { XCTFail("Expected to parse UserPoolData into object") @@ -161,7 +172,8 @@ final class ConfigurationHelperTests: XCTestCase { .sub, .updatedAt, .zoneinfo - ]) + ] + ) guard let result = ConfigurationHelper.parseUserPoolData(config) else { XCTFail("Expected to parse UserPoolData into object") @@ -177,7 +189,8 @@ final class ConfigurationHelperTests: XCTestCase { awsRegion: "us-east-1", userPoolId: "poolId", userPoolClientId: "clientId", - userVerificationTypes: [.phoneNumber, .email]) + userVerificationTypes: [.phoneNumber, .email] + ) guard let result = ConfigurationHelper.parseUserPoolData(config) else { XCTFail("Expected to parse UserPoolData into object") @@ -195,14 +208,15 @@ final class ConfigurationHelperTests: XCTestCase { let config = AuthConfiguration .userPools(.init( poolId: "", - clientId: "", + clientId: "", region: "", passwordProtectionSettings: .init(from: .init( minLength: 8, requireNumbers: true, requireLowercase: true, requireUppercase: true, - requireSymbols: true)), + requireSymbols: true + )), usernameAttributes: [ .init(from: .email), .init(from: .phoneNumber) @@ -214,7 +228,8 @@ final class ConfigurationHelperTests: XCTestCase { verificationMechanisms: [ .init(from: .email), .init(from: .phoneNumber) - ])) + ] + )) let json = ConfigurationHelper.createUserPoolJsonConfiguration(config) guard let authConfig = json.Auth?.Default else { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/CustomEndpoint+AuthConfigurationJSONTestCase.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/CustomEndpoint+AuthConfigurationJSONTestCase.swift index 62c3e537f2..7cab8ec037 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/CustomEndpoint+AuthConfigurationJSONTestCase.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/CustomEndpoint+AuthConfigurationJSONTestCase.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -@testable import AWSCognitoAuthPlugin import Amplify +import Foundation import XCTest +@testable import AWSCognitoAuthPlugin class CustomEndpoint_AuthConfigurationJSONTestCase: XCTestCase { /// Given: The `awsCognitoAuthPlugin` portion of an `amplifyconfiguration.json` diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolving+ValidationStepTestCase.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolving+ValidationStepTestCase.swift index 600609dc2d..32088717c2 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolving+ValidationStepTestCase.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolving+ValidationStepTestCase.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import XCTest @testable import AWSCognitoAuthPlugin -import Amplify class EndpointResolving_ValidationStepTestCase: XCTestCase { // MARK: EndpointResolving.ValidationStep.schemeIsEmpty() diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolvingTestCase.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolvingTestCase.swift index d460299d87..8ca7741c76 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolvingTestCase.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolvingTestCase.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import XCTest @testable import AWSCognitoAuthPlugin -import Amplify class EndpointResolvingTestCase: XCTestCase { /// Given: A String representation of a URL. diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/DefaultConfig.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/DefaultConfig.swift index 13e5a8781e..05fe361998 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/DefaultConfig.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/DefaultConfig.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -@testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider +import AWSPluginsCore import ClientRuntime +import Foundation @testable import Amplify -import AWSPluginsCore +@testable import AWSCognitoAuthPlugin enum Defaults { @@ -72,17 +72,19 @@ enum Defaults { static func makeUserPoolAnalytics() -> UserPoolAnalyticsBehavior { MockAnalyticsHandler() } - + static func makeIdentity() throws -> CognitoIdentityBehavior { let getId: MockIdentity.MockGetIdResponse = { _ in return .init(identityId: "mockIdentityId") } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } return MockIdentity(mockGetIdResponse: getId, mockGetCredentialsResponse: getCredentials) @@ -90,17 +92,21 @@ enum Defaults { static func makeDefaultUserPoolConfigData(withHostedUI: HostedUIConfigurationData? = nil) -> UserPoolConfigurationData { - UserPoolConfigurationData(poolId: userPoolId, - clientId: appClientId, - region: regionString, - clientSecret: appClientSecret, - pinpointAppId: "", - hostedUIConfig: withHostedUI) + UserPoolConfigurationData( + poolId: userPoolId, + clientId: appClientId, + region: regionString, + clientSecret: appClientSecret, + pinpointAppId: "", + hostedUIConfig: withHostedUI + ) } static func makeIdentityConfigData() -> IdentityPoolConfigurationData { - IdentityPoolConfigurationData(poolId: identityPoolId, - region: regionString) + IdentityPoolConfigurationData( + poolId: identityPoolId, + region: regionString + ) } static func makeDefaultAuthConfigData(withHostedUI: HostedUIConfigurationData? = nil) -> AuthConfiguration { @@ -148,13 +154,17 @@ enum Defaults { userPoolConfiguration: userPoolConfigData, cognitoUserPoolFactory: userPoolFactory, cognitoUserPoolASFFactory: makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: makeUserPoolAnalytics) - let authenticationEnvironment = BasicAuthenticationEnvironment(srpSignInEnvironment: srpSignInEnvironment, - userPoolEnvironment: userPoolEnvironment, - hostedUIEnvironment: hostedUIEnvironment) + cognitoUserPoolAnalyticsHandlerFactory: makeUserPoolAnalytics + ) + let authenticationEnvironment = BasicAuthenticationEnvironment( + srpSignInEnvironment: srpSignInEnvironment, + userPoolEnvironment: userPoolEnvironment, + hostedUIEnvironment: hostedUIEnvironment + ) let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: identityPoolFactory) + cognitoIdentityFactory: identityPoolFactory + ) let authEnv = AuthEnvironment( configuration: Defaults.makeDefaultAuthConfigData(), userPoolConfigData: userPoolConfigData, @@ -172,38 +182,53 @@ enum Defaults { initialState: AuthState? = nil, identityPoolFactory: @escaping () throws -> CognitoIdentityBehavior = makeIdentity, userPoolFactory: @escaping () throws -> CognitoUserPoolBehavior = makeDefaultUserPool, - hostedUIEnvironment: HostedUIEnvironment? = nil) -> + hostedUIEnvironment: HostedUIEnvironment? = nil + ) -> AuthStateMachine { - let environment = makeDefaultAuthEnvironment(identityPoolFactory: identityPoolFactory, - userPoolFactory: userPoolFactory, - hostedUIEnvironment: hostedUIEnvironment) - return AuthStateMachine(resolver: AuthState.Resolver(), - environment: environment, - initialState: initialState) + let environment = makeDefaultAuthEnvironment( + identityPoolFactory: identityPoolFactory, + userPoolFactory: userPoolFactory, + hostedUIEnvironment: hostedUIEnvironment + ) + return AuthStateMachine( + resolver: AuthState.Resolver(), + environment: environment, + initialState: initialState + ) } static func makeDefaultCredentialStateMachine() -> CredentialStoreStateMachine { - return CredentialStoreStateMachine(resolver: CredentialStoreState.Resolver(), - environment: makeDefaultCredentialStoreEnvironment(), - initialState: .idle) + return CredentialStoreStateMachine( + resolver: CredentialStoreState.Resolver(), + environment: makeDefaultCredentialStoreEnvironment(), + initialState: .idle + ) } - static func authStateMachineWith(environment: AuthEnvironment = makeDefaultAuthEnvironment(), - initialState: AuthState? = nil) + static func authStateMachineWith( + environment: AuthEnvironment = makeDefaultAuthEnvironment(), + initialState: AuthState? = nil + ) -> AuthStateMachine { - return AuthStateMachine(resolver: AuthState.Resolver(), - environment: environment, - initialState: initialState) + return AuthStateMachine( + resolver: AuthState.Resolver(), + environment: environment, + initialState: initialState + ) } - static func makeAuthState(tokens: AWSCognitoUserPoolTokens, - signedInDate: Date = Date(), - signInMethod: SignInMethod = .apiBased(.userSRP)) -> AuthState { + static func makeAuthState( + tokens: AWSCognitoUserPoolTokens, + signedInDate: Date = Date(), + signInMethod: SignInMethod = .apiBased(.userSRP) + ) -> AuthState { - let signedInData = SignedInData(signedInDate: signedInDate, - signInMethod: signInMethod, - cognitoUserPoolTokens: tokens) + let signedInData = SignedInData( + signedInDate: signedInDate, + signInMethod: signInMethod, + cognitoUserPoolTokens: tokens + ) let authNState: AuthenticationState = .signedIn(signedInData) let authZState: AuthorizationState = .configured @@ -219,10 +244,12 @@ enum Defaults { ) } - static func makeCognitoUserPoolTokens(idToken: String = "XX", - accessToken: String = "", - refreshToken: String = "XX", - expiresIn: Int = 300) -> AWSCognitoUserPoolTokens { + static func makeCognitoUserPoolTokens( + idToken: String = "XX", + accessToken: String = "", + refreshToken: String = "XX", + expiresIn: Int = 300 + ) -> AWSCognitoUserPoolTokens { AWSCognitoUserPoolTokens(idToken: idToken, accessToken: accessToken, refreshToken: refreshToken, expiresIn: expiresIn) } @@ -246,8 +273,7 @@ struct MockCredentialStoreOperationClient: CredentialStoreStateBehavior { let device = try mockAmplifyStore.retrieveASFDevice(for: username) return .asfDeviceId(device, username) } - } - catch KeychainStoreError.itemNotFound { + } catch KeychainStoreError.itemNotFound { switch type { case .amplifyCredentials: return .amplifyCredentials(.testData) @@ -255,12 +281,12 @@ struct MockCredentialStoreOperationClient: CredentialStoreStateBehavior { return .deviceMetadata(.metadata(.init( deviceKey: "key", deviceGroupKey: "key", - deviceSecret: "secret")), username) + deviceSecret: "secret" + )), username) case .asfDeviceId(username: let username): return .asfDeviceId("id", username) } - } - catch { + } catch { fatalError() } } @@ -292,7 +318,8 @@ class MockAmplifyStore: AmplifyAuthCredentialStoreBehavior { func retrieveCredential() throws -> AmplifyCredentials { guard let data = Self.dict.getValue(forKey: credentialsKey), - let cred = (try? JSONDecoder().decode(AmplifyCredentials.self, from: data)) else { + let cred = (try? JSONDecoder().decode(AmplifyCredentials.self, from: data)) + else { throw KeychainStoreError.itemNotFound } return cred @@ -313,7 +340,8 @@ class MockAmplifyStore: AmplifyAuthCredentialStoreBehavior { func retrieveDevice(for username: String) throws -> DeviceMetadata { guard let data = Self.dict.getValue(forKey: username), - let device = (try? JSONDecoder().decode(DeviceMetadata.self, from: data)) else { + let device = (try? JSONDecoder().decode(DeviceMetadata.self, from: data)) + else { throw KeychainStoreError.itemNotFound } return device @@ -331,7 +359,8 @@ class MockAmplifyStore: AmplifyAuthCredentialStoreBehavior { func retrieveASFDevice(for username: String) throws -> String { guard let data = Self.dict.getValue(forKey: username), - let device = (try? JSONDecoder().decode(String.self, from: data)) else { + let device = (try? JSONDecoder().decode(String.self, from: data)) + else { throw KeychainStoreError.itemNotFound } return device @@ -370,10 +399,12 @@ struct MockLegacyStore: KeychainStoreBehavior { } struct MockASF: AdvancedSecurityBehavior { - func userContextData(for username: String, - deviceInfo: ASFDeviceBehavior, - appInfo: ASFAppInfoBehavior, - configuration: UserPoolConfigurationData) throws -> String { + func userContextData( + for username: String, + deviceInfo: ASFDeviceBehavior, + appInfo: ASFAppInfoBehavior, + configuration: UserPoolConfigurationData + ) throws -> String { return "" } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIASWebAuthenticationSessionTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIASWebAuthenticationSessionTests.swift index f8e00626fb..da49780584 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIASWebAuthenticationSessionTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIASWebAuthenticationSessionTests.swift @@ -8,19 +8,19 @@ #if os(iOS) || os(macOS) || os(visionOS) import Amplify import AuthenticationServices -@testable import AWSCognitoAuthPlugin import XCTest +@testable import AWSCognitoAuthPlugin class HostedUIASWebAuthenticationSessionTests: XCTestCase { private var session: HostedUIASWebAuthenticationSession! private var factory: ASWebAuthenticationSessionFactory! - + override func setUp() { session = HostedUIASWebAuthenticationSession() factory = ASWebAuthenticationSessionFactory() session.authenticationSessionFactory = factory.createSession(url:callbackURLScheme:completionHandler:) } - + override func tearDown() { session = nil factory = nil @@ -36,7 +36,7 @@ class HostedUIASWebAuthenticationSessionTests: XCTestCase { XCTAssertEqual(queryItems.first?.name, "name") XCTAssertEqual(queryItems.first?.value, "value") } - + /// Given: A HostedUIASWebAuthenticationSession /// When: showHostedUI is invoked and the session factory returns a URL without query items /// Then: An empty array should be returned @@ -45,7 +45,7 @@ class HostedUIASWebAuthenticationSessionTests: XCTestCase { let queryItems = try await session.showHostedUI() XCTAssertTrue(queryItems.isEmpty) } - + /// Given: A HostedUIASWebAuthenticationSession /// When: showHostedUI is invoked and the session factory returns a URL with query items representing errors /// Then: A HostedUIError.serviceMessage should be returned @@ -68,7 +68,7 @@ class HostedUIASWebAuthenticationSessionTests: XCTestCase { XCTFail("Expected HostedUIError.serviceMessage, got \(error)") } } - + /// Given: A HostedUIASWebAuthenticationSession /// When: showHostedUI is invoked and the session factory returns ASWebAuthenticationSessionErrors /// Then: A HostedUIError corresponding to the error code should be returned @@ -98,7 +98,7 @@ class HostedUIASWebAuthenticationSessionTests: XCTestCase { } } } - + /// Given: A HostedUIASWebAuthenticationSession /// When: showHostedUI is invoked and the session factory returns an error /// Then: A HostedUIError.unknown should be returned @@ -170,7 +170,7 @@ class MockASWebAuthenticationSession: ASWebAuthenticationSession { completionHandler: completionHandler ) } - + var mockedURL: URL? = nil var mockedError: Error? = nil override func start() -> Bool { @@ -190,13 +190,14 @@ extension HostedUIASWebAuthenticationSession { url: URL(string: "https://test.com")!, callbackScheme: "https", inPrivate: false, - presentationAnchor: nil) + presentationAnchor: nil + ) } } #else -@testable import AWSCognitoAuthPlugin import XCTest +@testable import AWSCognitoAuthPlugin class HostedUIASWebAuthenticationSessionTests: XCTestCase { func testShowHostedUI_shouldThrowServiceError() async { @@ -206,7 +207,8 @@ class HostedUIASWebAuthenticationSessionTests: XCTestCase { url: URL(string: "https://test.com")!, callbackScheme: "https", inPrivate: false, - presentationAnchor: nil) + presentationAnchor: nil + ) } catch let error as HostedUIError { if case .serviceMessage(let message) = error { XCTAssertEqual(message, "HostedUI is only available in iOS, macOS and visionOS") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIRequestHelperTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIRequestHelperTests.swift index 69f8ae19a0..e62234191f 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIRequestHelperTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIRequestHelperTests.swift @@ -7,9 +7,9 @@ import Foundation -@testable import AWSCognitoAuthPlugin import Amplify import XCTest +@testable import AWSCognitoAuthPlugin class HostedUIRequestHelperTests: XCTestCase { private var configuration: HostedUIConfigurationData! @@ -24,7 +24,8 @@ class HostedUIRequestHelperTests: XCTestCase { idpIdentifier: nil ), presentationAnchor: nil, - preferPrivateSession: false) + preferPrivateSession: false + ) ) override func setUp() { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentity.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentity.swift index ed6d2a48e0..929feeb725 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentity.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentity.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentity import ClientRuntime +@testable import AWSCognitoAuthPlugin struct MockIdentity: CognitoIdentityBehavior { @@ -19,8 +19,10 @@ struct MockIdentity: CognitoIdentityBehavior { let mockGetIdResponse: MockGetIdResponse? let mockGetCredentialsResponse: MockGetCredentialsResponse? - init(mockGetIdResponse: MockGetIdResponse? = nil, - mockGetCredentialsResponse: MockGetCredentialsResponse? = nil) { + init( + mockGetIdResponse: MockGetIdResponse? = nil, + mockGetCredentialsResponse: MockGetCredentialsResponse? = nil + ) { self.mockGetIdResponse = mockGetIdResponse self.mockGetCredentialsResponse = mockGetCredentialsResponse } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentityProvider.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentityProvider.swift index 5558466828..5cb525f25f 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentityProvider.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentityProvider.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +@testable import AWSCognitoAuthPlugin struct MockIdentityProvider: CognitoUserPoolBehavior { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/StateSequence.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/StateSequence.swift index 8f30f50335..a77649ae61 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/StateSequence.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/StateSequence.swift @@ -7,8 +7,8 @@ import XCTest -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +@testable import AWSCognitoAuthPlugin struct StateSequence: CustomStringConvertible where MyState: State, MyEvent: StateMachineEvent { let resolver: AnyResolver @@ -16,10 +16,11 @@ struct StateSequence: CustomStringConvertible where MyState: S let event: MyEvent let expected: MyState - init(resolver: AnyResolver, - oldState: MyState, - event: MyEvent, - expected: MyState + init( + resolver: AnyResolver, + oldState: MyState, + event: MyEvent, + expected: MyState ) { self.resolver = resolver self.oldState = oldState diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFederationToIdentityPoolTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFederationToIdentityPoolTests.swift index 604c0b24d8..58576b0806 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFederationToIdentityPoolTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFederationToIdentityPoolTests.swift @@ -7,11 +7,11 @@ import Foundation +import AWSCognitoIdentity +import AWSPluginsCore import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentity -import AWSPluginsCore // swiftlint:disable file_length // swiftlint:disable type_body_length @@ -37,7 +37,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secretAccessKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let getId: MockIdentity.MockGetIdResponse = { input in @@ -68,25 +69,31 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)), + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ), AuthState.configured( AuthenticationState.notConfigured, AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)), + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ), AuthState.configured( AuthenticationState.federatedToIdentityPool, AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredAWSCredentials)), + AmplifyCredentials.testDataWithExpiredAWSCredentials) + ), AuthState.configured( AuthenticationState.notConfigured, - AuthorizationState.configured), + AuthorizationState.configured + ), AuthState.configured( AuthenticationState.error(.testData), - AuthorizationState.configured), + AuthorizationState.configured + ), AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.error(.sessionExpired( - error: NotAuthorizedException(message: "message")))) + error: NotAuthorizedException(message: "message"))) + ) ] for initialState in statesToTest { @@ -94,9 +101,11 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { let federatedResult = try await plugin.federateToIdentityPool(withProviderToken: authenticationToken, for: provider) XCTAssertNotNil(federatedResult) @@ -130,7 +139,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secret", - sessionToken: "session") + sessionToken: "session" + ) let getId: MockIdentity.MockGetIdResponse = { input in @@ -160,14 +170,17 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)) + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ) let plugin = configurePluginWith( identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { let federatedResult = try await plugin.federateToIdentityPool(withProviderToken: authenticationToken, for: provider) @@ -220,10 +233,12 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let statesToTest = [ AuthState.configured( AuthenticationState.signedOut(.testData), - AuthorizationState.notConfigured), + AuthorizationState.notConfigured + ), AuthState.configured( AuthenticationState.signedIn(.testData), - AuthorizationState.configured) + AuthorizationState.configured + ) ] for initialState in statesToTest { @@ -231,9 +246,11 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { _ = try await plugin.federateToIdentityPool(withProviderToken: authenticationToken, for: provider) XCTFail("Should not succeed") @@ -261,7 +278,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secret", - sessionToken: "session") + sessionToken: "session" + ) let getId: MockIdentity.MockGetIdResponse = { _ in if shouldThrowError { @@ -279,23 +297,28 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, initialState: AuthState.configured( AuthenticationState.error(.testData), - AuthorizationState.error(.invalidState(message: "")))) + AuthorizationState.error(.invalidState(message: "")) + ) + ) do { // Should setup the plugin with a token shouldThrowError = false _ = try await plugin.federateToIdentityPool( withProviderToken: "someToken", - for: .facebook) + for: .facebook + ) // Push the AuthState to an error state shouldThrowError = true _ = try? await plugin.federateToIdentityPool( withProviderToken: "someToken", - for: .facebook) + for: .facebook + ) // Should still be able to clear credentials try await plugin.clearFederationToIdentityPool() @@ -318,7 +341,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secret", - sessionToken: "session") + sessionToken: "session" + ) let getId: MockIdentity.MockGetIdResponse = { _ in return .init(identityId: "mockIdentityId") @@ -334,10 +358,13 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { AuthorizationState.sessionEstablished(.identityPoolWithFederation( federatedToken: .testData, identityID: "identityId", - credentials: .testData))), + credentials: .testData + )) + ), AuthState.configured( AuthenticationState.error(.testData), - AuthorizationState.error(.invalidState(message: ""))) + AuthorizationState.error(.invalidState(message: "")) + ) ] for initialState in statesToTest { @@ -345,13 +372,16 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { _ = try await plugin.federateToIdentityPool( withProviderToken: "someToken", - for: .facebook) + for: .facebook + ) try await plugin.clearFederationToIdentityPool() } catch { XCTFail("Received failure with error \(error)") @@ -382,13 +412,16 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let statesToTest = [ AuthState.configured( AuthenticationState.federatedToIdentityPool, - AuthorizationState.configured), + AuthorizationState.configured + ), AuthState.configured( AuthenticationState.configured, AuthorizationState.sessionEstablished(.identityPoolWithFederation( federatedToken: .testData, identityID: "identityId", - credentials: .testData))) + credentials: .testData + )) + ) ] for initialState in statesToTest { @@ -396,9 +429,11 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { try await plugin.clearFederationToIdentityPool() XCTFail("Should not succeed") @@ -433,7 +468,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secretAccessKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let cognitoAPIExpectation = expectation(description: "Cognito API gets called") cognitoAPIExpectation.expectedFulfillmentCount = 1 @@ -464,15 +500,19 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { .identityPoolWithFederation( federatedToken: federatedToken, identityID: mockIdentityId, - credentials: .expiredTestData))) + credentials: .expiredTestData + )) + ) let plugin = configurePluginWith( identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertTrue(session.isSignedIn) @@ -489,8 +529,7 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { do { _ = try (session as? AuthCognitoTokensProvider)?.getCognitoTokens().get() - } - catch let error as AuthError { + } catch let error as AuthError { guard case .invalidState = error else { XCTFail("Should throw Auth Error with invalid state \(error)") return @@ -526,7 +565,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secretAccessKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let getId: MockIdentity.MockGetIdResponse = { _ in XCTFail("Get ID should not get called") @@ -544,15 +584,19 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { .identityPoolWithFederation( federatedToken: federatedToken, identityID: mockIdentityId, - credentials: .testData))) + credentials: .testData + )) + ) let plugin = configurePluginWith( identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertTrue(session.isSignedIn) @@ -568,8 +612,7 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { do { _ = try (session as? AuthCognitoTokensProvider)?.getCognitoTokens().get() - } - catch let error as AuthError { + } catch let error as AuthError { guard case .invalidState = error else { XCTFail("Should throw Auth Error with invalid state \(error)") return @@ -604,7 +647,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secretKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let cognitoAPIExpectation = expectation(description: "Cognito API gets called") cognitoAPIExpectation.expectedFulfillmentCount = 1 @@ -635,15 +679,19 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { .identityPoolWithFederation( federatedToken: federatedToken, identityID: mockIdentityId, - credentials: .expiredTestData))) + credentials: .expiredTestData + )) + ) let plugin = configurePluginWith( identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { let session = try await plugin.fetchAuthSession(options: .forceRefresh()) @@ -660,8 +708,7 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { do { _ = try (session as? AuthCognitoTokensProvider)?.getCognitoTokens().get() - } - catch let error as AuthError { + } catch let error as AuthError { guard case .invalidState = error else { XCTFail("Should throw Auth Error with invalid state \(error)") return @@ -695,7 +742,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secretKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let getId: MockIdentity.MockGetIdResponse = { _ in XCTFail("Get ID should not get called") @@ -719,18 +767,22 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)), + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ), AuthState.configured( AuthenticationState.notConfigured, AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)), + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ), AuthState.configured( AuthenticationState.federatedToIdentityPool, AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredAWSCredentials)), + AmplifyCredentials.testDataWithExpiredAWSCredentials) + ), AuthState.configured( AuthenticationState.notConfigured, - AuthorizationState.configured) + AuthorizationState.configured + ) ] for initialState in statesToTest { @@ -738,14 +790,17 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { let federatedResult = try await plugin.federateToIdentityPool( withProviderToken: authenticationToken, for: provider, - options: .init(developerProvidedIdentityID: mockIdentityId)) + options: .init(developerProvidedIdentityID: mockIdentityId) + ) XCTAssertNotNil(federatedResult) XCTAssertEqual(federatedResult.credentials.sessionToken, credentials.sessionToken) XCTAssertEqual(federatedResult.credentials.accessKeyId, credentials.accessKeyId) @@ -770,7 +825,7 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { /// func testFederateToIdentityPoolWhenGetIdErrorsOut() async throws { - var shouldThrowError: Bool = false + var shouldThrowError = false let provider = AuthProvider.facebook let authenticationToken = "authenticationToken" @@ -780,7 +835,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secretAccessKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let getId: MockIdentity.MockGetIdResponse = { input in return .init(identityId: mockIdentityId) @@ -797,15 +853,18 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)) + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ) let plugin = configurePluginWith( identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) shouldThrowError = true do { @@ -849,14 +908,15 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let mockIdentityId = "mockIdentityId" - var shouldThrowError: Bool = false + var shouldThrowError = false let federatedToken: FederatedToken = .testData let credentials = CognitoIdentityClientTypes.Credentials( accessKeyId: "accessKey", expiration: Date(), secretKey: "secretAccessKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let getId: MockIdentity.MockGetIdResponse = { _ in XCTFail("GetId should not be called") @@ -877,15 +937,19 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { .identityPoolWithFederation( federatedToken: federatedToken, identityID: mockIdentityId, - credentials: .expiredTestData))) + credentials: .expiredTestData + )) + ) let plugin = configurePluginWith( identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) shouldThrowError = true @@ -925,6 +989,6 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { XCTFail("Received failure with error \(error)") } } - + } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFetchSignInSessionOperationTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFetchSignInSessionOperationTests.swift index 0afa434b9c..3ab0dd1b06 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFetchSignInSessionOperationTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFetchSignInSessionOperationTests.swift @@ -7,13 +7,13 @@ import Foundation -import XCTest -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentity import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon @@ -37,24 +37,32 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testData)) + AmplifyCredentials.testData) + ) let getId: MockIdentity.MockGetIdResponse = { _ in return .init(identityId: "mockIdentityId") } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } - let plugin = configurePluginWith(identityPool: { - MockIdentity(mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) }, - initialState: initialState) + let plugin = configurePluginWith( + identityPool: { + MockIdentity( + mockGetIdResponse: getId, + mockGetCredentialsResponse: getCredentials + ) + }, + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertTrue(session.isSignedIn) @@ -92,14 +100,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testData)) + AmplifyCredentials.testData) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in resultExpectation.fulfill() return InitiateAuthOutput(authenticationResult: .init( accessToken: "accessToken", - expiresIn: 1000, + expiresIn: 1_000, idToken: "idToken", - refreshToken: "refreshToke")) + refreshToken: "refreshToke" + )) } let awsCredentials: MockIdentity.MockGetCredentialsResponse = { _ in @@ -108,14 +118,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secret", - sessionToken: "session") + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } let plugin = configurePluginWith( userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, identityPool: { MockIdentity(mockGetCredentialsResponse: awsCredentials) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: .forceRefresh()) resultExpectation.fulfill() XCTAssertTrue(session.isSignedIn) @@ -152,24 +164,32 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)) + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ) let getId: MockIdentity.MockGetIdResponse = { _ in return .init(identityId: "mockIdentityId") } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } - let plugin = configurePluginWith(identityPool: { - MockIdentity(mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) }, - initialState: initialState) + let plugin = configurePluginWith( + identityPool: { + MockIdentity( + mockGetIdResponse: getId, + mockGetCredentialsResponse: getCredentials + ) + }, + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertFalse(session.isSignedIn) @@ -183,7 +203,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let error) = tokensResult, - case .signedOut = error else { + case .signedOut = error + else { XCTFail("Should return signed out error") return } @@ -206,7 +227,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException() @@ -224,14 +246,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let identityIdResult = (session as? AuthCognitoIdentityProvider)?.getIdentityId() guard case .failure(let identityIdError) = identityIdResult, - case .sessionExpired = identityIdError else { + case .sessionExpired = identityIdError + else { XCTFail("Should return sessionExpired error") return } let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .sessionExpired = tokenError else { + case .sessionExpired = tokenError + else { XCTFail("Should return sessionExpired error") return } @@ -254,13 +278,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in - return InitiateAuthOutput(authenticationResult: .init(accessToken: "accessToken", - expiresIn: 1000, - idToken: "idToken", - refreshToken: "refreshToke")) + return InitiateAuthOutput(authenticationResult: .init( + accessToken: "accessToken", + expiresIn: 1_000, + idToken: "idToken", + refreshToken: "refreshToke" + )) } let awsCredentials: MockIdentity.MockGetCredentialsResponse = { _ in @@ -270,7 +297,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let plugin = configurePluginWith( userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, identityPool: { MockIdentity(mockGetCredentialsResponse: awsCredentials) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) @@ -283,14 +311,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let identityIdResult = (session as? AuthCognitoIdentityProvider)?.getIdentityId() guard case .failure(let identityIdError) = identityIdResult, - case .sessionExpired = identityIdError else { + case .sessionExpired = identityIdError + else { XCTFail("Should return sessionExpired error") return } let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .sessionExpired = tokenError else { + case .sessionExpired = tokenError + else { XCTFail("Should return sessionExpired error") return } @@ -486,18 +516,22 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in - return InitiateAuthOutput(authenticationResult: .init(accessToken: nil, - expiresIn: 1000, - idToken: "idToken", - refreshToken: "refreshToke")) + return InitiateAuthOutput(authenticationResult: .init( + accessToken: nil, + expiresIn: 1_000, + idToken: "idToken", + refreshToken: "refreshToke" + )) } let plugin = configurePluginWith( userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) @@ -510,14 +544,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let identityIdResult = (session as? AuthCognitoIdentityProvider)?.getIdentityId() guard case .failure(let identityIdError) = identityIdResult, - case .unknown = identityIdError else { + case .unknown = identityIdError + else { XCTFail("Should return unknown error") return } let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .unknown = tokenError else { + case .unknown = tokenError + else { XCTFail("Should return unknown error") return } @@ -539,13 +575,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in - return InitiateAuthOutput(authenticationResult: .init(accessToken: "accessToken", - expiresIn: 1000, - idToken: "idToken", - refreshToken: "refreshToke")) + return InitiateAuthOutput(authenticationResult: .init( + accessToken: "accessToken", + expiresIn: 1_000, + idToken: "idToken", + refreshToken: "refreshToke" + )) } let awsCredentials: MockIdentity.MockGetCredentialsResponse = { _ in @@ -554,7 +593,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let plugin = configurePluginWith( userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, identityPool: { MockIdentity(mockGetCredentialsResponse: awsCredentials) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) @@ -567,14 +607,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let identityIdResult = (session as? AuthCognitoIdentityProvider)?.getIdentityId() guard case .failure(let identityIdError) = identityIdResult, - case .unknown = identityIdError else { + case .unknown = identityIdError + else { XCTFail("Should return unknown error") return } let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .unknown = tokenError else { + case .unknown = tokenError + else { XCTFail("Should return unknown error") return } @@ -596,24 +638,32 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedOut(.testData), - AuthorizationState.error(.sessionError(.service(AuthError.unknown("error")), .noCredentials))) + AuthorizationState.error(.sessionError(.service(AuthError.unknown("error")), .noCredentials)) + ) let getId: MockIdentity.MockGetIdResponse = { _ in return .init(identityId: "mockIdentityId") } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } - let plugin = configurePluginWith(identityPool: { - MockIdentity(mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) }, - initialState: initialState) + let plugin = configurePluginWith( + identityPool: { + MockIdentity( + mockGetIdResponse: getId, + mockGetCredentialsResponse: getCredentials + ) + }, + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertFalse(session.isSignedIn) @@ -627,7 +677,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let error) = tokensResult, - case .signedOut = error else { + case .signedOut = error + else { XCTFail("Should return signed out error") return } @@ -650,19 +701,25 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)) + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ) let awsCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") - return GetCredentialsForIdentityOutput(credentials: credentials, - identityId: "ss") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) + return GetCredentialsForIdentityOutput( + credentials: credentials, + identityId: "ss" + ) } let plugin = configurePluginWith( identityPool: { MockIdentity(mockGetCredentialsResponse: awsCredentials) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertFalse(session.isSignedIn) @@ -680,7 +737,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .signedOut = tokenError else { + case .signedOut = tokenError + else { XCTFail("Should return signedOut error") return } @@ -702,7 +760,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException(message: "NotAuthorized") @@ -710,7 +769,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let plugin = configurePluginWith( userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) @@ -718,21 +778,24 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let credentialsResult = (session as? AuthAWSCredentialsProvider)?.getAWSCredentials() guard case .failure(let error) = credentialsResult, - case .sessionExpired = error else { + case .sessionExpired = error + else { XCTFail("Should return sessionExpired error") return } let identityIdResult = (session as? AuthCognitoIdentityProvider)?.getIdentityId() guard case .failure(let identityIdError) = identityIdResult, - case .sessionExpired = identityIdError else { + case .sessionExpired = identityIdError + else { XCTFail("Should return sessionExpired error") return } let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .sessionExpired = tokenError else { + case .sessionExpired = tokenError + else { XCTFail("Should return sessionExpired error") return } @@ -763,17 +826,24 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } - let plugin = configurePluginWith(identityPool: { - MockIdentity(mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) }, - initialState: initialState) + let plugin = configurePluginWith( + identityPool: { + MockIdentity( + mockGetIdResponse: getId, + mockGetCredentialsResponse: getCredentials + ) + }, + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertFalse(session.isSignedIn) @@ -802,13 +872,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in - return InitiateAuthOutput(authenticationResult: .init(accessToken: "accessToken", - expiresIn: 1000, - idToken: "idToken", - refreshToken: "refreshToke")) + return InitiateAuthOutput(authenticationResult: .init( + accessToken: "accessToken", + expiresIn: 1_000, + idToken: "idToken", + refreshToken: "refreshToke" + )) } let awsCredentials: MockIdentity.MockGetCredentialsResponse = { _ in @@ -817,7 +890,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let plugin = configurePluginWith( userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, identityPool: { MockIdentity(mockGetCredentialsResponse: awsCredentials) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) @@ -830,14 +904,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let identityIdResult = (session as? AuthCognitoIdentityProvider)?.getIdentityId() guard case .failure(let identityIdError) = identityIdResult, - case .service = identityIdError else { + case .service = identityIdError + else { XCTFail("Should return service error") return } let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .service = tokenError else { + case .service = tokenError + else { XCTFail("Should return service error") return } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/BaseAuthorizationTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/BaseAuthorizationTests.swift index 560584a639..2b66c149e9 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/BaseAuthorizationTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/BaseAuthorizationTests.swift @@ -14,24 +14,30 @@ class BaseAuthorizationTests: XCTestCase { let apiTimeout = 2.0 - func configurePluginWith(authConfiguration: AuthConfiguration = Defaults.makeDefaultAuthConfigData(), - userPool: @escaping () throws -> CognitoUserPoolBehavior = Defaults.makeDefaultUserPool, - identityPool: @escaping () throws -> CognitoIdentityBehavior = Defaults.makeIdentity, - initialState: AuthState) -> AWSCognitoAuthPlugin { + func configurePluginWith( + authConfiguration: AuthConfiguration = Defaults.makeDefaultAuthConfigData(), + userPool: @escaping () throws -> CognitoUserPoolBehavior = Defaults.makeDefaultUserPool, + identityPool: @escaping () throws -> CognitoIdentityBehavior = Defaults.makeIdentity, + initialState: AuthState + ) -> AWSCognitoAuthPlugin { let plugin = AWSCognitoAuthPlugin() let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: identityPool, - userPoolFactory: userPool) - let statemachine = AuthStateMachine(resolver: AuthState.Resolver(), - environment: environment, - initialState: initialState) + userPoolFactory: userPool + ) + let statemachine = AuthStateMachine( + resolver: AuthState.Resolver(), + environment: environment, + initialState: initialState + ) plugin.configure( authConfiguration: Defaults.makeDefaultAuthConfigData(), authEnvironment: environment, authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) return plugin } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSAuthSignOutTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSAuthSignOutTaskTests.swift index e940246c43..51e440650b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSAuthSignOutTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSAuthSignOutTaskTests.swift @@ -7,10 +7,10 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -19,16 +19,18 @@ class AWSAuthSignOutTaskTests: BasePluginTest { override var initialState: AuthState { AuthState.configured( AuthenticationState.signedIn(.testData), - AuthorizationState.sessionEstablished(.testData)) + AuthorizationState.sessionEstablished(.testData) + ) } func testSuccessfullSignOut() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in return .testData }, mockGlobalSignOutResponse: { _ in return .testData - }) + } + ) guard let result = await plugin.signOut() as? AWSCognitoSignOutResult, case .complete = result else { XCTFail("Did not return complete signOut") @@ -37,16 +39,19 @@ class AWSAuthSignOutTaskTests: BasePluginTest { } func testGlobalSignOutFailed() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in return .testData }, mockGlobalSignOutResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException() - }) + } + ) guard let result = await plugin.signOut(options: .init(globalSignOut: true)) as? AWSCognitoSignOutResult, - case .partial(revokeTokenError: let revokeTokenError, - globalSignOutError: let globalSignOutError, - hostedUIError: let hostedUIError) = result else { + case .partial( + revokeTokenError: let revokeTokenError, + globalSignOutError: let globalSignOutError, + hostedUIError: let hostedUIError + ) = result else { XCTFail("Did not return partial signOut") return } @@ -57,16 +62,19 @@ class AWSAuthSignOutTaskTests: BasePluginTest { } func testRevokeSignOutFailed() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException() }, mockGlobalSignOutResponse: { _ in return .testData - }) + } + ) guard let result = await plugin.signOut(options: .init(globalSignOut: true)) as? AWSCognitoSignOutResult, - case .partial(revokeTokenError: let revokeTokenError, - globalSignOutError: let globalSignOutError, - hostedUIError: let hostedUIError) = result else { + case .partial( + revokeTokenError: let revokeTokenError, + globalSignOutError: let globalSignOutError, + hostedUIError: let hostedUIError + ) = result else { XCTFail("Did not return partial signOut") return } @@ -79,7 +87,8 @@ class AWSAuthSignOutTaskTests: BasePluginTest { let initialState = AuthState.configured( AuthenticationState.federatedToIdentityPool, - AuthorizationState.sessionEstablished(.testData)) + AuthorizationState.sessionEstablished(.testData) + ) let authPlugin = configureCustomPluginWith(initialState: initialState) @@ -98,7 +107,8 @@ class AWSAuthSignOutTaskTests: BasePluginTest { let initialState = AuthState.configured( AuthenticationState.signedIn(.hostedUISignInData), - AuthorizationState.sessionEstablished(.hostedUITestData)) + AuthorizationState.sessionEstablished(.hostedUITestData) + ) let authPlugin = configureCustomPluginWith(initialState: initialState) @@ -118,7 +128,8 @@ class AWSAuthSignOutTaskTests: BasePluginTest { let initialState = AuthState.configured( AuthenticationState.signedOut(.init()), - AuthorizationState.sessionEstablished(.testDataIdentityPool)) + AuthorizationState.sessionEstablished(.testDataIdentityPool) + ) let authPlugin = configureCustomPluginWith(initialState: initialState) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSCognitoAuthClientBehaviorTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSCognitoAuthClientBehaviorTests.swift index 9b17dbf1dc..7b818aeca8 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSCognitoAuthClientBehaviorTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSCognitoAuthClientBehaviorTests.swift @@ -7,11 +7,11 @@ import Foundation -import XCTest import AWSCognitoIdentity +import AWSCognitoIdentityProvider +import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider class AWSCognitoAuthClientBehaviorTests: XCTestCase { let networkTimeout = TimeInterval(10) @@ -21,10 +21,12 @@ class AWSCognitoAuthClientBehaviorTests: XCTestCase { AuthState.configured( AuthenticationState.signedIn( SignedInData( - signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData)), - AuthorizationState.sessionEstablished(AmplifyCredentials.testData)) + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData + )), + AuthorizationState.sessionEstablished(AmplifyCredentials.testData) + ) } override func setUp() { @@ -35,25 +37,30 @@ class AWSCognitoAuthClientBehaviorTests: XCTestCase { } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } let mockIdentity = MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: { mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) let statemachine = Defaults.makeDefaultAuthStateMachine( initialState: initialState, identityPoolFactory: { mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) plugin?.configure( authConfiguration: Defaults.makeDefaultAuthConfigData(), @@ -61,7 +68,8 @@ class AWSCognitoAuthClientBehaviorTests: XCTestCase { authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) } override func tearDown() async throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift index fcdd702657..bcd2bbe465 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift @@ -7,12 +7,12 @@ import Foundation +import AWSCognitoIdentityProvider +import AwsCommonRuntimeKit +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import ClientRuntime -import AwsCommonRuntimeKit @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime class AuthenticationProviderDeleteUserTests: BasePluginTest { @@ -84,7 +84,7 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { GlobalSignOutOutput() }, mockDeleteUserOutput: { _ in - throw CommonRunTimeError.crtError(CRTError(code: 1059)) + throw CommonRunTimeError.crtError(CRTError(code: 1_059)) } ) do { @@ -118,7 +118,7 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { GlobalSignOutOutput() }, mockDeleteUserOutput: { _ in - throw CommonRunTimeError.crtError(CRTError(code: 1059)) + throw CommonRunTimeError.crtError(CRTError(code: 1_059)) } ) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorConfirmResetPasswordTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorConfirmResetPasswordTests.swift index e72b5fc73b..547acc70c3 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorConfirmResetPasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorConfirmResetPasswordTests.swift @@ -7,13 +7,13 @@ import Foundation -import XCTest import AWSCognitoIdentity import AWSCognitoIdentityProvider +import ClientRuntime +import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests { @@ -113,10 +113,12 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests } ) let pluginOptions = AWSAuthConfirmResetPasswordOptions(metadata: ["key": "value"]) - try await plugin.confirmResetPassword(for: "username", - with: "newpassword", - confirmationCode: "code", - options: .init(pluginOptions: pluginOptions)) + try await plugin.confirmResetPassword( + for: "username", + with: "newpassword", + confirmationCode: "code", + options: .init(pluginOptions: pluginOptions) + ) } /// Test a confirmResetPassword call with empty new password diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorResetPasswordTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorResetPasswordTests.swift index 40661b0fbc..fea0bc9361 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorResetPasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorResetPasswordTests.swift @@ -7,12 +7,12 @@ import Foundation -import XCTest import AWSCognitoIdentity -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { @@ -60,9 +60,11 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { /// - I should get a successful result /// func testSuccessfulResetPassword() async throws { - let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType(attributeName: "attribute", - deliveryMedium: .email, - destination: "Amplify@amazon.com") + let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType( + attributeName: "attribute", + deliveryMedium: .email, + destination: "Amplify@amazon.com" + ) mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutput: { _ in ForgotPasswordOutput(codeDeliveryDetails: codeDeliveryDetails) @@ -108,9 +110,11 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { /// func testResetPasswordWithEmptyUsername() async throws { - let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType(attributeName: "attribute", - deliveryMedium: .email, - destination: "Amplify@amazon.com") + let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType( + attributeName: "attribute", + deliveryMedium: .email, + destination: "Amplify@amazon.com" + ) mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutput: { _ in ForgotPasswordOutput(codeDeliveryDetails: codeDeliveryDetails) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/FetchMFAPreferenceTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/FetchMFAPreferenceTaskTests.swift index 9c63e5088a..ad7f092b30 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/FetchMFAPreferenceTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/FetchMFAPreferenceTaskTests.swift @@ -7,10 +7,10 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime // swiftlint:disable type_body_length @@ -27,7 +27,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { /// func testSuccessfulPreferenceFetchWithTOTPPreferred() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init( preferredMfaSetting: "SOFTWARE_TOKEN_MFA", @@ -54,7 +54,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { /// func testSuccessfulPreferenceFetchWithSMSPreferred() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init( preferredMfaSetting: "SMS_MFA", @@ -81,7 +81,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { /// func testSuccessfulPreferenceFetchWithNonePreferred() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init( userMFASettingList: ["SOFTWARE_TOKEN_MFA", "SMS_MFA"] @@ -107,7 +107,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { /// func testInvalidResponseForUserMFASettingsList() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init( userMFASettingList: ["DUMMY"] @@ -133,7 +133,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { /// func testInvalidResponseForUserMFAPreference() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init( preferredMfaSetting: "DUMMY", @@ -160,7 +160,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { /// func testSuccessfulPreferenceFetchWithNonePreferredAndNoneEnabled() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init() }) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/SetUpTOTPTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/SetUpTOTPTaskTests.swift index 9677d365c5..c693368ba6 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/SetUpTOTPTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/SetUpTOTPTaskTests.swift @@ -7,10 +7,10 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime // swiftlint:disable type_body_length @@ -27,7 +27,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSuccessfulSetUpTOTPRequest() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in return .init(secretCode: "sharedSecret") }) @@ -53,7 +53,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpTOTPWithConcurrentModificationException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.ConcurrentModificationException( message: "Exception" @@ -85,7 +85,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpTOTPWithForbiddenException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.ForbiddenException( message: "Exception" @@ -117,7 +117,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpTOTPWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InternalErrorException( message: "Exception" @@ -149,7 +149,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpTOTPWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "Exception" @@ -183,7 +183,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpTOTPWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "Exception" @@ -213,7 +213,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpWithSoftwareTokenMFANotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( message: "Exception" @@ -245,7 +245,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// - I should get a .service error with .resourceNotFound as underlyingError /// func testSetUpTOTPInWithResourceNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.ResourceNotFoundException( message: "Exception" @@ -278,7 +278,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpWithUnknownException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSClientRuntime.UnknownAWSHTTPServiceError( httpResponse: .init(body: .empty, statusCode: .ok), diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/UpdateMFAPreferenceTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/UpdateMFAPreferenceTaskTests.swift index 75b367b5c0..5218c67219 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/UpdateMFAPreferenceTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/UpdateMFAPreferenceTaskTests.swift @@ -7,10 +7,10 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime // swiftlint:disable type_body_length @@ -33,7 +33,7 @@ class UpdateMFAPreferenceTaskTests: BasePluginTest { // Test all the combinations for preference types for smsPreference in allSMSPreferences { for totpPreference in allTOTPPreference { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init( userMFASettingList: ["SOFTWARE_TOKEN_MFA", "SMS_MFA"] @@ -42,18 +42,22 @@ class UpdateMFAPreferenceTaskTests: BasePluginTest { mockSetUserMFAPreferenceResponse: { request in XCTAssertEqual( request.smsMfaSettings?.preferredMfa, - smsPreference.smsSetting().preferredMfa) + smsPreference.smsSetting().preferredMfa + ) XCTAssertEqual( request.softwareTokenMfaSettings?.preferredMfa, - totpPreference.softwareTokenSetting().preferredMfa) + totpPreference.softwareTokenSetting().preferredMfa + ) return .init() - }) + } + ) do { try await plugin.updateMFAPreference( sms: smsPreference, - totp: totpPreference) + totp: totpPreference + ) } catch { XCTFail("Received failure with error \(error)") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/VerifyTOTPSetupTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/VerifyTOTPSetupTaskTests.swift index e9b727624b..a6265c4d37 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/VerifyTOTPSetupTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/VerifyTOTPSetupTaskTests.swift @@ -7,10 +7,10 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime // swiftlint:disable type_body_length @@ -27,7 +27,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testSuccessfulVerifyTOTPSetupRequest() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in XCTAssertEqual(request.userCode, "123456") XCTAssertEqual(request.friendlyDeviceName, "device") @@ -37,7 +37,8 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { do { let pluginOptions = VerifyTOTPSetupOptions(friendlyDeviceName: "device") try await plugin.verifyTOTPSetup( - code: "123456", options: .init(pluginOptions: pluginOptions)) + code: "123456", options: .init(pluginOptions: pluginOptions) + ) } catch { XCTFail("Received failure with error \(error)") } @@ -56,7 +57,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testVerifyTOTPSetupWithForbiddenException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.ForbiddenException( message: "Exception" @@ -88,7 +89,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testVerifyTOTPSetupWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InternalErrorException( message: "Exception" @@ -120,7 +121,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testVerifyTOTPSetupWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "Exception" @@ -154,7 +155,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testVerifyTOTPSetupWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "Exception" @@ -184,7 +185,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testVerifyTOTPSetupWithSoftwareTokenMFANotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( message: "Exception" @@ -216,7 +217,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .resourceNotFound as underlyingError /// func testVerifyTOTPSetupInWithResourceNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.ResourceNotFoundException( message: "Exception" @@ -249,7 +250,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testVerifyTOTPSetupWithUnknownException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSClientRuntime.UnknownAWSHTTPServiceError( httpResponse: .init(body: .empty, statusCode: .ok), @@ -281,7 +282,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .codeMismatch as underlyingError /// func testVerifyTOTPSetupInWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -313,7 +314,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .softwareTokenMFANotEnabled as underlyingError /// func testVerifyTOTPSetupInWithEnableSoftwareTokenMFAException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.EnableSoftwareTokenMFAException( message: "Exception" @@ -345,7 +346,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .passwordResetRequired as underlyingError /// func testVerifyTOTPSetupInWithPasswordResetRequiredException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.PasswordResetRequiredException( message: "Exception" @@ -377,7 +378,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .requestLimitExceeded as underlyingError /// func testVerifyTOTPSetupInWithTooManyRequestsException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.TooManyRequestsException( message: "Exception" @@ -409,7 +410,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .userNotFound as underlyingError /// func testVerifyTOTPSetupInWithUserNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.UserNotFoundException( message: "Exception" @@ -441,7 +442,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .userNotConfirmed as underlyingError /// func testVerifyTOTPSetupInWithUserNotConfirmedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.UserNotConfirmedException( message: "Exception" @@ -473,7 +474,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error /// func testVerifyTOTPSetupInWithInvalidUserPoolConfigurationException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InvalidUserPoolConfigurationException( message: "Exception" diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthConfirmSignInTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthConfirmSignInTaskTests.swift index da1a27739a..b41c051a4d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthConfirmSignInTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthConfirmSignInTaskTests.swift @@ -7,23 +7,27 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length class AuthenticationProviderConfirmSigninTests: BasePluginTest { - + override var initialState: AuthState { AuthState.configured( AuthenticationState.signingIn( - .resolvingChallenge(.waitingForAnswer(.testData(), .apiBased(.userSRP)), - .smsMfa, .apiBased(.userSRP))), - AuthorizationState.sessionEstablished(.testData)) + .resolvingChallenge( + .waitingForAnswer(.testData(), .apiBased(.userSRP)), + .smsMfa, + .apiBased(.userSRP) + )), + AuthorizationState.sessionEstablished(.testData) + ) } - + /// Test a successful confirmSignIn call with .done as next step /// /// - Given: an auth plugin with mocked service. Mocked service calls should mock a successful response @@ -33,14 +37,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a successful result with .done as the next step /// func testSuccessfulConfirmSignIn() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.challengeName, .smsMfa) XCTAssertEqual(request.challengeResponses?["SMS_MFA_CODE"], "code") return .testData() }) - + do { let confirmSignInResult = try await plugin.confirmSignIn(challengeResponse: "code") guard case .done = confirmSignInResult.nextStep else { @@ -52,7 +56,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { XCTFail("Received failure with error \(error)") } } - + /// Test a confirmSignIn call with an empty confirmation code /// /// - Given: an auth plugin with mocked service. Mocked service should mock a successful response @@ -62,13 +66,13 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get an .validation error /// func testConfirmSignInWithEmptyResponse() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in XCTFail("Cognito service should not be called") return .testData() }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "") XCTFail("Should not succeed") @@ -79,7 +83,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with an empty confirmation code followed by a second valid confirmSignIn call /// /// - Given: an auth plugin with mocked service. Mocked service should mock a successful response @@ -89,12 +93,12 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a successful result with .done as the next step /// func testSuccessfullyConfirmSignInAfterAFailedConfirmSignIn() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in return .testData() }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "") XCTFail("Should not succeed") @@ -103,7 +107,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { XCTFail("Should produce validation error instead of \(error)") return } - + do { let confirmSignInResult = try await plugin.confirmSignIn(challengeResponse: "code") XCTAssertTrue(confirmSignInResult.isSignedIn, "Signin result should be complete") @@ -125,10 +129,11 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { let confirmSignInOptions = AWSAuthConfirmSignInOptions( userAttributes: [.init(.email, value: "some@some.com")], - metadata: ["metadata": "test"]) + metadata: ["metadata": "test"] + ) - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { input in XCTAssertEqual(confirmSignInOptions.metadata, input.clientMetadata) XCTAssertEqual(input.challengeResponses?["userAttributes.email"], "some@some.com") @@ -138,7 +143,8 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { do { let confirmSignInResult = try await plugin.confirmSignIn( challengeResponse: "code", - options: .init(pluginOptions: confirmSignInOptions)) + options: .init(pluginOptions: confirmSignInOptions) + ) guard case .done = confirmSignInResult.nextStep else { XCTFail("Result should be .done for next step") return @@ -148,9 +154,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { XCTFail("Received failure with error \(error)") } } - + // MARK: Service error handling test - + /// Test a confirmSignIn call with aliasExistsException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -161,14 +167,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .aliasExists as underlyingError /// func testConfirmSignInWithAliasExistsException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.AliasExistsException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -180,7 +186,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { XCTAssertEqual(underlyingError as? AWSCognitoAuthError, .aliasExists) } } - + /// Test a confirmSignIn call with CodeMismatchException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -191,13 +197,13 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .codeMismatch as underlyingError /// func testConfirmSignInWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -214,7 +220,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } func testConfirmSignInRetryWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -234,7 +240,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { return } - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in return .testData() }) @@ -247,7 +253,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } - + /// Test a confirmSignIn call with CodeExpiredException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -258,14 +264,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .codeExpired as underlyingError /// func testConfirmSignInWithExpiredCodeException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.ExpiredCodeException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -280,7 +286,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with InternalErrorException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a InternalErrorException response @@ -290,14 +296,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get an .unknown error /// func testConfirmSignInWithInternalErrorException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -308,7 +314,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with InvalidLambdaResponseException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -319,13 +325,13 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .lambda as underlyingError /// func testConfirmSignInWithInvalidLambdaResponseException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidLambdaResponseException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -340,7 +346,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with InvalidParameterException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -352,14 +358,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .invalidParameter as underlyingError /// func testConfirmSignInWithInvalidParameterException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -374,7 +380,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with InvalidPasswordException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -386,14 +392,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .invalidPassword as underlyingError /// func testConfirmSignInWithInvalidPasswordException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidPasswordException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -408,7 +414,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with InvalidSmsRoleAccessPolicy response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -419,13 +425,13 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .smsRole as underlyingError /// func testConfirmSignInWithinvalidSmsRoleAccessPolicyException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -440,7 +446,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with InvalidSmsRoleTrustRelationship response from service /// /// - Given: Given an auth plugin with mocked service. Mocked service should mock a @@ -451,13 +457,13 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .smsRole as underlyingError /// func testConfirmSignInWithInvalidSmsRoleTrustRelationshipException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -486,7 +492,8 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { let identityPoolConfigData = Defaults.makeIdentityConfigData() let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: Defaults.makeIdentity) + cognitoIdentityFactory: Defaults.makeIdentity + ) let environment = AuthEnvironment( configuration: .identityPools(identityPoolConfigData), userPoolConfigData: nil, @@ -496,8 +503,10 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { credentialsClient: Defaults.makeCredentialStoreOperationBehavior(), logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") ) - let stateMachine = Defaults.authStateMachineWith(environment: environment, - initialState: .notConfigured) + let stateMachine = Defaults.authStateMachineWith( + environment: environment, + initialState: .notConfigured + ) let plugin = AWSCognitoAuthPlugin() plugin.configure( authConfiguration: .identityPools(identityPoolConfigData), @@ -505,7 +514,8 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { authStateMachine: stateMachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) do { _ = try await plugin.confirmSignIn(challengeResponse: "code") @@ -530,14 +540,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .mfaMethodNotFound as underlyingError /// func testCofirmSignInWithMFAMethodNotFoundException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.MFAMethodNotFoundException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should not succeed") @@ -552,7 +562,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with NotAuthorizedException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -564,14 +574,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .notAuthorized error /// func testConfirmSignInWithNotAuthorizedException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -582,7 +592,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn with PasswordResetRequiredException from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -594,14 +604,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .resetPassword as next step /// func testConfirmSignInWithPasswordResetRequiredException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.PasswordResetRequiredException( message: "Exception" ) }) - + do { let confirmSignInResult = try await plugin.confirmSignIn(challengeResponse: "code") guard case .resetPassword = confirmSignInResult.nextStep else { @@ -613,7 +623,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } - + /// Test a confirmSignIn call with SoftwareTokenMFANotFoundException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -625,14 +635,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .softwareTokenMFANotEnabled as underlyingError /// func testConfirmSignInWithSoftwareTokenMFANotFoundException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -647,7 +657,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with TooManyRequestsException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -659,14 +669,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .requestLimitExceeded as underlyingError /// func testConfirmSignInWithTooManyRequestsException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.TooManyRequestsException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -681,7 +691,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with UnexpectedLambdaException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -693,14 +703,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .lambda as underlyingError /// func testConfirmSignInWithUnexpectedLambdaException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UnexpectedLambdaException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -715,7 +725,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with UserLambdaValidationException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -727,14 +737,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .lambda as underlyingError /// func testConfirmSignInWithUserLambdaValidationException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserLambdaValidationException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -749,7 +759,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with UserNotConfirmedException response from service /// /// - Given: Given an auth plugin with mocked service. Mocked service should mock a @@ -761,14 +771,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get .confirmSignUp as next step /// func testConfirmSignInWithUserNotConfirmedException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserNotConfirmedException( message: "Exception" ) }) - + do { let confirmSignInResult = try await plugin.confirmSignIn(challengeResponse: "code") guard case .confirmSignUp = confirmSignInResult.nextStep else { @@ -779,7 +789,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { XCTFail("Should not return error \(error)") } } - + /// Test a confirmSignIn call with UserNotFound response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -791,14 +801,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .userNotFound error /// func testConfirmSignInWithUserNotFoundException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserNotFoundException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthMigrationSignInTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthMigrationSignInTaskTests.swift index de2caa7054..8b61c473ad 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthMigrationSignInTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthMigrationSignInTaskTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider class AWSAuthMigrationSignInTaskTests: XCTestCase { @@ -30,25 +30,30 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } let mockIdentity = MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: { mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) let statemachine = Defaults.makeDefaultAuthStateMachine( initialState: initialState, identityPoolFactory: { mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) plugin?.configure( authConfiguration: Defaults.makeDefaultAuthConfigData(), @@ -56,7 +61,8 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) } override func tearDown() { @@ -68,10 +74,12 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - return .init(authenticationResult: .init(accessToken: Defaults.validAccessToken, - expiresIn: 2, - idToken: "idToken", - refreshToken: "refreshToken")) + return .init(authenticationResult: .init( + accessToken: Defaults.validAccessToken, + expiresIn: 2, + idToken: "idToken", + refreshToken: "refreshToken" + )) } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInOptionsTestCase.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInOptionsTestCase.swift index 3968b20914..096b5ff865 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInOptionsTestCase.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInOptionsTestCase.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentity -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin class AWSAuthSignInOptionsTestCase: BasePluginTest { override var initialState: AuthState { @@ -24,7 +24,8 @@ class AWSAuthSignInOptionsTestCase: BasePluginTest { authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -33,10 +34,12 @@ class AWSAuthSignInOptionsTestCase: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) } @@ -174,7 +177,7 @@ class AWSAuthSignInOptionsTestCase: BasePluginTest { } } -fileprivate extension AuthState { +private extension AuthState { var authenticationState: AuthenticationState? { if case .configured(let authenticationState, _) = self { return authenticationState @@ -183,7 +186,7 @@ fileprivate extension AuthState { } } -fileprivate extension AuthenticationState { +private extension AuthenticationState { var signInEvent: SignInEventData? { if case .signingIn(.signingInWithSRP(_, let eventData)) = self { return eventData diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInPluginTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInPluginTests.swift index 22ae40ce2c..493a391815 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInPluginTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInPluginTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentity -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin class AWSAuthSignInPluginTests: BasePluginTest { @@ -29,13 +29,14 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSuccessfulSignIn() async { let clientMetadata = ["somekey": "somevalue"] - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in XCTAssertEqual(clientMetadata, input.clientMetadata) return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in XCTAssertEqual(clientMetadata, input.clientMetadata) return RespondToAuthChallengeOutput( @@ -45,10 +46,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions(metadata: clientMetadata) @@ -77,12 +80,13 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSuccessfulSignInWithAuthFlow() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -91,10 +95,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions( @@ -126,7 +132,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithEmptyUsername() async { - self.mockIdentityProvider = MockIdentityProvider() + mockIdentityProvider = MockIdentityProvider() let options = AuthSignInRequest.Options() @@ -152,16 +158,18 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithEmptyPassword() async { - self.mockIdentity = MockIdentity( + mockIdentity = MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -170,10 +178,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -200,7 +210,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithInvalidResult() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput() }) let options = AuthSignInRequest.Options() @@ -226,7 +236,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSecondSignInAfterSignInWithInvalidResult() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput() }) let options = AuthSignInRequest.Options() @@ -234,12 +244,13 @@ class AWSAuthSignInPluginTests: BasePluginTest { let result = try await plugin.signIn(username: "username", password: "password", options: options) XCTFail("Should not receive a success response \(result)") } catch { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -248,10 +259,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) do { @@ -274,18 +287,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithNextStepSMS() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .smsMfa, challengeParameters: [:], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -313,20 +328,22 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testCustomAuthWithAdditionalInfo() async { let clientMetadata = ["somekey": "somevalue"] - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in XCTAssertEqual(clientMetadata, input.clientMetadata) return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in XCTAssertEqual(clientMetadata, input.clientMetadata) return RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .customChallenge, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions( @@ -362,18 +379,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSMSMFAWithAdditionalInfo() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .smsMfa, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -405,18 +424,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithNextStepNewPassword() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .newPasswordRequired, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -444,18 +465,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testNewPasswordWithAdditionalInfo() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .newPasswordRequired, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -487,18 +510,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithNextStepCustomChallenge() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .customChallenge, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions(authFlowType: .customWithSRP) @@ -526,18 +551,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithNextStepUnknown() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .sdkUnknown("no idea"), challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -563,18 +590,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithNextDeviceSRP() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .deviceSrpAuth, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .devicePasswordVerifier, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions( @@ -586,7 +615,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { let result = try await plugin.signIn( username: "username", password: "password", - options: options) + options: options + ) XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service = error else { @@ -607,18 +637,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithCustomAuthIncorrectCode() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .customChallenge, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .smsMfa, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions( @@ -630,7 +662,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { let result = try await plugin.signIn( username: "username", password: "password", - options: options) + options: options + ) guard case .confirmSignInWithCustomChallenge = result.nextStep, case let confirmSignInResult = try await plugin.confirmSignIn( challengeResponse: "245234" @@ -647,18 +680,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithNextStepTOTP() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .softwareTokenMfa, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -676,18 +711,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithNextStepSelectMFAType() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .selectMfaType, challengeParameters: ["MFAS_CAN_CHOOSE": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -707,18 +744,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithNextStepSetupMFA() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"], - session: "session") + session: "session" + ) }, mockAssociateSoftwareTokenResponse: { _ in return .init(secretCode: "123456", session: "session") } ) @@ -740,18 +779,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithNextStepSetupMFAWithUnavailableMFAType() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\"]"], - session: "session") + session: "session" + ) }, mockAssociateSoftwareTokenResponse: { _ in return .init(secretCode: "123456", session: "session") } ) @@ -782,7 +823,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException() }) @@ -810,7 +851,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithInvalidLambdaResponseException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.InvalidLambdaResponseException() }) @@ -839,7 +880,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.InvalidParameterException() }) @@ -868,7 +909,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithInvalidUserPoolConfigurationException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.InvalidUserPoolConfigurationException() }) @@ -896,7 +937,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException() }) @@ -924,7 +965,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithPasswordResetRequiredException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.PasswordResetRequiredException() }) @@ -953,7 +994,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithPasswordResetRequiredException2() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.PasswordResetRequiredException() }) @@ -982,7 +1023,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithResourceNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) @@ -1011,7 +1052,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithTooManyRequestsException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.TooManyRequestsException() }) @@ -1040,7 +1081,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithUnexpectedLambdaException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.UnexpectedLambdaException() }) @@ -1069,7 +1110,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithUserLambdaValidationException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.UserLambdaValidationException() }) @@ -1097,7 +1138,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// - I should get a .confirmSignUp as next step /// func testSignInWithUserNotConfirmedException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.UserNotConfirmedException() }) @@ -1126,7 +1167,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithUserNotConfirmedException2() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.UserNotConfirmedException() }) @@ -1155,7 +1196,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithUserNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.UserNotFoundException() }) @@ -1186,12 +1227,13 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithAliasExistsException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.AliasExistsException() }) @@ -1221,12 +1263,13 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithInvalidPasswordException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidPasswordException() }) @@ -1255,18 +1298,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testRestartSignIn() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .smsMfa, challengeParameters: [:], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions(metadata: ["somekey": "somevalue"]) @@ -1279,12 +1324,13 @@ class AWSAuthSignInPluginTests: BasePluginTest { return } XCTAssertFalse(result.isSignedIn) - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -1293,10 +1339,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) let result2 = try await plugin.signIn(username: "username2", password: "password", options: options) guard case .done = result2.nextStep else { @@ -1322,22 +1370,24 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSuccessfulSignInWithFailingIdentity() async { - self.mockIdentity = MockIdentity( + mockIdentity = MockIdentity( mockGetIdResponse: { _ in throw AWSCognitoIdentity.InvalidParameterException( message: "Invalid parameter passed" ) }, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) - self.mockIdentityProvider = MockIdentityProvider(mockRevokeTokenResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockRevokeTokenResponse: { _ in RevokeTokenOutput() }, mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -1346,10 +1396,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions(metadata: ["somekey": "somevalue"]) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInTOTPTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInTOTPTaskTests.swift index 98849dce07..89551406da 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInTOTPTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInTOTPTaskTests.swift @@ -7,10 +7,10 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -25,8 +25,10 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { .apiBased(.userSRP) ), .totpMFA, - .apiBased(.userSRP))), - AuthorizationState.sessionEstablished(.testData)) + .apiBased(.userSRP) + )), + AuthorizationState.sessionEstablished(.testData) + ) } /// Test a successful confirmSignIn call with .done as next step @@ -39,7 +41,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testSuccessfulConfirmSignIn() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.challengeName, .softwareTokenMfa) XCTAssertEqual(request.challengeResponses?["SOFTWARE_TOKEN_MFA_CODE"], "code") @@ -69,7 +71,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithEmptyResponse() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in XCTFail("Cognito service should not be called") return .testData() @@ -96,7 +98,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testSuccessfullyConfirmSignInAfterAFailedConfirmSignIn() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in return .testData() }) @@ -131,10 +133,11 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { let confirmSignInOptions = AWSAuthConfirmSignInOptions( userAttributes: [.init(.email, value: "some@some.com")], - metadata: ["metadata": "test"]) + metadata: ["metadata": "test"] + ) - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { input in XCTAssertEqual(confirmSignInOptions.metadata, input.clientMetadata) XCTAssertEqual(input.challengeResponses?["userAttributes.email"], "some@some.com") @@ -144,7 +147,8 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { do { let confirmSignInResult = try await plugin.confirmSignIn( challengeResponse: "code", - options: .init(pluginOptions: confirmSignInOptions)) + options: .init(pluginOptions: confirmSignInOptions) + ) guard case .done = confirmSignInResult.nextStep else { XCTFail("Result should be .done for next step") return @@ -168,7 +172,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithAliasExistsException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.AliasExistsException( message: "Exception" @@ -200,7 +204,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// - I should get a .service error with .codeMismatch as underlyingError /// func testConfirmSignInWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -232,7 +236,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// - I should get a .service error with .codeMismatch as underlyingError /// func testConfirmSignInRetryWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -252,7 +256,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { return } - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in return .testData() }) @@ -277,7 +281,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithExpiredCodeException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.ExpiredCodeException( message: "Exception" @@ -309,7 +313,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException( message: "Exception" @@ -337,7 +341,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// - I should get a .service error with .lambda as underlyingError /// func testConfirmSignInWithInvalidLambdaResponseException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidLambdaResponseException( message: "Exception" @@ -371,7 +375,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "Exception" @@ -405,7 +409,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithInvalidPasswordException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidPasswordException( message: "Exception" @@ -437,7 +441,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// - I should get a .service error with .smsRole as underlyingError /// func testConfirmSignInWithinvalidSmsRoleAccessPolicyException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException( message: "Exception" @@ -469,7 +473,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// - I should get a .service error with .smsRole as underlyingError /// func testConfirmSignInWithInvalidSmsRoleTrustRelationshipException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException( message: "Exception" @@ -504,7 +508,8 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { let identityPoolConfigData = Defaults.makeIdentityConfigData() let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: Defaults.makeIdentity) + cognitoIdentityFactory: Defaults.makeIdentity + ) let environment = AuthEnvironment( configuration: .identityPools(identityPoolConfigData), userPoolConfigData: nil, @@ -514,8 +519,10 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { credentialsClient: Defaults.makeCredentialStoreOperationBehavior(), logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") ) - let stateMachine = Defaults.authStateMachineWith(environment: environment, - initialState: .notConfigured) + let stateMachine = Defaults.authStateMachineWith( + environment: environment, + initialState: .notConfigured + ) let plugin = AWSCognitoAuthPlugin() plugin.configure( authConfiguration: .identityPools(identityPoolConfigData), @@ -523,7 +530,8 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { authStateMachine: stateMachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) do { _ = try await plugin.confirmSignIn(challengeResponse: "code") @@ -549,7 +557,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testCofirmSignInWithMFAMethodNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.MFAMethodNotFoundException( message: "Exception" @@ -583,7 +591,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "Exception" @@ -613,7 +621,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithPasswordResetRequiredException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.PasswordResetRequiredException( message: "Exception" @@ -644,7 +652,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithSoftwareTokenMFANotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( message: "Exception" @@ -678,7 +686,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithTooManyRequestsException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.TooManyRequestsException( message: "Exception" @@ -712,7 +720,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithUnexpectedLambdaException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UnexpectedLambdaException( message: "Exception" @@ -746,7 +754,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithUserLambdaValidationException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserLambdaValidationException( message: "Exception" @@ -780,7 +788,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithUserNotConfirmedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserNotConfirmedException( message: "Exception" @@ -810,7 +818,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithUserNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserNotFoundException( message: "Exception" diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithMFASelectionTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithMFASelectionTaskTests.swift index da3e22fa6c..55033052ee 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithMFASelectionTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithMFASelectionTaskTests.swift @@ -7,10 +7,10 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -25,8 +25,10 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { .apiBased(.userSRP) ), .selectMFAType, - .apiBased(.userSRP))), - AuthorizationState.sessionEstablished(.testData)) + .apiBased(.userSRP) + )), + AuthorizationState.sessionEstablished(.testData) + ) } /// Test a successful confirmSignIn call with .confirmSignInWithSMSMFACode as next step @@ -39,7 +41,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testSuccessfulConfirmSignInWithSMSAsMFASelection() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.challengeName, .selectMfaType) @@ -71,7 +73,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testSuccessfulConfirmSignInWithTOTPAsMFASelection() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.challengeName, .selectMfaType) @@ -103,7 +105,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithInvalidMFASelection() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in XCTFail("Cognito service should not be called") return .testData() @@ -119,7 +121,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with an empty confirmation code /// @@ -131,7 +133,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithEmptyResponse() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in XCTFail("Cognito service should not be called") return .testData() @@ -158,7 +160,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testSuccessfullyConfirmSignInAfterAFailedConfirmSignIn() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in return .testData(challenge: .softwareTokenMfa) }) @@ -198,7 +200,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithAliasExistsException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.AliasExistsException( message: "Exception" @@ -230,7 +232,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// - I should get a .service error with .codeMismatch as underlyingError /// func testConfirmSignInWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -264,7 +266,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// - I invoke confirmSignIn with a valid MFA selection, I should get a successful result /// func testConfirmSignInRetryWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -284,7 +286,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { return } - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in return .testData(challenge: .softwareTokenMfa) }) @@ -313,7 +315,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithExpiredCodeException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.ExpiredCodeException( message: "Exception" @@ -345,7 +347,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException( message: "Exception" @@ -373,7 +375,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// - I should get a .service error with .lambda as underlyingError /// func testConfirmSignInWithInvalidLambdaResponseException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidLambdaResponseException( message: "Exception" @@ -407,7 +409,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "Exception" @@ -441,7 +443,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithInvalidPasswordException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidPasswordException( message: "Exception" @@ -473,7 +475,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// - I should get a .service error with .smsRole as underlyingError /// func testConfirmSignInWithinvalidSmsRoleAccessPolicyException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException( message: "Exception" @@ -505,7 +507,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// - I should get a .service error with .smsRole as underlyingError /// func testConfirmSignInWithInvalidSmsRoleTrustRelationshipException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException( message: "Exception" @@ -540,7 +542,8 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { let identityPoolConfigData = Defaults.makeIdentityConfigData() let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: Defaults.makeIdentity) + cognitoIdentityFactory: Defaults.makeIdentity + ) let environment = AuthEnvironment( configuration: .identityPools(identityPoolConfigData), userPoolConfigData: nil, @@ -550,8 +553,10 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { credentialsClient: Defaults.makeCredentialStoreOperationBehavior(), logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") ) - let stateMachine = Defaults.authStateMachineWith(environment: environment, - initialState: .notConfigured) + let stateMachine = Defaults.authStateMachineWith( + environment: environment, + initialState: .notConfigured + ) let plugin = AWSCognitoAuthPlugin() plugin.configure( authConfiguration: .identityPools(identityPoolConfigData), @@ -559,7 +564,8 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { authStateMachine: stateMachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) do { _ = try await plugin.confirmSignIn(challengeResponse: MFAType.totp.challengeResponse) @@ -585,7 +591,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testCofirmSignInWithMFAMethodNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.MFAMethodNotFoundException( message: "Exception" @@ -619,7 +625,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "Exception" @@ -649,7 +655,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithPasswordResetRequiredException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.PasswordResetRequiredException( message: "Exception" @@ -680,7 +686,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithSoftwareTokenMFANotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( message: "Exception" @@ -714,7 +720,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithTooManyRequestsException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.TooManyRequestsException( message: "Exception" @@ -748,7 +754,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithUnexpectedLambdaException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UnexpectedLambdaException( message: "Exception" @@ -782,7 +788,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithUserLambdaValidationException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserLambdaValidationException( message: "Exception" @@ -816,7 +822,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithUserNotConfirmedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserNotConfirmedException( message: "Exception" @@ -846,7 +852,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithUserNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserNotFoundException( message: "Exception" diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithSetUpMFATaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithSetUpMFATaskTests.swift index b0ab9ad69a..bc27e4a470 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithSetUpMFATaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithSetUpMFATaskTests.swift @@ -7,10 +7,10 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -23,9 +23,12 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { .waitingForAnswer(.init( secretCode: "sharedSecret", session: "session", - username: "username")), - .testData)), - AuthorizationState.sessionEstablished(.testData)) + username: "username" + )), + .testData + )), + AuthorizationState.sessionEstablished(.testData) + ) } /// Test a successful confirmSignIn call with .done as next step @@ -38,7 +41,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testSuccessfulTOTPMFASetupStep() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.session, "verifiedSession") return .testData() @@ -55,7 +58,8 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { let pluginOptions = AWSAuthConfirmSignInOptions(friendlyDeviceName: "device") let confirmSignInResult = try await plugin.confirmSignIn( challengeResponse: "123456", - options: .init(pluginOptions: pluginOptions)) + options: .init(pluginOptions: pluginOptions) + ) guard case .done = confirmSignInResult.nextStep else { XCTFail("Result should be .done for next step") return @@ -77,7 +81,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithEmptyResponse() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in XCTFail("Cognito service should not be called") return .testData() @@ -104,7 +108,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testSuccessfullyConfirmSignInAfterAFailedConfirmSignIn() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.session, "verifiedSession") return .testData() @@ -150,7 +154,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -183,9 +187,9 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// - I should get a .service error with .codeMismatch as underlyingError /// Then: /// - RETRY SHOULD ALSO SUCCEED - /// + /// func testConfirmSignInRetryWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -206,7 +210,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { return } - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.session, "verifiedSession") return .testData() @@ -237,7 +241,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InternalErrorException( message: "Exception" @@ -268,7 +272,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "Exception" @@ -303,7 +307,8 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { let identityPoolConfigData = Defaults.makeIdentityConfigData() let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: Defaults.makeIdentity) + cognitoIdentityFactory: Defaults.makeIdentity + ) let environment = AuthEnvironment( configuration: .identityPools(identityPoolConfigData), userPoolConfigData: nil, @@ -313,8 +318,10 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { credentialsClient: Defaults.makeCredentialStoreOperationBehavior(), logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") ) - let stateMachine = Defaults.authStateMachineWith(environment: environment, - initialState: .notConfigured) + let stateMachine = Defaults.authStateMachineWith( + environment: environment, + initialState: .notConfigured + ) let plugin = AWSCognitoAuthPlugin() plugin.configure( authConfiguration: .identityPools(identityPoolConfigData), @@ -322,7 +329,8 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { authStateMachine: stateMachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) do { _ = try await plugin.confirmSignIn(challengeResponse: "") @@ -348,7 +356,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "Exception" @@ -378,7 +386,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithPasswordResetRequiredException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.PasswordResetRequiredException( message: "Exception" @@ -409,7 +417,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithSoftwareTokenMFANotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( message: "Exception" @@ -443,7 +451,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithTooManyRequestsException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.TooManyRequestsException( message: "Exception" @@ -477,7 +485,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithUserNotConfirmedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.UserNotConfirmedException( message: "Exception" @@ -507,7 +515,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithUserNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.UserNotFoundException( message: "Exception" diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/SignInSetUpTOTPTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/SignInSetUpTOTPTests.swift index 65afb80f8a..9ce63aefc8 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/SignInSetUpTOTPTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/SignInSetUpTOTPTests.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentity +import AWSCognitoIdentityProvider +import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime class SignInSetUpTOTPTests: BasePluginTest { @@ -28,16 +28,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// - I should get a .continueSignInWithTOTPSetup response /// func testSuccessfulTOTPSetupChallenge() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in return .init(secretCode: "sharedSecret", session: "newSession") }) @@ -47,7 +49,8 @@ class SignInSetUpTOTPTests: BasePluginTest { let result = try await plugin.signIn( username: "username", password: "password", - options: options) + options: options + ) guard case .continueSignInWithTOTPSetup(let totpDetails) = result.nextStep else { XCTFail("Result should be .continueSignInWithTOTPSetup for next step") return @@ -62,18 +65,20 @@ class SignInSetUpTOTPTests: BasePluginTest { func testSignInWithNextStepSetupMFAWithUnavailableMFAType() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\"]"], - session: "session") + session: "session" + ) }, mockAssociateSoftwareTokenResponse: { _ in return .init(secretCode: "123456", session: "session") } ) @@ -101,16 +106,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// - I should get a .continueSignInWithTOTPSetup response /// func testSuccessfulTOTPSetupChallengeWithEmptyMFASCanSetup() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: [:]) + challengeParameters: [:] + ) }, mockAssociateSoftwareTokenResponse: { input in return .init(secretCode: "sharedSecret", session: "newSession") }) @@ -120,7 +127,8 @@ class SignInSetUpTOTPTests: BasePluginTest { _ = try await plugin.signIn( username: "username", password: "password", - options: options) + options: options + ) XCTFail("Should throw an error") } catch { guard case AuthError.service(_, _, _) = error else { @@ -142,16 +150,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithInvalidResult() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: [:]) + challengeParameters: [:] + ) }, mockAssociateSoftwareTokenResponse: { input in return .init() }) @@ -161,7 +171,8 @@ class SignInSetUpTOTPTests: BasePluginTest { _ = try await plugin.signIn( username: "username", password: "password", - options: options) + options: options + ) XCTFail("Should throw an error") } catch { guard case AuthError.service(_, _, _) = error else { @@ -182,16 +193,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSecondSignInAfterSignInWithInvalidResult() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in return .init() }) @@ -200,16 +213,18 @@ class SignInSetUpTOTPTests: BasePluginTest { let result = try await plugin.signIn(username: "username", password: "password", options: options) XCTFail("Should not receive a success response \(result)") } catch { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in return .init(secretCode: "sharedSecret", session: "newSession") }) @@ -243,16 +258,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.InternalErrorException() }) @@ -281,16 +298,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.InvalidParameterException() }) @@ -320,16 +339,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.NotAuthorizedException() }) @@ -358,16 +379,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithResourceNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) @@ -397,16 +420,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithConcurrentModificationException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.ConcurrentModificationException() }) @@ -435,16 +460,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithForbiddenException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.ForbiddenException() }) @@ -473,16 +500,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithSoftwareTokenMFANotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException() }) @@ -512,16 +541,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithUnknownAWSHttpServiceError() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSClientRuntime.UnknownAWSHTTPServiceError( httpResponse: .init(body: .empty, statusCode: .ok), diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpAPITests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpAPITests.swift index 0dea576291..3a38b8bf74 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpAPITests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpAPITests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentity -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime class AWSAuthConfirmSignUpAPITests: BasePluginTest { @@ -23,7 +23,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSuccessfulSignUp() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { request in XCTAssertNil(request.clientMetadata) XCTAssertNil(request.forceAliasCreation) @@ -31,10 +31,11 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { } ) - let result = try await self.plugin.confirmSignUp( + let result = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "123456", - options: options) + options: options + ) guard case .done = result.nextStep else { XCTFail("Result should be .done for next step") @@ -45,7 +46,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSuccessfulSignUpWithOptions() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { request in XCTAssertNotNil(request.clientMetadata) XCTAssertEqual(request.clientMetadata?["key"], "value") @@ -56,12 +57,14 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { let pluginOptions = AWSAuthConfirmSignUpOptions( metadata: ["key": "value"], - forceAliasCreation: true) + forceAliasCreation: true + ) let options = AuthConfirmSignUpRequest.Options(pluginOptions: pluginOptions) - let result = try await self.plugin.confirmSignUp( + let result = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "123456", - options: options) + options: options + ) guard case .done = result.nextStep else { XCTFail("Result should be .done for next step") @@ -72,7 +75,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSignUpWithEmptyUsername() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in XCTFail("Sign up API should not be called") return .init() @@ -80,10 +83,11 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { ) do { - let _ = try await self.plugin.confirmSignUp( + let _ = try await plugin.confirmSignUp( for: "", confirmationCode: "123456", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { @@ -96,7 +100,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSignUpWithEmptyConfirmationCode() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in XCTFail("Sign up API should not be called") return .init() @@ -104,10 +108,11 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { ) do { - let _ = try await self.plugin.confirmSignUp( + let _ = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { @@ -137,32 +142,36 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { for errorToTest in errorsToTest { await validateConfirmSignUpServiceErrors( confirmSignUpOutputError: errorToTest.confirmSignUpOutputError, - expectedCognitoError: errorToTest.cognitoError) + expectedCognitoError: errorToTest.cognitoError + ) } } func testSignUpWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException() } ) do { - let _ = try await self.plugin.confirmSignUp( + let _ = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "12345", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") return } - guard case .notAuthorized(let errorDescription, - let recoverySuggestion, - let notAuthorizedError) = authError else { + guard case .notAuthorized( + let errorDescription, + let recoverySuggestion, + let notAuthorizedError + ) = authError else { XCTFail("Auth error should be of type notAuthorized") return } @@ -175,17 +184,18 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSignUpWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException() } ) do { - let _ = try await self.plugin.confirmSignUp( + let _ = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "12345", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") @@ -203,7 +213,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSignUpWithUnknownErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in throw AWSClientRuntime.UnknownAWSHTTPServiceError.init( httpResponse: .init(body: .empty, statusCode: .accepted), @@ -215,10 +225,11 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { ) do { - let _ = try await self.plugin.confirmSignUp( + let _ = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "12345", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") @@ -236,27 +247,31 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func validateConfirmSignUpServiceErrors( confirmSignUpOutputError: Error, - expectedCognitoError: AWSCognitoAuthError) async { - self.mockIdentityProvider = MockIdentityProvider( + expectedCognitoError: AWSCognitoAuthError + ) async { + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in throw confirmSignUpOutputError } ) do { - let _ = try await self.plugin.confirmSignUp( + let _ = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "12345", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") return } - guard case .service(let errorMessage, - let recovery, - let serviceError) = authError else { + guard case .service( + let errorMessage, + let recovery, + let serviceError + ) = authError else { XCTFail("Auth error should be of type service error") return } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpTaskTests.swift index 74eed8cfb8..be9ff3f1fd 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpTaskTests.swift @@ -11,11 +11,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime import AWSCognitoIdentityProvider @@ -39,9 +39,11 @@ class AWSAuthConfirmSignUpTaskTests: XCTestCase { let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: {MockIdentityProvider(mockConfirmSignUpResponse: confirmSignUp)}) - let request = AuthConfirmSignUpRequest(username: "jeffb", - code: "213", - options: AuthConfirmSignUpRequest.Options()) + let request = AuthConfirmSignUpRequest( + username: "jeffb", + code: "213", + options: AuthConfirmSignUpRequest.Options() + ) let task = AWSAuthConfirmSignUpTask(request, authEnvironment: authEnvironment) let confirmSignUpResult = try await task.value print("Confirm Sign Up Result: \(confirmSignUpResult)") @@ -63,9 +65,11 @@ class AWSAuthConfirmSignUpTaskTests: XCTestCase { let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: {MockIdentityProvider(mockConfirmSignUpResponse: confirmSignUp)}) - let request = AuthConfirmSignUpRequest(username: "jeffb", - code: "213", - options: AuthConfirmSignUpRequest.Options()) + let request = AuthConfirmSignUpRequest( + username: "jeffb", + code: "213", + options: AuthConfirmSignUpRequest.Options() + ) do { let task = AWSAuthConfirmSignUpTask(request, authEnvironment: authEnvironment) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthResendSignUpCodeAPITests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthResendSignUpCodeAPITests.swift index 492b17f2a8..0638ff6885 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthResendSignUpCodeAPITests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthResendSignUpCodeAPITests.swift @@ -7,12 +7,12 @@ import Foundation -import XCTest import AWSCognitoIdentity -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { @@ -61,9 +61,11 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { /// func testResendSignupCodeWithSuccess() async throws { - let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType(attributeName: nil, - deliveryMedium: .email, - destination: nil) + let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType( + attributeName: nil, + deliveryMedium: .email, + destination: nil + ) mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutput: { _ in ResendConfirmationCodeOutput(codeDeliveryDetails: codeDeliveryDetails) @@ -87,9 +89,11 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { /// func testResendSignupCodeWithEmptyUsername() async throws { - let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType(attributeName: nil, - deliveryMedium: .email, - destination: nil) + let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType( + attributeName: nil, + deliveryMedium: .email, + destination: nil + ) mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutput: { _ in ResendConfirmationCodeOutput(codeDeliveryDetails: codeDeliveryDetails) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpAPITests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpAPITests.swift index bd44caa089..feec00c983 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpAPITests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpAPITests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentity -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin class AWSAuthSignUpAPITests: BasePluginTest { @@ -24,18 +24,21 @@ class AWSAuthSignUpAPITests: BasePluginTest { func testSuccessfulSignUp() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in - return .init(codeDeliveryDetails: nil, - userConfirmed: true, - userSub: UUID().uuidString) + return .init( + codeDeliveryDetails: nil, + userConfirmed: true, + userSub: UUID().uuidString + ) } ) - let result = try await self.plugin.signUp( + let result = try await plugin.signUp( username: "jeffb", password: "Valid&99", - options: options) + options: options + ) guard case .done = result.nextStep else { XCTFail("Result should be .done for next step") @@ -46,17 +49,18 @@ class AWSAuthSignUpAPITests: BasePluginTest { func testSignUpWithEmptyUsername() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in XCTFail("Sign up API should not be called") return .init(codeDeliveryDetails: nil, userConfirmed: true, userSub: nil) } ) - do { _ = try await self.plugin.signUp( + do { _ = try await plugin.signUp( username: "", password: "Valid&99", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { @@ -69,22 +73,25 @@ class AWSAuthSignUpAPITests: BasePluginTest { func testSignUpWithUserConfirmationRequired() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in return .init( codeDeliveryDetails: .init( attributeName: "some attribute", deliveryMedium: .email, - destination: "random@random.com"), + destination: "random@random.com" + ), userConfirmed: false, - userSub: "userId") + userSub: "userId" + ) } ) - let result = try await self.plugin.signUp( + let result = try await plugin.signUp( username: "jeffb", password: "Valid&99", - options: options) + options: options + ) guard case .confirmUser(let deliveryDetails, let additionalInfo, let userId) = result.nextStep else { XCTFail("Result should be .confirmUser for next step") @@ -100,19 +107,21 @@ class AWSAuthSignUpAPITests: BasePluginTest { func testSignUpNilCognitoResponse() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in return .init( codeDeliveryDetails: nil, userConfirmed: false, - userSub: nil) + userSub: nil + ) } ) - let result = try await self.plugin.signUp( + let result = try await plugin.signUp( username: "jeffb", password: "Valid&99", - options: options) + options: options + ) guard case .confirmUser(let deliveryDetails, let additionalInfo, let userId) = result.nextStep else { XCTFail("Result should be .done for next step") @@ -205,32 +214,36 @@ class AWSAuthSignUpAPITests: BasePluginTest { for errorToTest in errorsToTest { await validateSignUpServiceErrors( signUpOutputError: errorToTest.signUpOutputError, - expectedCognitoError: errorToTest.cognitoError) + expectedCognitoError: errorToTest.cognitoError + ) } } func testSignUpWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException() } ) do { - _ = try await self.plugin.signUp( + _ = try await plugin.signUp( username: "username", password: "Valid&99", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") return } - guard case .notAuthorized(let errorDescription, - let recoverySuggestion, - let notAuthorizedError) = authError else { + guard case .notAuthorized( + let errorDescription, + let recoverySuggestion, + let notAuthorizedError + ) = authError else { XCTFail("Auth error should be of type notAuthorized") return } @@ -243,17 +256,18 @@ class AWSAuthSignUpAPITests: BasePluginTest { func testSignUpWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException() } ) do { - _ = try await self.plugin.signUp( + _ = try await plugin.signUp( username: "username", password: "Valid&99", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") @@ -271,27 +285,31 @@ class AWSAuthSignUpAPITests: BasePluginTest { func validateSignUpServiceErrors( signUpOutputError: Error, - expectedCognitoError: AWSCognitoAuthError) async { - self.mockIdentityProvider = MockIdentityProvider( + expectedCognitoError: AWSCognitoAuthError + ) async { + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in throw signUpOutputError } ) do { - _ = try await self.plugin.signUp( + _ = try await plugin.signUp( username: "username", password: "Valid&99", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") return } - guard case .service(let errorMessage, - let recovery, - let serviceError) = authError else { + guard case .service( + let errorMessage, + let recovery, + let serviceError + ) = authError else { XCTFail("Auth error should be of type service error") return } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpTaskTests.swift index b2192c1357..98a123ab78 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpTaskTests.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime import AWSCognitoIdentityProvider @@ -34,9 +34,11 @@ class AWSAuthSignUpTaskTests: XCTestCase { return .init(codeDeliveryDetails: nil, userConfirmed: true, userSub: UUID().uuidString) } - let request = AuthSignUpRequest(username: "jeffb", - password: "Valid&99", - options: AuthSignUpRequest.Options()) + let request = AuthSignUpRequest( + username: "jeffb", + password: "Valid&99", + options: AuthSignUpRequest.Options() + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: {MockIdentityProvider(mockSignUpResponse: signUp)}) let task = AWSAuthSignUpTask(request, authEnvironment: authEnvironment) @@ -58,9 +60,11 @@ class AWSAuthSignUpTaskTests: XCTestCase { ) } - let request = AuthSignUpRequest(username: "jeffb", - password: "Valid&99", - options: AuthSignUpRequest.Options()) + let request = AuthSignUpRequest( + username: "jeffb", + password: "Valid&99", + options: AuthSignUpRequest.Options() + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: {MockIdentityProvider(mockSignUpResponse: signUp)}) @@ -85,9 +89,11 @@ class AWSAuthSignUpTaskTests: XCTestCase { return .init(codeDeliveryDetails: nil, userConfirmed: true, userSub: UUID().uuidString) } - let request = AuthSignUpRequest(username: "jeffb", - password: "Valid&99", - options: AuthSignUpRequest.Options()) + let request = AuthSignUpRequest( + username: "jeffb", + password: "Valid&99", + options: AuthSignUpRequest.Options() + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: {MockIdentityProvider(mockSignUpResponse: signUp)}) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorFetchDevicesTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorFetchDevicesTests.swift index a0606fdac9..1a754293b0 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorFetchDevicesTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorFetchDevicesTests.swift @@ -7,12 +7,12 @@ import Foundation -import XCTest -import AWSCognitoIdentityProvider import Amplify +import AWSCognitoIdentityProvider +import ClientRuntime +import XCTest @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime class DeviceBehaviorFetchDevicesTests: BasePluginTest { @@ -85,7 +85,8 @@ class DeviceBehaviorFetchDevicesTests: BasePluginTest { deviceLastAuthenticatedDate: dateToTest, deviceLastModifiedDate: dateToTest ) - ], paginationToken: nil) + ], paginationToken: nil + ) } ) let listDevicesResult = try await plugin.fetchDevices() diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorForgetDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorForgetDeviceTests.swift index 2bceafa709..a32cac81e4 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorForgetDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorForgetDeviceTests.swift @@ -7,12 +7,12 @@ import Foundation -import XCTest -import AWSCognitoIdentityProvider import Amplify +import AWSCognitoIdentityProvider +import ClientRuntime +import XCTest @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime class DeviceBehaviorForgetDeviceTests: BasePluginTest { @@ -47,12 +47,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { /// func testSuccessfulForgetDevice() async throws { - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) } @@ -108,12 +110,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error") @@ -147,7 +151,8 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { XCTFail("Should return an error if the result from service is invalid") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .invalidParameter = (underlyingError as? AWSCognitoAuthError) else { + case .invalidParameter = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Underlying error should be invalidParameter \(error)") return } @@ -173,18 +178,21 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .invalidParameter = (underlyingError as? AWSCognitoAuthError) else { + case .invalidParameter = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Underlying error should be invalidParameter \(error)") return } @@ -240,12 +248,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") @@ -306,12 +316,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") @@ -376,12 +388,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") @@ -450,12 +464,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") @@ -524,12 +540,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") @@ -598,12 +616,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") @@ -672,12 +692,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorRememberDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorRememberDeviceTests.swift index b0d262be4c..de13118590 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorRememberDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorRememberDeviceTests.swift @@ -7,12 +7,12 @@ import Foundation -import XCTest -import AWSCognitoIdentityProvider import Amplify +import AWSCognitoIdentityProvider +import ClientRuntime +import XCTest @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime class DeviceBehaviorRememberDeviceTests: BasePluginTest { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/HostedUITests/AWSAuthHostedUISignInTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/HostedUITests/AWSAuthHostedUISignInTests.swift index 7ce5a0b15c..e38441aea2 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/HostedUITests/AWSAuthHostedUISignInTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/HostedUITests/AWSAuthHostedUISignInTests.swift @@ -8,11 +8,11 @@ #if os(iOS) || os(macOS) import Foundation +import AuthenticationServices +import AWSCognitoIdentityProvider import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AuthenticationServices -import AWSCognitoIdentityProvider class AWSAuthHostedUISignInTests: XCTestCase { @@ -20,10 +20,12 @@ class AWSAuthHostedUISignInTests: XCTestCase { let networkTimeout = TimeInterval(5) var mockIdentityProvider: CognitoUserPoolBehavior! var mockHostedUIResult: Result<[URLQueryItem], HostedUIError>! - var mockTokenResult = ["id_token": AWSCognitoUserPoolTokens.testData.idToken, - "access_token": AWSCognitoUserPoolTokens.testData.accessToken, - "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken, - "expires_in": 10] as [String: Any] + var mockTokenResult = [ + "id_token": AWSCognitoUserPoolTokens.testData.idToken, + "access_token": AWSCognitoUserPoolTokens.testData.accessToken, + "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken, + "expires_in": 10 + ] as [String: Any] var mockState = "someState" var mockProof = "someProof" var mockJson: Data! @@ -56,13 +58,16 @@ class AWSAuthHostedUISignInTests: XCTestCase { return MockRandomStringGenerator(mockString: mockState, mockUUID: mockState) } - let environment = BasicHostedUIEnvironment(configuration: cusotmConfiguration ?? configuration, - hostedUISessionFactory: sessionFactory, - urlSessionFactory: urlSessionMock, - randomStringFactory: mockRandomString) + let environment = BasicHostedUIEnvironment( + configuration: cusotmConfiguration ?? configuration, + hostedUISessionFactory: sessionFactory, + urlSessionFactory: urlSessionMock, + randomStringFactory: mockRandomString + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: { self.mockIdentityProvider }, - hostedUIEnvironment: environment) + hostedUIEnvironment: environment + ) let stateMachine = Defaults.authStateMachineWith( environment: authEnvironment, initialState: initialState @@ -74,7 +79,8 @@ class AWSAuthHostedUISignInTests: XCTestCase { authStateMachine: stateMachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) return plugin } @@ -93,13 +99,16 @@ class AWSAuthHostedUISignInTests: XCTestCase { return MockRandomStringGenerator(mockString: mockState, mockUUID: mockState) } - let environment = BasicHostedUIEnvironment(configuration: configuration, - hostedUISessionFactory: sessionFactory, - urlSessionFactory: urlSessionMock, - randomStringFactory: mockRandomString) + let environment = BasicHostedUIEnvironment( + configuration: configuration, + hostedUISessionFactory: sessionFactory, + urlSessionFactory: urlSessionMock, + randomStringFactory: mockRandomString + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: { self.mockIdentityProvider }, - hostedUIEnvironment: environment) + hostedUIEnvironment: environment + ) let stateMachine = Defaults.authStateMachineWith( environment: authEnvironment, initialState: initialState @@ -111,7 +120,8 @@ class AWSAuthHostedUISignInTests: XCTestCase { authStateMachine: stateMachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) } @MainActor @@ -126,9 +136,11 @@ class AWSAuthHostedUISignInTests: XCTestCase { @MainActor func testSuccessfulSignIn_missingExpiresIn() async throws { - mockTokenResult = ["id_token": AWSCognitoUserPoolTokens.testData.idToken, - "access_token": AWSCognitoUserPoolTokens.testData.accessToken, - "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken] as [String: Any] + mockTokenResult = [ + "id_token": AWSCognitoUserPoolTokens.testData.idToken, + "access_token": AWSCognitoUserPoolTokens.testData.accessToken, + "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken + ] as [String: Any] mockJson = try! JSONSerialization.data(withJSONObject: mockTokenResult) MockURLProtocol.requestHandler = { _ in return (HTTPURLResponse(), self.mockJson) @@ -144,9 +156,11 @@ class AWSAuthHostedUISignInTests: XCTestCase { @MainActor func testSuccessfulSignIn_missingExpiresIn_testTokenMissingExp() async throws { - mockTokenResult = ["id_token": AWSCognitoUserPoolTokens.testDataWithoutExp.idToken, - "access_token": AWSCognitoUserPoolTokens.testData.accessToken, - "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken] as [String: Any] + mockTokenResult = [ + "id_token": AWSCognitoUserPoolTokens.testDataWithoutExp.idToken, + "access_token": AWSCognitoUserPoolTokens.testData.accessToken, + "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken + ] as [String: Any] mockJson = try! JSONSerialization.data(withJSONObject: mockTokenResult) MockURLProtocol.requestHandler = { _ in return (HTTPURLResponse(), self.mockJson) @@ -162,9 +176,11 @@ class AWSAuthHostedUISignInTests: XCTestCase { @MainActor func testSuccessfulSignIn_missingExpiresIn_testBothTokenMissingExp() async throws { - mockTokenResult = ["id_token": AWSCognitoUserPoolTokens.testDataWithoutExp.idToken, - "access_token": AWSCognitoUserPoolTokens.testDataWithoutExp.accessToken, - "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken] as [String: Any] + mockTokenResult = [ + "id_token": AWSCognitoUserPoolTokens.testDataWithoutExp.idToken, + "access_token": AWSCognitoUserPoolTokens.testDataWithoutExp.accessToken, + "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken + ] as [String: Any] mockJson = try! JSONSerialization.data(withJSONObject: mockTokenResult) MockURLProtocol.requestHandler = { _ in return (HTTPURLResponse(), self.mockJson) @@ -187,7 +203,8 @@ class AWSAuthHostedUISignInTests: XCTestCase { XCTFail("Should not succeed") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .userCancelled = (underlyingError as? AWSCognitoAuthError) else { + case .userCancelled = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should not fail with error = \(error)") return } @@ -205,7 +222,8 @@ class AWSAuthHostedUISignInTests: XCTestCase { XCTFail("Should not succeed") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .userCancelled = (underlyingError as? AWSCognitoAuthError) else { + case .userCancelled = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should not fail with error = \(error)") return } @@ -289,7 +307,8 @@ class AWSAuthHostedUISignInTests: XCTestCase { ]) mockTokenResult = [ "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken, - "expires_in": 10] as [String: Any] + "expires_in": 10 + ] as [String: Any] mockJson = try! JSONSerialization.data(withJSONObject: mockTokenResult) MockURLProtocol.requestHandler = { _ in return (HTTPURLResponse(), self.mockJson) @@ -361,7 +380,8 @@ class AWSAuthHostedUISignInTests: XCTestCase { ]) mockTokenResult = [ "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken, - "expires_in": 10] as [String: Any] + "expires_in": 10 + ] as [String: Any] mockJson = try! JSONSerialization.data(withJSONObject: mockTokenResult) MockURLProtocol.requestHandler = { _ in return (HTTPURLResponse(), self.mockJson) @@ -395,18 +415,20 @@ class AWSAuthHostedUISignInTests: XCTestCase { @MainActor func testRestartSignInWithWebUI() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .smsMfa, challengeParameters: [:], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions(metadata: ["somekey": "somevalue"]) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/AWSCognitoAuthUserBehaviorTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/AWSCognitoAuthUserBehaviorTests.swift index b317ebfeca..b6c0a87055 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/AWSCognitoAuthUserBehaviorTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/AWSCognitoAuthUserBehaviorTests.swift @@ -7,10 +7,10 @@ import Foundation +import AWSCognitoIdentityProvider import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider class AWSCognitoAuthUserBehaviorTests: BasePluginTest { @@ -150,7 +150,8 @@ class AWSCognitoAuthUserBehaviorTests: BasePluginTest { codeDeliveryDetails: .init( attributeName: "attributeName", deliveryMedium: .email, - destination: "destination")) + destination: "destination" + )) }) let pluginOptions = AWSSendUserAttributeVerificationCodeOptions(metadata: ["key": "value"]) let options = AuthSendUserAttributeVerificationCodeRequest.Options(pluginOptions: pluginOptions) @@ -174,7 +175,8 @@ class AWSCognitoAuthUserBehaviorTests: BasePluginTest { codeDeliveryDetails: .init( attributeName: "attributeName", deliveryMedium: .email, - destination: "destination")) + destination: "destination" + )) }) let pluginOptions = AWSSendUserAttributeVerificationCodeOptions(metadata: ["key": "value"]) let options = AuthSendUserAttributeVerificationCodeRequest.Options(pluginOptions: pluginOptions) @@ -195,7 +197,8 @@ class AWSCognitoAuthUserBehaviorTests: BasePluginTest { codeDeliveryDetails: .init( attributeName: "attributeName", deliveryMedium: .email, - destination: "destination")) + destination: "destination" + )) }) _ = try await plugin.sendVerificationCode(forUserAttributeKey: .email) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/BasePluginTest.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/BasePluginTest.swift index ea6171b1b9..7c2accbc8b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/BasePluginTest.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/BasePluginTest.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentity +import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin @@ -14,11 +14,10 @@ class BasePluginTest: XCTestCase { let apiTimeout = 2.0 var mockIdentityProvider: CognitoUserPoolBehavior! - lazy var mockIdentity: CognitoIdentityBehavior = { - MockIdentity( - mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) - }() + lazy var mockIdentity: CognitoIdentityBehavior = MockIdentity( + mockGetIdResponse: getId, + mockGetCredentialsResponse: getCredentials + ) var plugin: AWSCognitoAuthPlugin! let getId: MockIdentity.MockGetIdResponse = { _ in @@ -26,20 +25,25 @@ class BasePluginTest: XCTestCase { } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } var initialState: AuthState { AuthState.configured( AuthenticationState.signedIn( - SignedInData(signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData)), - AuthorizationState.sessionEstablished(AmplifyCredentials.testData)) + SignedInData( + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData + )), + AuthorizationState.sessionEstablished(AmplifyCredentials.testData) + ) } override func setUp() { @@ -47,12 +51,14 @@ class BasePluginTest: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: { self.mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) let statemachine = Defaults.makeDefaultAuthStateMachine( initialState: initialState, identityPoolFactory: { self.mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) plugin?.configure( authConfiguration: Defaults.makeDefaultAuthConfigData(), @@ -60,28 +66,34 @@ class BasePluginTest: XCTestCase { authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) } func configureCustomPluginWith( authConfiguration: AuthConfiguration = Defaults.makeDefaultAuthConfigData(), userPool: @escaping () throws -> CognitoUserPoolBehavior = Defaults.makeDefaultUserPool, identityPool: @escaping () throws -> CognitoIdentityBehavior = Defaults.makeIdentity, - initialState: AuthState) -> AWSCognitoAuthPlugin { + initialState: AuthState + ) -> AWSCognitoAuthPlugin { let plugin = AWSCognitoAuthPlugin() let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: identityPool, - userPoolFactory: userPool) - let statemachine = AuthStateMachine(resolver: AuthState.Resolver(), - environment: environment, - initialState: initialState) + userPoolFactory: userPool + ) + let statemachine = AuthStateMachine( + resolver: AuthState.Resolver(), + environment: environment, + initialState: initialState + ) plugin.configure( authConfiguration: Defaults.makeDefaultAuthConfigData(), authEnvironment: environment, authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) return plugin } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/SendUserAttributeVerificationCodeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/SendUserAttributeVerificationCodeTests.swift index 6271cafa3e..7e9c03b937 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/SendUserAttributeVerificationCodeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/SendUserAttributeVerificationCodeTests.swift @@ -7,11 +7,11 @@ import Foundation +import AWSCognitoIdentityProvider +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import ClientRuntime class SendUserAttributeVerificationCodeTests: BasePluginTest { @@ -30,7 +30,8 @@ class SendUserAttributeVerificationCodeTests: BasePluginTest { codeDeliveryDetails: .init( attributeName: "attributeName", deliveryMedium: .email, - destination: "destination")) + destination: "destination" + )) }) let attribute = try await plugin.sendVerificationCode(forUserAttributeKey: .email) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorChangePasswordTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorChangePasswordTests.swift index 7ce3db71ac..09278a9e9f 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorChangePasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorChangePasswordTests.swift @@ -7,11 +7,11 @@ import Foundation +import AWSCognitoIdentityProvider +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import ClientRuntime class UserBehaviorChangePasswordTests: BasePluginTest { @@ -24,7 +24,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// - I should get a successful result /// func testSuccessfulChangePassword() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in return ChangePasswordOutput() }) try await plugin.update(oldPassword: "old password", to: "new password") @@ -40,7 +40,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithInternalErrorException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.InternalErrorException( message: "internal error exception" ) @@ -68,7 +68,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithInvalidParameterException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "invalid parameter exception" ) @@ -100,7 +100,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithInvalidPasswordException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.InvalidPasswordException( message: "invalid password exception" ) @@ -132,7 +132,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithLimitExceededException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.LimitExceededException() }) do { @@ -162,7 +162,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithNotAuthorizedException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "not authorized exception" ) @@ -190,7 +190,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithPasswordResetRequiredException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.PasswordResetRequiredException( message: "password reset required exception" ) @@ -222,7 +222,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithResourceNotFoundException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.ResourceNotFoundException( message: "resource not found exception" ) @@ -254,7 +254,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithTooManyRequestsException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.TooManyRequestsException( message: "too many requests exception" ) @@ -286,7 +286,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithUserNotConfirmedException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.UserNotConfirmedException( message: "user not confirmed exception" ) @@ -318,7 +318,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithUserNotFoundException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.UserNotFoundException( message: "user not found exception" ) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorConfirmAttributeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorConfirmAttributeTests.swift index 0a9974552e..60a8512785 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorConfirmAttributeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorConfirmAttributeTests.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoIdentityProvider +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import ClientRuntime class UserBehaviorConfirmAttributeTests: BasePluginTest { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorFetchAttributeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorFetchAttributeTests.swift index a34aa32bc9..929afd1091 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorFetchAttributeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorFetchAttributeTests.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoIdentityProvider +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import ClientRuntime @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime class UserBehaviorFetchAttributesTests: BasePluginTest { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorUpdateAttributeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorUpdateAttributeTests.swift index 8df4a55b47..9d1e103ab0 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorUpdateAttributeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorUpdateAttributeTests.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoIdentityProvider +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import ClientRuntime @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime class UserBehaviorUpdateAttributesTests: BasePluginTest { @@ -26,9 +26,12 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in UpdateUserAttributesOutput(codeDeliveryDetailsList: [ - .init(attributeName: "attributeName", - deliveryMedium: .email, - destination: "destination")]) + .init( + attributeName: "attributeName", + deliveryMedium: .email, + destination: "destination" + ) + ]) }) let attributes = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAPIDecoding/TestHarnessAPIDecoder.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAPIDecoding/TestHarnessAPIDecoder.swift index e5ffca104e..5faf265dae 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAPIDecoding/TestHarnessAPIDecoder.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAPIDecoding/TestHarnessAPIDecoder.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // +import Foundation @testable import Amplify @testable import AWSCognitoAuthPlugin -import Foundation -struct TestHarnessAPIDecoder { +enum TestHarnessAPIDecoder { static func decode( specification: FeatureSpecification) -> AmplifyAPI { @@ -40,32 +40,38 @@ struct TestHarnessAPIDecoder { return signInAPI( params: specification.api.params, responseType: responseType, - data: data) + data: data + ) case .signUp: return signUpAPI( params: specification.api.params, responseType: responseType, - data: data) + data: data + ) case .deleteUser: return deleteUserAPI( params: specification.api.params, responseType: responseType, - data: data) + data: data + ) case .confirmSignIn: return confirmSignInAPI( params: specification.api.params, responseType: responseType, - data: data) + data: data + ) case .fetchAuthSession: return fetchAuthSession( params: specification.api.params, responseType: responseType, - data: data) + data: data + ) case .signOut: return signOutApi( options: specification.api.options, responseType: responseType, - data: data) + data: data + ) default: fatalError() } @@ -86,8 +92,10 @@ struct TestHarnessAPIDecoder { return .signIn( input: .init( username: username, - password: inputPassword, options: .init()), - expectedOutput: generateResult(responseType: responseType, data: data)) + password: inputPassword, options: .init() + ), + expectedOutput: generateResult(responseType: responseType, data: data) + ) } private static func signUpAPI( @@ -105,8 +113,10 @@ struct TestHarnessAPIDecoder { return .signUp( input: .init( username: username, - password: inputPassword, options: .init()), - expectedOutput: generateResult(responseType: responseType, data: data)) + password: inputPassword, options: .init() + ), + expectedOutput: generateResult(responseType: responseType, data: data) + ) } private static func resetPasswordAPI( @@ -118,9 +128,12 @@ struct TestHarnessAPIDecoder { fatalError("missing username parameter") } return .resetPassword( - input: .init(username: username, - options: .init()), - expectedOutput: generateResult(responseType: responseType, data: data)) + input: .init( + username: username, + options: .init() + ), + expectedOutput: generateResult(responseType: responseType, data: data) + ) } private static func confirmSignInAPI( @@ -133,7 +146,8 @@ struct TestHarnessAPIDecoder { } return .confirmSignIn( input: .init(challengeResponse: challengeResponse, options: .init()), - expectedOutput: generateResult(responseType: responseType, data: data)) + expectedOutput: generateResult(responseType: responseType, data: data) + ) } private static func fetchAuthSession( @@ -143,11 +157,13 @@ struct TestHarnessAPIDecoder { ) -> AmplifyAPI { let result: Result? = generateResult( - responseType: responseType, data: data) + responseType: responseType, data: data + ) return .fetchAuthSession( input: .init(options: .init()), - expectedOutput: result) + expectedOutput: result + ) } private static func signOutApi( @@ -162,11 +178,13 @@ struct TestHarnessAPIDecoder { } let result: Result? = generateResult( - responseType: responseType, data: data) + responseType: responseType, data: data + ) return .signOut( input: .init(options: .init(globalSignOut: globalSignOut)), - expectedOutput: result) + expectedOutput: result + ) } private static func deleteUserAPI( @@ -175,10 +193,11 @@ struct TestHarnessAPIDecoder { data: Data? ) -> AmplifyAPI { - guard let responseType = responseType, let data = data else { + guard let responseType, let data else { return .deleteUser( input: (), - expectedOutput: nil) + expectedOutput: nil + ) } let result: Result @@ -186,7 +205,8 @@ struct TestHarnessAPIDecoder { switch responseType { case "failure": let authError = try! JSONDecoder().decode( - AuthError.self, from: data) + AuthError.self, from: data + ) result = .failure(authError) case "success": result = .success(()) @@ -195,13 +215,15 @@ struct TestHarnessAPIDecoder { } return .deleteUser( input: (), - expectedOutput: result) + expectedOutput: result + ) } private static func generateResult( - responseType: String?, data: Data?) -> Result? { + responseType: String?, data: Data? + ) -> Result? { - guard let responseType = responseType, let data = data else { + guard let responseType, let data else { return nil } @@ -210,11 +232,13 @@ struct TestHarnessAPIDecoder { switch responseType { case "failure": let authError = try! JSONDecoder().decode( - AuthError.self, from: data) + AuthError.self, from: data + ) result = .failure(authError) case "success": let output = try! JSONDecoder().decode( - Output.self, from: data) + Output.self, from: data + ) result = .success(output) default: fatalError("invalid response type") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift index eef6bf85c1..01eacb3b28 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoIdentityProvider import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider class AmplifyAuthCognitoPluginTests: XCTestCase { @@ -42,32 +42,44 @@ class AmplifyAuthCognitoPluginTests: XCTestCase { func beginTest( for plugin: AWSCognitoAuthPlugin, - with testHarness: AuthTestHarness) async { + with testHarness: AuthTestHarness + ) async { switch testHarness.apiUnderTest { - case .resetPassword(let resetPasswordRequest, - let expectedOutput): + case .resetPassword( + let resetPasswordRequest, + let expectedOutput + ): await validateAPI(expectedOutput: expectedOutput) { return try await plugin.resetPassword( for: resetPasswordRequest.username, - options: resetPasswordRequest.options) + options: resetPasswordRequest.options + ) } - case .signUp(let signUpRequest, - let expectedOutput): + case .signUp( + let signUpRequest, + let expectedOutput + ): await validateAPI(expectedOutput: expectedOutput) { return try await plugin.signUp( username: signUpRequest.username, - password: signUpRequest.password, options: signUpRequest.options) + password: signUpRequest.password, options: signUpRequest.options + ) } - case .signIn(let request, - let expectedOutput): + case .signIn( + let request, + let expectedOutput + ): await validateAPI(expectedOutput: expectedOutput) { return try await plugin.signIn( username: request.username, - password: request.password, options: request.options) + password: request.password, options: request.options + ) } - case .fetchAuthSession(let request, - let expectedOutput): + case .fetchAuthSession( + let request, + let expectedOutput + ): await validateAPI(expectedOutput: expectedOutput) { return try await plugin.fetchAuthSession(options: request.options) as! AWSAuthCognitoSession } @@ -96,17 +108,19 @@ class AmplifyAuthCognitoPluginTests: XCTestCase { case .confirmSignIn(let request, expectedOutput: let expectedOutput): await validateAPI(expectedOutput: expectedOutput) { return try await plugin.confirmSignIn( - challengeResponse: request.challengeResponse, options: request.options) + challengeResponse: request.challengeResponse, options: request.options + ) } } } - + // Helper to validate API Result func validateAPI( expectedOutput: Result?, - apiCall: @escaping () async throws -> T) async { + apiCall: @escaping () async throws -> T + ) async { let expectation = expectation(description: "expectation") do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ChangePasswordInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ChangePasswordInput+Codable.swift index aaf462cfc7..549981032a 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ChangePasswordInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ChangePasswordInput+Codable.swift @@ -27,7 +27,8 @@ extension ChangePasswordInput: Decodable { self.init( accessToken: accessTokenDecoded, previousPassword: previousPasswordDecoded, - proposedPassword: proposedPasswordDecoded) + proposedPassword: proposedPasswordDecoded + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ConfirmDeviceInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ConfirmDeviceInput+Codable.swift index 8ca5db107f..ee926761e5 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ConfirmDeviceInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ConfirmDeviceInput+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider import ClientRuntime extension ConfirmDeviceInput: Decodable { @@ -33,7 +33,8 @@ extension ConfirmDeviceInput: Decodable { deviceName: deviceName, deviceSecretVerifierConfig: .init( passwordVerifier: passwordVerifier, - salt: salt) + salt: salt + ) ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ForgotPasswordInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ForgotPasswordInput+Codable.swift index 457096b9a0..9eeca91844 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ForgotPasswordInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ForgotPasswordInput+Codable.swift @@ -24,7 +24,8 @@ extension ForgotPasswordInput: Decodable { self.init( clientId: clientId, clientMetadata: clientMetadata, - username: username) + username: username + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetCredentialsForIdentityInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetCredentialsForIdentityInput+Codable.swift index 1b8cfcab72..d9eb4a09b6 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetCredentialsForIdentityInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetCredentialsForIdentityInput+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider import ClientRuntime extension GetCredentialsForIdentityInput: Decodable { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetIdInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetIdInput+Codable.swift index 992ac9ea7a..6dd40e1a95 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetIdInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetIdInput+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider import ClientRuntime extension GetIdInput: Decodable { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/InitiateAuthInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/InitiateAuthInput+Codable.swift index 6aca69ede1..ac6413eb42 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/InitiateAuthInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/InitiateAuthInput+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider import ClientRuntime extension InitiateAuthInput: Decodable { @@ -27,7 +27,8 @@ extension InitiateAuthInput: Decodable { authFlow: authFlow, authParameters: authParameters, clientId: clientId, - clientMetadata: clientMetadata) + clientMetadata: clientMetadata + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/RevokeTokenInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/RevokeTokenInput+Codable.swift index f98185a19a..5235a793db 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/RevokeTokenInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/RevokeTokenInput+Codable.swift @@ -24,7 +24,8 @@ extension RevokeTokenInput: Decodable { self.init( clientId: clientId, clientSecret: clientSecret, - token: token) + token: token + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ChangePasswordOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ChangePasswordOutputResponse+Codable.swift index a0cc62c640..466ffb3f9a 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ChangePasswordOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ChangePasswordOutputResponse+Codable.swift @@ -11,7 +11,7 @@ import SmithyHTTPAPI extension ChangePasswordOutput: Codable { enum CodingKeys: String, CodingKey { - case httpResponse = "httpResponse" + case httpResponse } public init(from decoder: Decoder) throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ConfirmDeviceOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ConfirmDeviceOutputResponse+Codable.swift index 2cb298d4a5..618b596846 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ConfirmDeviceOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ConfirmDeviceOutputResponse+Codable.swift @@ -14,7 +14,7 @@ extension ConfirmDeviceOutput: Codable { case userConfirmationNecessary = "UserConfirmationNecessary" } - public init (from decoder: Swift.Decoder) throws { + public init(from decoder: Swift.Decoder) throws { self.init() let containerValues = try decoder.container(keyedBy: CodingKeys.self) let userConfirmationNecessaryDecoded = try containerValues.decode(Swift.Bool.self, forKey: .userConfirmationNecessary) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetCredentialsForIdentityOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetCredentialsForIdentityOutputResponse+Codable.swift index c602cf7108..dcb2ac0a86 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetCredentialsForIdentityOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetCredentialsForIdentityOutputResponse+Codable.swift @@ -14,7 +14,7 @@ extension GetCredentialsForIdentityOutput: Codable { case identityId = "IdentityId" } - public init (from decoder: Swift.Decoder) throws { + public init(from decoder: Swift.Decoder) throws { self.init() let containerValues = try decoder.container(keyedBy: CodingKeys.self) let identityIdDecoded = try containerValues.decodeIfPresent(Swift.String.self, forKey: .identityId) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetIdOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetIdOutputResponse+Codable.swift index 2180ce9402..e9bfb0904e 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetIdOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetIdOutputResponse+Codable.swift @@ -13,7 +13,7 @@ extension GetIdOutput: Codable { case identityId = "IdentityId" } - public init (from decoder: Swift.Decoder) throws { + public init(from decoder: Swift.Decoder) throws { self.init() let containerValues = try decoder.container(keyedBy: CodingKeys.self) let identityIdDecoded = try containerValues.decodeIfPresent(Swift.String.self, forKey: .identityId) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/HttpResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/HttpResponse+Codable.swift index f185186f5b..9fd654c597 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/HttpResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/HttpResponse+Codable.swift @@ -11,20 +11,20 @@ import SmithyHTTPAPI extension SmithyHTTPAPI.HTTPResponse: Codable { } enum HTTPResponseCodingKeys: String, CodingKey { - case statusCode = "statusCode" + case statusCode } -extension Encodable where Self: SmithyHTTPAPI.HTTPResponse { +public extension Encodable where Self: SmithyHTTPAPI.HTTPResponse { - public func encode(to encoder: Encoder) throws { + func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: HTTPResponseCodingKeys.self) try container.encode(statusCode.rawValue, forKey: .statusCode) } } -extension Decodable where Self: SmithyHTTPAPI.HTTPResponse { +public extension Decodable where Self: SmithyHTTPAPI.HTTPResponse { - public init(from decoder: Decoder) throws { + init(from decoder: Decoder) throws { let containerValues = try decoder.container(keyedBy: HTTPResponseCodingKeys.self) let httpStatusCode = try containerValues.decodeIfPresent(Int.self, forKey: .statusCode) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/InitiateAuthOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/InitiateAuthOutputResponse+Codable.swift index 155fd62081..cd6c80b822 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/InitiateAuthOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/InitiateAuthOutputResponse+Codable.swift @@ -17,7 +17,7 @@ extension InitiateAuthOutput: Codable { case session = "Session" } - public init (from decoder: Swift.Decoder) throws { + public init(from decoder: Swift.Decoder) throws { self.init() let containerValues = try decoder.container(keyedBy: CodingKeys.self) let challengeNameDecoded = try containerValues.decodeIfPresent(CognitoIdentityProviderClientTypes.ChallengeNameType.self, forKey: .challengeName) @@ -25,11 +25,11 @@ extension InitiateAuthOutput: Codable { let sessionDecoded = try containerValues.decodeIfPresent(Swift.String.self, forKey: .session) session = sessionDecoded let challengeParametersContainer = try containerValues.decodeIfPresent([Swift.String: Swift.String?].self, forKey: .challengeParameters) - var challengeParametersDecoded0: [Swift.String:Swift.String]? = nil - if let challengeParametersContainer = challengeParametersContainer { - challengeParametersDecoded0 = [Swift.String:Swift.String]() + var challengeParametersDecoded0: [Swift.String: Swift.String]? = nil + if let challengeParametersContainer { + challengeParametersDecoded0 = [Swift.String: Swift.String]() for (key0, stringtype0) in challengeParametersContainer { - if let stringtype0 = stringtype0 { + if let stringtype0 { challengeParametersDecoded0?[key0] = stringtype0 } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/RespondToAuthChallengeOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/RespondToAuthChallengeOutputResponse+Codable.swift index 692887ad89..696282db3f 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/RespondToAuthChallengeOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/RespondToAuthChallengeOutputResponse+Codable.swift @@ -16,7 +16,7 @@ extension RespondToAuthChallengeOutput: Codable { case session = "Session" } - public init (from decoder: Swift.Decoder) throws { + public init(from decoder: Swift.Decoder) throws { self.init() let containerValues = try decoder.container(keyedBy: CodingKeys.self) let challengeNameDecoded = try containerValues.decodeIfPresent(CognitoIdentityProviderClientTypes.ChallengeNameType.self, forKey: .challengeName) @@ -24,11 +24,11 @@ extension RespondToAuthChallengeOutput: Codable { let sessionDecoded = try containerValues.decodeIfPresent(Swift.String.self, forKey: .session) session = sessionDecoded let challengeParametersContainer = try containerValues.decodeIfPresent([Swift.String: Swift.String?].self, forKey: .challengeParameters) - var challengeParametersDecoded0: [Swift.String:Swift.String]? = nil - if let challengeParametersContainer = challengeParametersContainer { - challengeParametersDecoded0 = [Swift.String:Swift.String]() + var challengeParametersDecoded0: [Swift.String: Swift.String]? = nil + if let challengeParametersContainer { + challengeParametersDecoded0 = [Swift.String: Swift.String]() for (key0, stringtype0) in challengeParametersContainer { - if let stringtype0 = stringtype0 { + if let stringtype0 { challengeParametersDecoded0?[key0] = stringtype0 } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/SignUpOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/SignUpOutputResponse+Codable.swift index e6f9255302..202138a402 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/SignUpOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/SignUpOutputResponse+Codable.swift @@ -15,7 +15,7 @@ extension SignUpOutput: Codable { case userSub = "UserSub" } - public init (from decoder: Swift.Decoder) throws { + public init(from decoder: Swift.Decoder) throws { self.init() let containerValues = try decoder.container(keyedBy: CodingKeys.self) let userConfirmedDecoded = try containerValues.decode(Swift.Bool.self, forKey: .userConfirmed) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSAuthCognitoSession+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSAuthCognitoSession+Codable.swift index 12de2f5742..d2f346427d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSAuthCognitoSession+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSAuthCognitoSession+Codable.swift @@ -6,8 +6,8 @@ // import Foundation -@testable import AWSCognitoAuthPlugin @testable import Amplify +@testable import AWSCognitoAuthPlugin extension AWSAuthCognitoSession: Codable { enum CodingKeys: String, CodingKey { @@ -44,7 +44,8 @@ extension AWSAuthCognitoSession: Codable { idToken: accessToken, accessToken: idToken, refreshToken: refreshToken, - expiration: userPoolTokenExpiration) + expiration: userPoolTokenExpiration + ) let accessKeyId = try awsCredentialChildren.decode(String.self, forKey: .accessKeyId) let secretAccessKey = try awsCredentialChildren.decode(String.self, forKey: .secretAccessKey) @@ -55,13 +56,15 @@ extension AWSAuthCognitoSession: Codable { accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, sessionToken: sessionToken, - expiration: expiration) + expiration: expiration + ) self.init( isSignedIn: isSignedIn, identityIdResult: .success(identityIdResult), awsCredentialsResult: .success(awsCredentials), - cognitoTokensResult: .success(userPoolTokens)) + cognitoTokensResult: .success(userPoolTokens) + ) } public func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSCognitoSignOutResult+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSCognitoSignOutResult+Codable.swift index a874428ad4..d7f65c16c4 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSCognitoSignOutResult+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSCognitoSignOutResult+Codable.swift @@ -6,8 +6,8 @@ // import Foundation -@testable import AWSCognitoAuthPlugin @testable import Amplify +@testable import AWSCognitoAuthPlugin extension AWSCognitoSignOutResult: Equatable { public static func == (lhs: AWSCognitoSignOutResult, rhs: AWSCognitoSignOutResult) -> Bool { @@ -60,23 +60,26 @@ extension AWSCognitoSignOutResult: Codable { let accessToken = try globalSignOutError?.decodeIfPresent(String.self, forKey: .accessToken) var revokeTokenErrorObject: AWSCognitoRevokeTokenError? = nil - if let revokeAuthError = revokeAuthError, - let refreshToken = refreshToken { + if let revokeAuthError, + let refreshToken { revokeTokenErrorObject = AWSCognitoRevokeTokenError( - refreshToken: refreshToken, error: revokeAuthError) + refreshToken: refreshToken, error: revokeAuthError + ) } var globalSignOutErrorObject: AWSCognitoGlobalSignOutError? = nil - if let globalAuthError = globalAuthError, - let accessToken = accessToken { + if let globalAuthError, + let accessToken { globalSignOutErrorObject = AWSCognitoGlobalSignOutError( - accessToken: accessToken, error: globalAuthError) + accessToken: accessToken, error: globalAuthError + ) } self = .partial( revokeTokenError: revokeTokenErrorObject, globalSignOutError: globalSignOutErrorObject, - hostedUIError: nil) + hostedUIError: nil + ) } else { fatalError("type not supported") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthResetPasswordResult+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthResetPasswordResult+Codable.swift index 0cc890d123..19f6555fde 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthResetPasswordResult+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthResetPasswordResult+Codable.swift @@ -18,8 +18,10 @@ extension AuthResetPasswordResult: Codable { let values = try decoder.container(keyedBy: CodingKeys.self) let isPasswordReset = try values.decode(Bool.self, forKey: .isPasswordReset) let resetPasswordStep = try values.decode(AuthResetPasswordStep.self, forKey: .nextStep) - self.init(isPasswordReset: isPasswordReset, - nextStep: resetPasswordStep) + self.init( + isPasswordReset: isPasswordReset, + nextStep: resetPasswordStep + ) } public func encode(to encoder: Encoder) throws { @@ -43,13 +45,16 @@ extension AuthResetPasswordStep: Codable { let codeDeliveryDetails = try values.decode( AuthCodeDeliveryDetails.self, - forKey: .codeDeliveryDetails) + forKey: .codeDeliveryDetails + ) let additionalInfo = try values.decode( AdditionalInfo.self, - forKey: .additionalInfo) + forKey: .additionalInfo + ) self = .confirmResetPasswordWithCode( codeDeliveryDetails, - additionalInfo) + additionalInfo + ) } else { fatalError("next step type not supported") } @@ -89,12 +94,14 @@ extension AuthCodeDeliveryDetails: Codable { let attributeName = try values.decodeIfPresent(String.self, forKey: .attributeName) if attributeName == "EMAIL" { attributeKey = .email - } else if let attributeName = attributeName { + } else if let attributeName { attributeKey = .unknown(attributeName) } - self.init(destination: destination, - attributeKey: attributeKey) + self.init( + destination: destination, + attributeKey: attributeKey + ) } public func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignInResult+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignInResult+Codable.swift index 8fc03da9af..1806be279b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignInResult+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignInResult+Codable.swift @@ -62,7 +62,8 @@ extension AuthSignInStep: Codable { let additionalInfo = try values.decodeIfPresent([String: String].self, forKey: .additionalInfo) self = .confirmSignInWithSMSMFACode( codeDeliveryDetails, - additionalInfo) + additionalInfo + ) } else { fatalError("next step type not supported") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignUpResult+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignUpResult+Codable.swift index 899d43be13..ecf80b4d91 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignUpResult+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignUpResult+Codable.swift @@ -59,14 +59,17 @@ extension AuthSignUpStep: Codable { let codeDeliveryDetails = try values.decode( AuthCodeDeliveryDetails.self, - forKey: .codeDeliveryDetails) + forKey: .codeDeliveryDetails + ) let additionalInfo = try values.decode( AdditionalInfo.self, - forKey: .additionalInfo) + forKey: .additionalInfo + ) self = .confirmUser( codeDeliveryDetails, additionalInfo, - nil) + nil + ) } else { fatalError("next step type not supported") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarness.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarness.swift index b219711dee..da14b28223 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarness.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarness.swift @@ -38,18 +38,20 @@ class AuthTestHarness { } guard let authConfiguration = try? ConfigurationHelper - .authConfiguration(jsonValueConfiguration) else { + .authConfiguration(jsonValueConfiguration) + else { fatalError("Unable to create auth configuarion") } - testHarnessInput = await AuthTestHarnessInput.createInput( + self.testHarnessInput = await AuthTestHarnessInput.createInput( from: featureSpecification) - mockedCognitoHelper = MockedAuthCognitoPluginHelper( + self.mockedCognitoHelper = MockedAuthCognitoPluginHelper( authConfiguration: authConfiguration, initialAuthState: testHarnessInput.initialAuthState, mockIdentityProvider: testHarnessInput.getMockIdentityProvider(), - mockIdentity: testHarnessInput.getMockIdentity()) + mockIdentity: testHarnessInput.getMockIdentity() + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessConstants.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessConstants.swift index 7c190a1060..43200d158d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessConstants.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessConstants.swift @@ -7,7 +7,7 @@ import Foundation -struct AuthTestHarnessConstants { +enum AuthTestHarnessConstants { static let authConfigurationResourcePath = "TestResources/configuration" static let authStatesResourcePath = "TestResources/states" static let testSuitesPath = "TestResources/testSuites" diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessInput.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessInput.swift index bf7d92f287..345ef32fef 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessInput.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessInput.swift @@ -10,9 +10,9 @@ import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime +import Foundation @testable import Amplify @testable import AWSCognitoAuthPlugin -import Foundation struct AuthTestHarnessInput { let initialAuthState: AuthState @@ -27,11 +27,11 @@ extension AuthTestHarnessInput { from specification: FeatureSpecification ) async -> AuthTestHarnessInput { return await AuthTestHarnessInput( - initialAuthState: specification.preConditions.initialAuthState, - expectedAuthState: getExpectedAuthState(from: specification), - amplifyAPI: getAmplifyAPIUnderTest(from: specification), - cognitoAPI: getCognitoAPI(from: specification) - ) + initialAuthState: specification.preConditions.initialAuthState, + expectedAuthState: getExpectedAuthState(from: specification), + amplifyAPI: getAmplifyAPIUnderTest(from: specification), + cognitoAPI: getCognitoAPI(from: specification) + ) } private static func getAmplifyAPIUnderTest(from specification: FeatureSpecification) -> AmplifyAPI { @@ -61,25 +61,32 @@ extension AuthTestHarnessInput { enum AmplifyAPI { case resetPassword( input: AuthResetPasswordRequest, - expectedOutput: Result?) + expectedOutput: Result? + ) case signUp( input: AuthSignUpRequest, - expectedOutput: Result?) + expectedOutput: Result? + ) case signIn( input: AuthSignInRequest, - expectedOutput: Result?) + expectedOutput: Result? + ) case fetchAuthSession( input: AuthFetchSessionRequest, - expectedOutput: Result?) + expectedOutput: Result? + ) case signOut( input: AuthSignOutRequest, - expectedOutput: Result?) + expectedOutput: Result? + ) case deleteUser( input: Void, - expectedOutput: Result?) + expectedOutput: Result? + ) case confirmSignIn( input: AuthConfirmSignInRequest, - expectedOutput: Result?) + expectedOutput: Result? + ) } enum CognitoAPI { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthState+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthState+Codable.swift index 870ef3469b..d5f572234d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthState+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthState+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import Foundation +@testable import AWSCognitoAuthPlugin extension AuthState: Codable { @@ -26,7 +26,8 @@ extension AuthState: Codable { let authorizationState = try values.decode(AuthorizationState.self, forKey: .authorizationState) self = .configured( authenticationState, - authorizationState) + authorizationState + ) } else { fatalError("Decoding not supported") } @@ -46,14 +47,17 @@ extension AuthState: Codable { static func initialize( fileName: String, - with fileExtension: String = "") -> AuthState { + with fileExtension: String = "" + ) -> AuthState { let bundle = Bundle.authCognitoTestBundle() let url = bundle.url( forResource: fileName, withExtension: fileExtension, - subdirectory: AuthTestHarnessConstants.authStatesResourcePath)! + subdirectory: AuthTestHarnessConstants.authStatesResourcePath + )! let fileData: Data = try! Data(contentsOf: url) return try! JSONDecoder().decode( - AuthState.self, from: fileData) + AuthState.self, from: fileData + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthenticationState+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthenticationState+Codable.swift index 492f6cdcd6..045f349916 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthenticationState+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthenticationState+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import Foundation +@testable import AWSCognitoAuthPlugin extension AuthenticationState: Codable { @@ -31,7 +31,7 @@ extension AuthenticationState: Codable { let signedOutData = SignedOutData(lastKnownUserName: nil) self = .signedOut(signedOutData) } else if type == "AuthenticationState.SigningIn" { - self = .signingIn(try values.decode(SignInState.self, forKey: .SignInState)) + self = try .signingIn(values.decode(SignInState.self, forKey: .SignInState)) } else { fatalError("Decoding not supported") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthorizationState+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthorizationState+Codable.swift index 9d79544b97..dc4e04c7b7 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthorizationState+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthorizationState+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import Foundation +@testable import AWSCognitoAuthPlugin extension AuthorizationState: Codable { @@ -56,7 +56,8 @@ extension AuthorizationState: Codable { idToken: accessToken, accessToken: idToken, refreshToken: refreshToken, - expiration: userPoolExpiration) + expiration: userPoolExpiration + ) let accessKeyId = try awsCredentialChildren.decode(String.self, forKey: .accessKeyId) let secretAccessKey = try awsCredentialChildren.decode(String.self, forKey: .secretAccessKey) @@ -67,15 +68,18 @@ extension AuthorizationState: Codable { accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, sessionToken: sessionToken, - expiration: expiration) + expiration: expiration + ) self = .sessionEstablished(.userPoolAndIdentityPool( signedInData: .init( signedInDate: Date(), signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: userPoolTokens), + cognitoUserPoolTokens: userPoolTokens + ), identityID: identityId, - credentials: awsCredentials)) + credentials: awsCredentials + )) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/CodableStates.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/CodableStates.swift index 0dc049110d..7cd8e0e1f7 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/CodableStates.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/CodableStates.swift @@ -5,19 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin +import Amplify import AWSCognitoIdentityProvider -import Foundation import AWSPluginsCore -import Amplify +import Foundation +@testable import AWSCognitoAuthPlugin extension DeviceMetadata { - public init(from decoder: Decoder) throws { + init(from decoder: Decoder) throws { self = .noData } - public func encode(to encoder: Encoder) throws { + func encode(to encoder: Encoder) throws { fatalError() } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInChallengeState+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInChallengeState+Codable.swift index 467535a3c9..5cf2f3372d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInChallengeState+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInChallengeState+Codable.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import Foundation +@testable import AWSCognitoAuthPlugin extension SignInChallengeState: Codable { enum CodingKeys: String, CodingKey { @@ -22,16 +22,18 @@ extension SignInChallengeState: Codable { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let nestedContainerValue = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .authChallenge) - + let type = try values.decode(String.self, forKey: .type) if type == "SignInChallengeState.WaitingForAnswer" { - self = .waitingForAnswer( + self = try .waitingForAnswer( RespondToAuthChallenge( - challenge: try nestedContainerValue.decode(CognitoIdentityProviderClientTypes.ChallengeNameType.self, forKey: .challengeName), - username: try nestedContainerValue.decode(String.self, forKey: .username), - session: try nestedContainerValue.decode(String.self, forKey: .session), - parameters: try nestedContainerValue.decode([String: String].self, forKey: .parameters)), - .apiBased(.userSRP)) + challenge: nestedContainerValue.decode(CognitoIdentityProviderClientTypes.ChallengeNameType.self, forKey: .challengeName), + username: nestedContainerValue.decode(String.self, forKey: .username), + session: nestedContainerValue.decode(String.self, forKey: .session), + parameters: nestedContainerValue.decode([String: String].self, forKey: .parameters) + ), + .apiBased(.userSRP) + ) } else { fatalError("Decoding not supported") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInState+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInState+Codable.swift index e28731918f..c00fa85c01 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInState+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInState+Codable.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import Foundation +@testable import AWSCognitoAuthPlugin extension SignInState: Codable { - + enum CodingKeys: String, CodingKey { case type case SignInChallengeState @@ -21,10 +21,11 @@ extension SignInState: Codable { let type = try values.decode(String.self, forKey: .type) if type == "SignInState.ResolvingChallenge" { - self = .resolvingChallenge( - try values.decode(SignInChallengeState.self, forKey: .SignInChallengeState), + self = try .resolvingChallenge( + values.decode(SignInChallengeState.self, forKey: .SignInChallengeState), .smsMfa, - .apiBased(.userSRP)) + .apiBased(.userSRP) + ) } else { fatalError("Decoding not supported") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CognitoAPIDecoding/CognitoAPIDecodingHelper.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CognitoAPIDecoding/CognitoAPIDecodingHelper.swift index 6f80804dce..15d8273b3e 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CognitoAPIDecoding/CognitoAPIDecodingHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CognitoAPIDecoding/CognitoAPIDecodingHelper.swift @@ -11,11 +11,11 @@ import AWSPluginsCore import ClientRuntime @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime +import Foundation @testable import Amplify @testable import AWSCognitoAuthPlugin -import Foundation -struct CognitoAPIDecodingHelper { +enum CognitoAPIDecodingHelper { static func decode(with specification: FeatureSpecification) async -> [API.APIName: CognitoAPI] { @@ -43,108 +43,89 @@ struct CognitoAPIDecodingHelper { let requestData = requestData( for: specification, - with: apiName) + with: apiName + ) switch apiName { case "forgotPassword": decodedAPIs[.forgotPassword] = await .forgotPassword( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "signUp": decodedAPIs[.signUp] = await .signUp( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "deleteUser": decodedAPIs[.deleteUser] = await .deleteUser( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "respondToAuthChallenge": decodedAPIs[.confirmSignIn] = await .respondToAuthChallenge( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "confirmDevice": decodedAPIs[.confirmDevice] = await .confirmDevice( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "initiateAuth": decodedAPIs[.initiateAuth] = await .initiateAuth( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "revokeToken": decodedAPIs[.revokeToken] = await .revokeToken( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "getId": decodedAPIs[.getId] = await .getId( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "getCredentialsForIdentity": decodedAPIs[.getCredentialsForIdentity] = await .getCredentialsForIdentity( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "globalSignOut": decodedAPIs[.globalSignOut] = await .globalSignOut( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) default: fatalError() @@ -154,9 +135,11 @@ struct CognitoAPIDecodingHelper { return decodedAPIs } - private static func requestData(for specification: FeatureSpecification, - with apiName: String) -> Data? { - var requestData: Data? = nil + private static func requestData( + for specification: FeatureSpecification, + with apiName: String + ) -> Data? { + var requestData: Data? // Request if let cognitoResponseValidation = specification.validations.first(where: { validation in validation.value(at: "type") == .string("cognitoIdentityProvider") && @@ -201,7 +184,8 @@ struct CognitoAPIDecodingHelper { case "success": let responseData = try! JSONEncoder().encode(response) let output = try! JSONDecoder().decode( - Output.self, from: responseData) + Output.self, from: responseData + ) result = .success(output) default: fatalError("invalid response type") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/FeatureSpecification.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/FeatureSpecification.swift index 26ef2771e6..d05b7a11db 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/FeatureSpecification.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/FeatureSpecification.swift @@ -22,17 +22,21 @@ struct FeatureSpecification: Codable { var api: API var validations: [JSONValue] - init(fileName: String, - fileExtension: String = "", - subdirectory: String) { + init( + fileName: String, + fileExtension: String = "", + subdirectory: String + ) { let bundle = Bundle.authCognitoTestBundle() let url = bundle.url( forResource: fileName, withExtension: fileExtension, - subdirectory: subdirectory)! + subdirectory: subdirectory + )! let fileData: Data = try! Data(contentsOf: url) self = try! JSONDecoder().decode( - FeatureSpecification.self, from: fileData) + FeatureSpecification.self, from: fileData + ) } } @@ -48,9 +52,11 @@ struct Preconditions: Codable { var initialAuthState: AuthState var mockedResponses: [JSONValue] - init(amplifyConfiguration: AmplifyConfiguration, - initialAuthState: AuthState, - expectedResponses: [JSONValue]) { + init( + amplifyConfiguration: AmplifyConfiguration, + initialAuthState: AuthState, + expectedResponses: [JSONValue] + ) { self.initialAuthState = initialAuthState self.amplifyConfiguration = amplifyConfiguration self.mockedResponses = expectedResponses @@ -94,7 +100,7 @@ struct API: Codable { case confirmSignIn case fetchAuthSession case signOut - + case getId case getCredentialsForIdentity case confirmDevice @@ -106,9 +112,9 @@ struct API: Codable { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - name = try values.decode(APIName.self, forKey: .name) - params = try values.decode(JSONValue.self, forKey: .params) - options = try values.decode(JSONValue.self, forKey: .options) + self.name = try values.decode(APIName.self, forKey: .name) + self.params = try values.decode(JSONValue.self, forKey: .params) + self.options = try values.decode(JSONValue.self, forKey: .options) } public func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Helpers/AmplifyConfigurationInitializationInTest.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Helpers/AmplifyConfigurationInitializationInTest.swift index 3f06b0ec1e..8663e5705d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Helpers/AmplifyConfigurationInitializationInTest.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Helpers/AmplifyConfigurationInitializationInTest.swift @@ -9,14 +9,17 @@ import Foundation @testable import Amplify extension AmplifyConfiguration { - init(fileName: String, - fileExtension: String = "") { + init( + fileName: String, + fileExtension: String = "" + ) { let bundle = Bundle.authCognitoTestBundle() let url = bundle.url( forResource: fileName, withExtension: fileExtension, - subdirectory: AuthTestHarnessConstants.authConfigurationResourcePath)! + subdirectory: AuthTestHarnessConstants.authConfigurationResourcePath + )! self = try! AmplifyConfiguration.loadAmplifyConfiguration(from: url) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentity.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentity.swift index 951744d216..3ece205b21 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentity.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentity.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Foundation import AWSCognitoIdentity +import Foundation +import XCTest extension AuthTestHarnessInput { @@ -49,7 +49,8 @@ extension AuthTestHarnessInput { return MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentityProvider.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentityProvider.swift index 02cd19b66e..bfc14ba5dc 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentityProvider.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentityProvider.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentityProvider +import XCTest extension AuthTestHarnessInput { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/MockedAuthCognitoPlugin.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/MockedAuthCognitoPlugin.swift index 12b744f71f..3341ed87db 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/MockedAuthCognitoPlugin.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/MockedAuthCognitoPlugin.swift @@ -33,11 +33,13 @@ struct MockedAuthCognitoPluginHelper { let authStateMachine = StateMachine( resolver: authResolver, environment: authEnvironment, - initialState: initialAuthState) + initialState: initialAuthState + ) let credentialStoreMachine = StateMachine( resolver: credentialStoreResolver, - environment: credentialEnvironment) + environment: credentialEnvironment + ) let plugin = AWSCognitoAuthPlugin() @@ -47,7 +49,8 @@ struct MockedAuthCognitoPluginHelper { authStateMachine: authStateMachine, credentialStoreStateMachine: credentialStoreMachine, hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) return plugin } @@ -57,7 +60,7 @@ struct MockedAuthCognitoPluginHelper { private func makeUserPool() throws -> CognitoUserPoolBehavior { switch authConfiguration { case .userPools, .userPoolsAndIdentityPools: - return self.mockIdentityProvider + return mockIdentityProvider default: fatalError() } @@ -124,7 +127,8 @@ struct MockedAuthCognitoPluginHelper { authenticationEnvironment: authenticationEnvironment, authorizationEnvironment: nil, credentialsClient: makeCredentialStoreClient(), - logger: log) + logger: log + ) case .identityPools(let identityPoolConfigurationData): let authorizationEnvironment = authorizationEnvironment( @@ -136,10 +140,13 @@ struct MockedAuthCognitoPluginHelper { authenticationEnvironment: nil, authorizationEnvironment: authorizationEnvironment, credentialsClient: makeCredentialStoreClient(), - logger: log) + logger: log + ) - case .userPoolsAndIdentityPools(let userPoolConfigurationData, - let identityPoolConfigurationData): + case .userPoolsAndIdentityPools( + let userPoolConfigurationData, + let identityPoolConfigurationData + ): let authenticationEnvironment = authenticationEnvironment( userPoolConfigData: userPoolConfigurationData) let authorizationEnvironment = authorizationEnvironment( @@ -151,40 +158,50 @@ struct MockedAuthCognitoPluginHelper { authenticationEnvironment: authenticationEnvironment, authorizationEnvironment: authorizationEnvironment, credentialsClient: makeCredentialStoreClient(), - logger: log) + logger: log + ) } } private func authenticationEnvironment(userPoolConfigData: UserPoolConfigurationData) -> AuthenticationEnvironment { - let srpAuthEnvironment = BasicSRPAuthEnvironment(userPoolConfiguration: userPoolConfigData, - cognitoUserPoolFactory: makeUserPool) + let srpAuthEnvironment = BasicSRPAuthEnvironment( + userPoolConfiguration: userPoolConfigData, + cognitoUserPoolFactory: makeUserPool + ) let srpSignInEnvironment = BasicSRPSignInEnvironment(srpAuthEnvironment: srpAuthEnvironment) let userPoolEnvironment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfigData, cognitoUserPoolFactory: makeUserPool, cognitoUserPoolASFFactory: makeCognitoASF, - cognitoUserPoolAnalyticsHandlerFactory: makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: makeUserPoolAnalytics + ) let hostedUIEnvironment = hostedUIEnvironment(userPoolConfigData) - return BasicAuthenticationEnvironment(srpSignInEnvironment: srpSignInEnvironment, - userPoolEnvironment: userPoolEnvironment, - hostedUIEnvironment: hostedUIEnvironment) + return BasicAuthenticationEnvironment( + srpSignInEnvironment: srpSignInEnvironment, + userPoolEnvironment: userPoolEnvironment, + hostedUIEnvironment: hostedUIEnvironment + ) } private func hostedUIEnvironment(_ configuration: UserPoolConfigurationData) -> HostedUIEnvironment? { guard let hostedUIConfig = configuration.hostedUIConfig else { return nil } - return BasicHostedUIEnvironment(configuration: hostedUIConfig, - hostedUISessionFactory: makeHostedUISession, - urlSessionFactory: makeURLSession, - randomStringFactory: makeRandomString) + return BasicHostedUIEnvironment( + configuration: hostedUIConfig, + hostedUISessionFactory: makeHostedUISession, + urlSessionFactory: makeURLSession, + randomStringFactory: makeRandomString + ) } private func authorizationEnvironment( identityPoolConfigData: IdentityPoolConfigurationData) -> BasicAuthorizationEnvironment { - BasicAuthorizationEnvironment(identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: makeIdentityClient) + BasicAuthorizationEnvironment( + identityPoolConfiguration: identityPoolConfigData, + cognitoIdentityFactory: makeIdentityClient + ) } private func credentialStoreEnvironment(authConfiguration: AuthConfiguration) -> CredentialEnvironment { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineListenerTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineListenerTests.swift index cdb8ccdc6b..0821c5b743 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineListenerTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineListenerTests.swift @@ -91,13 +91,13 @@ class StateMachineListenerTests: XCTestCase { func testOrderOfSubsription() async throws { let loop = 1_000 - for _ in 1...loop { + for _ in 1 ... loop { let notified = expectation(description: "notified") notified.expectedFulfillmentCount = 3 await stateMachine.send(Counter.Event(id: "set1", eventType: .set(10))) let seq = await stateMachine.listen() - await self.stateMachine.send(Counter.Event(id: "set2", eventType: .set(11))) + await stateMachine.send(Counter.Event(id: "set2", eventType: .set(11))) Task { var count = 0 for await state in seq { @@ -143,12 +143,12 @@ class StateMachineListenerTests: XCTestCase { let task2 = Task { - for index in 1...100 { + for index in 1 ... 100 { let event = Counter.Event(id: "test", eventType: .adjustBy(index)) await stateMachine.send(event) - if (index == 30) { + if index == 30 { task.cancel() await Task.yield() } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineTests.swift index c0d3dbca65..2d7ac2d6bb 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineTests.swift @@ -40,7 +40,7 @@ class StateMachineTests: XCTestCase { let taskCompletion = expectation(description: "Completed sending event") taskCompletion.expectedFulfillmentCount = 1_000 Task { - for i in 1...1_000 { + for i in 1 ... 1_000 { if i.isMultiple(of: 2) { await testMachine.send(increment) } else { diff --git a/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntDecimalTests.swift b/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntDecimalTests.swift index 5a5f5e792a..bb1161ab0d 100644 --- a/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntDecimalTests.swift +++ b/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntDecimalTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AmplifyBigInteger +import XCTest final class AmplifyBigIntDecimalTests: XCTestCase { diff --git a/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntegerHelperTests.swift b/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntegerHelperTests.swift index a4068d5098..12484fd65a 100644 --- a/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntegerHelperTests.swift +++ b/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntegerHelperTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AmplifyBigInteger +import XCTest final class AmplifyBigIntegerHelperTests: XCTestCase { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AWSAuthBaseTest.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AWSAuthBaseTest.swift index 69668eee0d..5ae8447ddb 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AWSAuthBaseTest.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AWSAuthBaseTest.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @_spi(InternalAmplifyConfiguration) @testable import Amplify -import AWSCognitoAuthPlugin class AWSAuthBaseTest: XCTestCase { @@ -21,8 +21,8 @@ class AWSAuthBaseTest: XCTestCase { } var randomPhoneNumber: String { - "+1" + (1...10) - .map { _ in String(Int.random(in: 0...9)) } + "+1" + (1 ... 10) + .map { _ in String(Int.random(in: 0 ... 9)) } .joined() } @@ -43,7 +43,7 @@ class AWSAuthBaseTest: XCTestCase { initializeAmplify() _ = await Amplify.Auth.signOut() } - + override func tearDown() async throws { try await super.tearDown() await Amplify.reset() @@ -102,7 +102,8 @@ class AWSAuthBaseTest: XCTestCase { "AppClientId": userPooldAppClientID, "Region": region ] - ]]] + ]] + ] ) let configuration = AmplifyConfiguration(auth: authConfiguration) let authPlugin = AWSCognitoAuthPlugin() diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AppSyncSignerTests/AppSyncSignerTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AppSyncSignerTests/AppSyncSignerTests.swift index c13675ea17..6ca298c5f1 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AppSyncSignerTests/AppSyncSignerTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AppSyncSignerTests/AppSyncSignerTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AppSyncSignerTests: AWSAuthBaseTest { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift index 6a34b479ed..2d0da51aba 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthDeleteUserTests: AWSAuthBaseTest { @@ -28,9 +28,11 @@ class AuthDeleteUserTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") // Check if the auth session is signed in diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthEventTests/AuthEventIntegrationTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthEventTests/AuthEventIntegrationTests.swift index c817772286..0b65189f60 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthEventTests/AuthEventIntegrationTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthEventTests/AuthEventIntegrationTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthEventIntegrationTests: AWSAuthBaseTest { @@ -49,7 +49,8 @@ class AuthEventIntegrationTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) await fulfillment(of: [signInExpectation], timeout: networkTimeout) } @@ -79,7 +80,8 @@ class AuthEventIntegrationTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) _ = await Amplify.Auth.signOut() await fulfillment(of: [signOutExpectation], timeout: networkTimeout) } @@ -115,10 +117,11 @@ class AuthEventIntegrationTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) } catch { _ = try await Amplify.Auth.fetchAuthSession() - AuthSessionHelper.invalidateSession(with: self.amplifyConfiguration) + AuthSessionHelper.invalidateSession(with: amplifyConfiguration) _ = try await Amplify.Auth.fetchAuthSession() } await fulfillment(of: [signInExpectation, sessionExpiredExpectation], timeout: networkTimeout) @@ -154,7 +157,8 @@ class AuthEventIntegrationTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) await fulfillment(of: [signInExpectation], timeout: networkTimeout) do { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthUserAttributesTests/AuthUserAttributesTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthUserAttributesTests/AuthUserAttributesTests.swift index 78f9b2a099..50755fb814 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthUserAttributesTests/AuthUserAttributesTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthUserAttributesTests/AuthUserAttributesTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthUserAttributesTests: AWSAuthBaseTest { @@ -33,14 +33,16 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let attributes = try await Amplify.Auth.fetchUserAttributes() if let emailAttribute = attributes.filter({ $0.key == .email }).first { - XCTAssertEqual(emailAttribute.value, self.defaultTestEmail) + XCTAssertEqual(emailAttribute.value, defaultTestEmail) } else { XCTFail("Email attribute not found") } @@ -63,9 +65,11 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let password = "P123@\(UUID().uuidString)" let updatedEmail = "\(username)@amazon.com" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let pluginOptions = AWSAuthUpdateUserAttributeOptions(metadata: ["mydata": "myvalue"]) @@ -98,9 +102,11 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let updatedFamilyName = "\(username)@amazon.com" let updatedName = "Name\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let pluginOptions = AWSAuthUpdateUserAttributesOptions(metadata: ["mydata": "myvalue"]) @@ -124,7 +130,7 @@ class AuthUserAttributesTests: AWSAuthBaseTest { XCTFail("name attribute not found") } } - + /// - Given: A confirmed user /// - When: /// - I invoke Amplify.Auth.update with email attribute and then confirm the email attribute with an invalid code @@ -136,9 +142,11 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let password = "P123@\(UUID().uuidString)" let updatedEmail = "\(username)@amazon.com" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let pluginOptions = AWSAuthUpdateUserAttributeOptions(metadata: ["mydata": "myvalue"]) @@ -151,7 +159,7 @@ class AuthUserAttributesTests: AWSAuthBaseTest { case .done: print("Update completed") } - + do { try await Amplify.Auth.confirm(userAttribute: .email, confirmationCode: "123") XCTFail("User attribute confirmation unexpectedly succeeded") @@ -180,9 +188,11 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let password = "P123@\(UUID().uuidString)" let updatedEmail = "\(username)@amazon.com" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") _ = try await Amplify.Auth.update(userAttribute: AuthUserAttribute(.email, value: updatedEmail)) @@ -207,9 +217,11 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let pluginOptions = AWSSendUserAttributeVerificationCodeOptions(metadata: ["mydata": "myvalue"]) @@ -230,16 +242,18 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let oldPassword = "P123@\(UUID().uuidString)" let updatedPassword = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: oldPassword, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: oldPassword, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") try await Amplify.Auth.update(oldPassword: oldPassword, to: updatedPassword) let attributes = try await Amplify.Auth.fetchUserAttributes() if let emailAttribute = attributes.filter({ $0.key == .email }).first { - XCTAssertEqual(emailAttribute.value, self.defaultTestEmail) + XCTAssertEqual(emailAttribute.value, defaultTestEmail) } else { XCTFail("Email attribute not found") } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/CredentialStore/CredentialStoreConfigurationTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/CredentialStore/CredentialStoreConfigurationTests.swift index 8efbebdefd..6e1c1dfee0 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/CredentialStore/CredentialStoreConfigurationTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/CredentialStore/CredentialStoreConfigurationTests.swift @@ -34,7 +34,8 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { let awsCredentials = AuthAWSCognitoCredentials.testData let initialCognitoCredentials = AmplifyCredentials.identityPoolOnly( identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) let configData = Defaults.makeIdentityConfigData() let initialAuthConfig = AuthConfiguration.identityPools(configData) let credentialStore = AWSCognitoAuthCredentialStore(authConfiguration: initialAuthConfig) @@ -46,8 +47,10 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { // When configuration changed let userPoolConfiguration = Defaults.makeDefaultUserPoolConfigData() - let newAuthConfig = AuthConfiguration.userPoolsAndIdentityPools(userPoolConfiguration, - configData) + let newAuthConfig = AuthConfiguration.userPoolsAndIdentityPools( + userPoolConfiguration, + configData + ) let newCredentialStore = AWSCognitoAuthCredentialStore(authConfiguration: newAuthConfig) // Then @@ -78,10 +81,12 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { let initialCognitoCredentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: .testData, identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) let initialAuthConfig = AuthConfiguration.userPoolsAndIdentityPools( Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + Defaults.makeIdentityConfigData() + ) let credentialStore = AWSCognitoAuthCredentialStore(authConfiguration: initialAuthConfig) do { try credentialStore.saveCredential(initialCognitoCredentials) @@ -91,20 +96,25 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { // When configuration changed let updatedConfig = AuthConfiguration.userPoolsAndIdentityPools( - UserPoolConfigurationData(poolId: Defaults.userPoolId, - clientId: Defaults.appClientId, - region: Defaults.regionString, - clientSecret: Defaults.appClientSecret, - pinpointAppId: "somethingNew"), - Defaults.makeIdentityConfigData()) + UserPoolConfigurationData( + poolId: Defaults.userPoolId, + clientId: Defaults.appClientId, + region: Defaults.regionString, + clientSecret: Defaults.appClientSecret, + pinpointAppId: "somethingNew" + ), + Defaults.makeIdentityConfigData() + ) // When configuration don't change changed let newCredentialStore = AWSCognitoAuthCredentialStore(authConfiguration: updatedConfig) // Then guard let credentials = try? newCredentialStore.retrieveCredential(), - case .userPoolAndIdentityPool(let retrievedTokens, - let retrievedIdentityID, - let retrievedCredentials) = credentials else { + case .userPoolAndIdentityPool( + let retrievedTokens, + let retrievedIdentityID, + let retrievedCredentials + ) = credentials else { XCTFail("Unable to retrieve Credentials") return } @@ -130,7 +140,8 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { let awsCredentials = AuthAWSCognitoCredentials.testData let initialCognitoCredentials = AmplifyCredentials.identityPoolOnly( identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) let initialAuthConfig = AuthConfiguration.userPools(Defaults.makeDefaultUserPoolConfigData()) let credentialStore = AWSCognitoAuthCredentialStore(authConfiguration: initialAuthConfig) do { @@ -142,7 +153,8 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { // When configuration changed let newAuthConfig = AuthConfiguration.userPoolsAndIdentityPools( Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + Defaults.makeIdentityConfigData() + ) let newCredentialStore = AWSCognitoAuthCredentialStore(authConfiguration: newAuthConfig) // Then @@ -164,7 +176,8 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { let awsCredentials = AuthAWSCognitoCredentials.testData let initialCognitoCredentials = AmplifyCredentials.identityPoolOnly( identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) let initialAuthConfig = AuthConfiguration.identityPools(Defaults.makeIdentityConfigData()) let credentialStore = AWSCognitoAuthCredentialStore(authConfiguration: initialAuthConfig) @@ -175,8 +188,10 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { } // When configuration changed - let newAuthConfig = AuthConfiguration.identityPools(IdentityPoolConfigurationData(poolId: "changed", - region: "changed")) + let newAuthConfig = AuthConfiguration.identityPools(IdentityPoolConfigurationData( + poolId: "changed", + region: "changed" + )) let newCredentialStore = AWSCognitoAuthCredentialStore(authConfiguration: newAuthConfig) // Then @@ -199,10 +214,12 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { let initialCognitoCredentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: .testData, identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) let initialAuthConfig = AuthConfiguration.userPoolsAndIdentityPools( Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + Defaults.makeIdentityConfigData() + ) let credentialStore = AWSCognitoAuthCredentialStore(authConfiguration: initialAuthConfig) do { try credentialStore.saveCredential(initialCognitoCredentials) diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthFetchDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthFetchDeviceTests.swift index e893bb5a2b..aabc36f07f 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthFetchDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthFetchDeviceTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthFetchDeviceTests: AWSAuthBaseTest { @@ -52,11 +52,12 @@ class AuthFetchDeviceTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) } catch { print(error) } - + await fulfillment(of: [signInExpectation], timeout: networkTimeout) // fetch devices diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthForgetDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthForgetDeviceTests.swift index b1df2d456a..d01ce6a0ae 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthForgetDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthForgetDeviceTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthForgetDeviceTests: AWSAuthBaseTest { @@ -52,7 +52,8 @@ class AuthForgetDeviceTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) await fulfillment(of: [signInExpectation], timeout: networkTimeout) _ = try await Amplify.Auth.rememberDevice() diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthRememberDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthRememberDeviceTests.swift index d54ce32273..4099d9ee61 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthRememberDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthRememberDeviceTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthRememberDeviceTests: AWSAuthBaseTest { @@ -52,7 +52,8 @@ class AuthRememberDeviceTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) await fulfillment(of: [signInExpectation], timeout: networkTimeout) _ = try await Amplify.Auth.rememberDevice() diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthEnvironmentHelper.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthEnvironmentHelper.swift index cf495aa7fb..f8c07e003a 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthEnvironmentHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthEnvironmentHelper.swift @@ -17,16 +17,20 @@ enum Defaults { static let appClientSecret = "XXX" static func makeDefaultUserPoolConfigData() -> UserPoolConfigurationData { - UserPoolConfigurationData(poolId: userPoolId, - clientId: appClientId, - region: regionString, - clientSecret: appClientSecret, - pinpointAppId: "") + UserPoolConfigurationData( + poolId: userPoolId, + clientId: appClientId, + region: regionString, + clientSecret: appClientSecret, + pinpointAppId: "" + ) } static func makeIdentityConfigData() -> IdentityPoolConfigurationData { - IdentityPoolConfigurationData(poolId: identityPoolId, - region: regionString) + IdentityPoolConfigurationData( + poolId: identityPoolId, + region: regionString + ) } } @@ -38,7 +42,8 @@ extension AuthAWSCognitoCredentials { accessKeyId: "xx", secretAccessKey: "xx", sessionToken: "xx", - expiration: Date()) + expiration: Date() + ) } } @@ -53,9 +58,11 @@ extension SignedInData { static var testData: SignedInData { let tokens = AWSCognitoUserPoolTokens.testData - return SignedInData(signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: tokens) + return SignedInData( + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: tokens + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSessionHelper.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSessionHelper.swift index 72855132de..c5296d1095 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSessionHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSessionHelper.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSPluginsCore @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSPluginsCore @_spi(KeychainStore) import AWSPluginsCore import CryptoKit import Foundation @@ -18,7 +18,8 @@ struct AuthSessionHelper { static func getCurrentAmplifySession( shouldForceRefresh: Bool = false, for testCase: XCTestCase, - with timeout: TimeInterval) async throws -> AWSAuthCognitoSession? { + with timeout: TimeInterval + ) async throws -> AWSAuthCognitoSession? { var cognitoSession: AWSAuthCognitoSession? let session = try await Amplify.Auth.fetchAuthSession(options: .init(forceRefresh: shouldForceRefresh)) cognitoSession = (session as? AWSAuthCognitoSession) @@ -38,25 +39,30 @@ struct AuthSessionHelper { return } switch credentials { - case .userPoolAndIdentityPool(signedInData: let signedInData, - identityID: let identityID, - credentials: let awsCredentials): + case .userPoolAndIdentityPool( + signedInData: let signedInData, + identityID: let identityID, + credentials: let awsCredentials + ): let updatedToken = updateTokenWithPastExpiry(signedInData.cognitoUserPoolTokens) let signedInData = SignedInData( signedInDate: signedInData.signedInDate, signInMethod: signedInData.signInMethod, - cognitoUserPoolTokens: updatedToken) + cognitoUserPoolTokens: updatedToken + ) let updatedCredentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: signedInData, identityID: identityID, - credentials: awsCredentials) + credentials: awsCredentials + ) try! credentialStore.saveCredential(updatedCredentials) case .userPoolOnly(signedInData: let signedInData): let updatedToken = updateTokenWithPastExpiry(signedInData.cognitoUserPoolTokens) let signedInData = SignedInData( signedInDate: signedInData.signedInDate, signInMethod: signedInData.signInMethod, - cognitoUserPoolTokens: updatedToken) + cognitoUserPoolTokens: updatedToken + ) let updatedCredentials = AmplifyCredentials.userPoolOnly(signedInData: signedInData) try! credentialStore.saveCredential(updatedCredentials) default: break @@ -64,33 +70,37 @@ struct AuthSessionHelper { } - static private func updateTokenWithPastExpiry(_ tokens: AWSCognitoUserPoolTokens) + private static func updateTokenWithPastExpiry(_ tokens: AWSCognitoUserPoolTokens) -> AWSCognitoUserPoolTokens { var idToken = tokens.idToken var accessToken = tokens.accessToken if var idTokenClaims = try? AWSAuthService().getTokenClaims(tokenString: idToken).get(), var accessTokenClaims = try? AWSAuthService().getTokenClaims(tokenString: accessToken).get() { - idTokenClaims["exp"] = String(Date(timeIntervalSinceNow: -3000).timeIntervalSince1970) as AnyObject - accessTokenClaims["exp"] = String(Date(timeIntervalSinceNow: -3000).timeIntervalSince1970) as AnyObject + idTokenClaims["exp"] = String(Date(timeIntervalSinceNow: -3_000).timeIntervalSince1970) as AnyObject + accessTokenClaims["exp"] = String(Date(timeIntervalSinceNow: -3_000).timeIntervalSince1970) as AnyObject idToken = CognitoAuthTestHelper.buildToken(for: idTokenClaims) accessToken = CognitoAuthTestHelper.buildToken(for: accessTokenClaims) } - return AWSCognitoUserPoolTokens(idToken: idToken, - accessToken: accessToken, - refreshToken: "invalid", - expiration: Date().addingTimeInterval(-50000)) + return AWSCognitoUserPoolTokens( + idToken: idToken, + accessToken: accessToken, + refreshToken: "invalid", + expiration: Date().addingTimeInterval(-50_000) + ) } - static private func getAuthConfiguration(configuration: AmplifyConfiguration) -> AuthConfiguration { + private static func getAuthConfiguration(configuration: AmplifyConfiguration) -> AuthConfiguration { let jsonValueConfiguration = configuration.auth!.plugins["awsCognitoAuthPlugin"]! let userPoolConfigData = parseUserPoolConfigData(jsonValueConfiguration) let identityPoolConfigData = parseIdentityPoolConfigData(jsonValueConfiguration) - return try! authConfiguration(userPoolConfig: userPoolConfigData, - identityPoolConfig: identityPoolConfigData) + return try! authConfiguration( + userPoolConfig: userPoolConfigData, + identityPoolConfig: identityPoolConfigData + ) } - static private func parseUserPoolConfigData(_ config: JSONValue) -> UserPoolConfigurationData? { + private static func parseUserPoolConfigData(_ config: JSONValue) -> UserPoolConfigurationData? { // TODO: Use JSON serialization here to convert. guard let cognitoUserPoolJSON = config.value(at: "CognitoUserPool.Default") else { Amplify.Logging.info("Could not find Cognito User Pool configuration") @@ -107,13 +117,15 @@ struct AuthSessionHelper { if case .string(let clientSecretFromConfig) = cognitoUserPoolJSON.value(at: "AppClientSecret") { clientSecret = clientSecretFromConfig } - return UserPoolConfigurationData(poolId: poolId, - clientId: appClientId, - region: region, - clientSecret: clientSecret) + return UserPoolConfigurationData( + poolId: poolId, + clientId: appClientId, + region: region, + clientSecret: clientSecret + ) } - static private func parseIdentityPoolConfigData(_ config: JSONValue) -> IdentityPoolConfigurationData? { + private static func parseIdentityPoolConfigData(_ config: JSONValue) -> IdentityPoolConfigurationData? { guard let cognitoIdentityPoolJSON = config.value(at: "CredentialsProvider.CognitoIdentity.Default") else { Amplify.Logging.info("Could not find Cognito Identity Pool configuration") @@ -127,8 +139,10 @@ struct AuthSessionHelper { return IdentityPoolConfigurationData(poolId: poolId, region: region) } - static private func authConfiguration(userPoolConfig: UserPoolConfigurationData?, - identityPoolConfig: IdentityPoolConfigurationData?) throws -> AuthConfiguration { + private static func authConfiguration( + userPoolConfig: UserPoolConfigurationData?, + identityPoolConfig: IdentityPoolConfigurationData? + ) throws -> AuthConfiguration { if let userPoolConfigNonNil = userPoolConfig, let identityPoolConfigNonNil = identityPoolConfig { return .userPoolsAndIdentityPools(userPoolConfigNonNil, identityPoolConfigNonNil) @@ -148,7 +162,7 @@ struct AuthSessionHelper { } } -struct CognitoAuthTestHelper { +enum CognitoAuthTestHelper { /// Helper to build a JWT Token static func buildToken(for payload: [String: AnyObject]) -> String { @@ -184,7 +198,7 @@ struct CognitoAuthTestHelper { } } -fileprivate extension Data { +private extension Data { func urlSafeBase64EncodedString() -> String { return base64EncodedString() .replacingOccurrences(of: "+", with: "-") diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSignInHelper.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSignInHelper.swift index 1dc43decc6..e3a807a265 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSignInHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSignInHelper.swift @@ -9,7 +9,7 @@ import Amplify import XCTest enum AuthSignInHelper { - + static func signOut() async { let session = try? await Amplify.Auth.fetchAuthSession() if session?.isSignedIn ?? false { @@ -21,13 +21,14 @@ enum AuthSignInHelper { username: String, password: String, email: String, - phoneNumber: String? = nil) async throws -> Bool { + phoneNumber: String? = nil + ) async throws -> Bool { var userAttributes = [ AuthUserAttribute(.email, value: email) ] - if let phoneNumber = phoneNumber { + if let phoneNumber { userAttributes.append(AuthUserAttribute(.phoneNumber, value: phoneNumber)) } @@ -45,12 +46,14 @@ enum AuthSignInHelper { username: String, password: String, email: String, - phoneNumber: String? = nil) async throws -> Bool { + phoneNumber: String? = nil + ) async throws -> Bool { let signedUp = try await AuthSignInHelper.signUpUser( username: username, password: password, email: email, - phoneNumber: phoneNumber) + phoneNumber: phoneNumber + ) guard signedUp else { throw AuthError.invalidState("Auth sign up failed", "", nil) } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/TOTPHelper.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/TOTPHelper.swift index f7c2203689..5089ec32a0 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/TOTPHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/TOTPHelper.swift @@ -8,7 +8,7 @@ import CryptoKit import XCTest -struct TOTPHelper { +enum TOTPHelper { static func generateTOTPCode(sharedSecret: String) -> String { @@ -25,16 +25,17 @@ struct TOTPHelper { private static func otpCode(secret: Data, date: Date, period: TimeInterval, digits: Int) -> String { let counter = UInt64(date.timeIntervalSince1970 / period) - let counterBytes = (0..<8).reversed().map { UInt8(counter >> (8 * $0) & 0xff) } + let counterBytes = (0 ..< 8).reversed().map { UInt8(counter >> (8 * $0) & 0xff) } let hash = HMAC.authenticationCode( for: counterBytes, - using: SymmetricKey(data: secret)) + using: SymmetricKey(data: secret) + ) let offset = Int(hash.suffix(1)[0] & 0x0f) let hash32 = hash .dropFirst(offset) .prefix(4) - .reduce(0, { ($0 << 8) | UInt32($1) }) - let hash31 = hash32 & 0x7FFF_FFFF + .reduce(0) { ($0 << 8) | UInt32($1) } + let hash31 = hash32 & 0x7fffffff let pad = String(repeating: "0", count: digits) return String((pad + String(hash31)).suffix(digits)) } @@ -43,22 +44,22 @@ struct TOTPHelper { private static let __: UInt8 = 255 private static let alphabetDecodeTable: [UInt8] = [ - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x00 - 0x0F - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x10 - 0x1F - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x20 - 0x2F - __,__,26,27, 28,29,30,31, __,__,__,__, __,__,__,__, // 0x30 - 0x3F - __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x40 - 0x4F - 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 0x50 - 0x5F - __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x60 - 0x6F - 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 0x70 - 0x7F - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x80 - 0x8F - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x90 - 0x9F - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xA0 - 0xAF - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xB0 - 0xBF - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xC0 - 0xCF - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xD0 - 0xDF - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xE0 - 0xEF - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xF0 - 0xFF + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0x00 - 0x0F + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0x10 - 0x1F + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0x20 - 0x2F + __, __, 26, 27, 28, 29, 30, 31, __, __, __, __, __, __, __, __, // 0x30 - 0x3F + __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 0x40 - 0x4F + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, __, __, __, __, __, // 0x50 - 0x5F + __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 0x60 - 0x6F + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, __, __, __, __, __, // 0x70 - 0x7F + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0x80 - 0x8F + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0x90 - 0x9F + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0xA0 - 0xAF + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0xB0 - 0xBF + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0xC0 - 0xCF + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0xD0 - 0xDF + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0xE0 - 0xEF + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0xF0 - 0xFF ] private static func base32decode(_ string: String, _ table: [UInt8]) -> [UInt8]? { @@ -116,12 +117,12 @@ struct TOTPHelper { (data: UnsafeBufferPointer) -> [UInt8] in var encoded = data.baseAddress! - var result = Array(repeating: 0, count: dataSize) + var result = [UInt8](repeating: 0, count: dataSize) var decodedOffset = 0 // decode regular blocks var value0, value1, value2, value3, value4, value5, value6, value7: UInt8 - (value0, value1, value2, value3, value4, value5, value6, value7) = (0,0,0,0,0,0,0,0) + (value0, value1, value2, value3, value4, value5, value6, value7) = (0, 0, 0, 0, 0, 0, 0, 0) while remainEncodedLength >= 8 { value0 = table[Int(encoded[0])] value1 = table[Int(encoded[1])] @@ -144,7 +145,7 @@ struct TOTPHelper { } // decode last block - (value0, value1, value2, value3, value4, value5, value6, value7) = (0,0,0,0,0,0,0,0) + (value0, value1, value2, value3, value4, value5, value6, value7) = (0, 0, 0, 0, 0, 0, 0, 0) switch remainEncodedLength { case 7: value6 = table[Int(encoded[6])] diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFAPreferenceTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFAPreferenceTests.swift index 587830f71c..d9a82487b0 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFAPreferenceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFAPreferenceTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify import AWSCognitoAuthPlugin +import XCTest class MFAPreferenceTests: AWSAuthBaseTest { @@ -34,7 +34,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { username: username, password: password, email: email ?? defaultTestEmail, - phoneNumber: phoneNumber) + phoneNumber: phoneNumber + ) XCTAssertTrue(didSucceed, "Signup and sign in should succeed") } @@ -88,7 +89,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test enabled try await authCognitoPlugin.updateMFAPreference( sms: nil, - totp: .enabled) + totp: .enabled + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -98,7 +100,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test preferred try await authCognitoPlugin.updateMFAPreference( sms: nil, - totp: .preferred) + totp: .preferred + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -109,7 +112,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test notPreferred try await authCognitoPlugin.updateMFAPreference( sms: nil, - totp: .notPreferred) + totp: .notPreferred + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -119,7 +123,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test disabled try await authCognitoPlugin.updateMFAPreference( sms: nil, - totp: .disabled) + totp: .disabled + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNil(fetchMFAResult.enabled) @@ -151,7 +156,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test enabled try await authCognitoPlugin.updateMFAPreference( sms: .enabled, - totp: nil) + totp: nil + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -161,7 +167,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test preferred try await authCognitoPlugin.updateMFAPreference( sms: .preferred, - totp: nil) + totp: nil + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -172,7 +179,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test notPreferred try await authCognitoPlugin.updateMFAPreference( sms: .notPreferred, - totp: nil) + totp: nil + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -182,7 +190,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test disabled try await authCognitoPlugin.updateMFAPreference( sms: .disabled, - totp: nil) + totp: nil + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNil(fetchMFAResult.enabled) @@ -201,8 +210,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { /// - I should get valid fetchMFAPreference results corresponding to the updateMFAPreference /// func testFetchAndUpdateMFAPreferenceForSMSAndTOTP() async throws { - let randomPhoneNumber = "+1" + (1...10) - .map { _ in String(Int.random(in: 0...9)) } + let randomPhoneNumber = "+1" + (1 ... 10) + .map { _ in String(Int.random(in: 0 ... 9)) } .joined() try await signUpAndSignIn( @@ -223,7 +232,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test both MFA types as enabled try await authCognitoPlugin.updateMFAPreference( sms: .enabled, - totp: .enabled) + totp: .enabled + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -233,7 +243,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test SMS as preferred, TOTP as enabled try await authCognitoPlugin.updateMFAPreference( sms: .preferred, - totp: .enabled) + totp: .enabled + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -244,7 +255,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test SMS as notPreferred, TOTP as preferred try await authCognitoPlugin.updateMFAPreference( sms: .notPreferred, - totp: .preferred) + totp: .preferred + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -255,7 +267,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test SMS as disabled, no change to TOTP try await authCognitoPlugin.updateMFAPreference( sms: .disabled, - totp: nil) + totp: nil + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -266,7 +279,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test SMS as preferred, no change to TOTP (which should remove TOTP from preferred list) try await authCognitoPlugin.updateMFAPreference( sms: .preferred, - totp: nil) + totp: nil + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -297,12 +311,14 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test both MFA types as enabled try await authCognitoPlugin.updateMFAPreference( sms: .preferred, - totp: .preferred) + totp: .preferred + ) XCTFail("Should not proceed, because MFA types cannot be marked as preferred") } catch { guard let authError = error as? AuthError, - case .service(_, _, let underlyingError) = authError else { + case .service(_, _, let underlyingError) = authError + else { XCTFail("Should throw service error") return } @@ -340,7 +356,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test SMS as preferred, TOTP as enabled try await authCognitoPlugin.updateMFAPreference( sms: .preferred, - totp: .enabled) + totp: .enabled + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertEqual(fetchMFAResult.enabled, [.sms, .totp]) diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFASignInTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFASignInTests.swift index cbfb0bb6b5..c86cb44acb 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFASignInTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFASignInTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify import AWSCognitoAuthPlugin +import XCTest class MFASignInTests: AWSAuthBaseTest { @@ -58,7 +58,8 @@ class MFASignInTests: AWSAuthBaseTest { try await Amplify.Auth.verifyTOTPSetup(code: totpCode) try await authCognitoPlugin.updateMFAPreference( sms: nil, - totp: .enabled) + totp: .enabled + ) await AuthSignInHelper.signOut() /// Sleep for 30 secs so that TOTP code can be regenerated for use during sign in otherwise will get @@ -75,7 +76,8 @@ class MFASignInTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .confirmSignInWithTOTPCode = result.nextStep else { XCTFail("Next step should be confirmSignInWithTOTPCode") return @@ -126,7 +128,8 @@ class MFASignInTests: AWSAuthBaseTest { for: "awsCognitoAuthPlugin") as! AWSCognitoAuthPlugin try await authCognitoPlugin.updateMFAPreference( sms: .enabled, - totp: nil) + totp: nil + ) await AuthSignInHelper.signOut() @@ -137,7 +140,8 @@ class MFASignInTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .confirmSignInWithSMSMFACode(let codeDeliveryDetails, _) = result.nextStep else { XCTFail("Next step should be confirmSignInWithSMSMFACode") return @@ -178,7 +182,8 @@ class MFASignInTests: AWSAuthBaseTest { username: username, password: password, email: randomEmail, - phoneNumber: randomPhoneNumber) + phoneNumber: randomPhoneNumber + ) XCTAssertTrue(didSucceed, "Signup and sign in should succeed") @@ -190,7 +195,8 @@ class MFASignInTests: AWSAuthBaseTest { try await Amplify.Auth.verifyTOTPSetup(code: totpCode) try await authCognitoPlugin.updateMFAPreference( sms: .enabled, - totp: .enabled) + totp: .enabled + ) await AuthSignInHelper.signOut() /// Sleep for 30 secs so that TOTP code can be regenerated for use during sign in otherwise will get @@ -206,7 +212,8 @@ class MFASignInTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .continueSignInWithMFASelection(let allowedMFATypes) = result.nextStep else { XCTFail("Next step should be continueSignInWithMFASelection") return @@ -270,7 +277,8 @@ class MFASignInTests: AWSAuthBaseTest { try await Amplify.Auth.verifyTOTPSetup(code: totpCode) try await authCognitoPlugin.updateMFAPreference( sms: .enabled, - totp: .enabled) + totp: .enabled + ) await AuthSignInHelper.signOut() // Once all preconditions are satisfied, try signing in @@ -278,7 +286,8 @@ class MFASignInTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .continueSignInWithMFASelection(let allowedMFATypes) = result.nextStep else { XCTFail("Next step should be continueSignInWithMFASelection") return diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenAuthenticatedTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenAuthenticatedTests.swift index f76d5d5c1a..9ad0d5e7bd 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenAuthenticatedTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenAuthenticatedTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify import AWSCognitoAuthPlugin +import XCTest class TOTPSetupWhenAuthenticatedTests: AWSAuthBaseTest { @@ -76,7 +76,8 @@ class TOTPSetupWhenAuthenticatedTests: AWSAuthBaseTest { } catch { guard let authError = error as? AuthError, - case .service(_, _, let underlyingError) = authError else { + case .service(_, _, let underlyingError) = authError + else { XCTFail("Should throw service error") return } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenUnauthenticatedTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenUnauthenticatedTests.swift index 4e514f81e4..ecd6212fe2 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenUnauthenticatedTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenUnauthenticatedTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify import AWSCognitoAuthPlugin +import XCTest class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { @@ -54,7 +54,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .continueSignInWithTOTPSetup(let totpSetupDetails) = result.nextStep else { XCTFail("Next step should be continueSignInWithTOTPSetup") return @@ -96,7 +97,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .confirmSignInWithSMSMFACode(let codeDeliveryDetails, _) = result.nextStep else { XCTFail("Next step should be confirmSignInWithSMSMFACode") return @@ -146,7 +148,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .continueSignInWithTOTPSetup(let totpSetupDetails) = result.nextStep else { XCTFail("Next step should be continueSignInWithTOTPSetup") return @@ -157,7 +160,7 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { let confirmSignInResult = try await Amplify.Auth.confirmSignIn( challengeResponse: totpCode) XCTAssertTrue(confirmSignInResult.isSignedIn) - + } catch { XCTFail("SignIn should successfully complete. \(error)") } @@ -195,7 +198,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .continueSignInWithTOTPSetup(let details) = result.nextStep else { XCTFail("Next step should be continueSignInWithTOTPSetup") return @@ -209,7 +213,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { } catch { guard let authError = error as? AuthError, - case .service(_, _, let underlyingError) = authError else { + case .service(_, _, let underlyingError) = authError + else { XCTFail("Should throw service error") return } @@ -263,7 +268,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .continueSignInWithTOTPSetup(let details) = result.nextStep else { XCTFail("Next step should be continueSignInWithTOTPSetup") return @@ -277,7 +283,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { } catch { guard let authError = error as? AuthError, - case .service(_, _, let underlyingError) = authError else { + case .service(_, _, let underlyingError) = authError + else { XCTFail("Should throw service error") return } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthConfirmResetPasswordTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthConfirmResetPasswordTests.swift index 299d67b6a1..bf91d52c24 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthConfirmResetPasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthConfirmResetPasswordTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthConfirmResetPasswordTests: AWSAuthBaseTest { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthResetPasswordTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthResetPasswordTests.swift index cabe4a672b..99249901c1 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthResetPasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthResetPasswordTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthResetPasswordTests: AWSAuthBaseTest { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/FederatedSessionTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/FederatedSessionTests.swift index 2fc5743290..51ae5668ae 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/FederatedSessionTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/FederatedSessionTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -@testable import Amplify import AWSCognitoAuthPlugin import AWSPluginsCore +import XCTest +@testable import Amplify class FederatedSessionTests: AWSAuthBaseTest { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/GetCurrentUserTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/GetCurrentUserTests.swift index dd203b6ab5..093e4cbf9a 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/GetCurrentUserTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/GetCurrentUserTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -@testable import Amplify import AWSCognitoAuthPlugin import AWSPluginsCore +import XCTest +@testable import Amplify class GetCurrentUserTests: AWSAuthBaseTest { @@ -36,7 +36,8 @@ class GetCurrentUserTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) let authUser = try await Amplify.Auth.getCurrentUser() diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedInAuthSessionTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedInAuthSessionTests.swift index 159f222430..5128307b51 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedInAuthSessionTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedInAuthSessionTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -@testable import Amplify import AWSCognitoAuthPlugin import AWSPluginsCore +import XCTest +@testable import Amplify class SignedInAuthSessionTests: AWSAuthBaseTest { @@ -33,26 +33,33 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { func testSuccessfulForceSessionFetch() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let firstCognitoSession = try await AuthSessionHelper.getCurrentAmplifySession( for: self, - with: networkTimeout) + with: networkTimeout + ) let secondCognitoSession = try await AuthSessionHelper.getCurrentAmplifySession( for: self, - with: networkTimeout) + with: networkTimeout + ) let thirdCognitoSession = try await AuthSessionHelper.getCurrentAmplifySession( shouldForceRefresh: true, for: self, - with: networkTimeout) + with: networkTimeout + ) let fourthCognitoSession = try await AuthSessionHelper.getCurrentAmplifySession( for: self, - with: networkTimeout) + with: networkTimeout + ) // First 2 sessions should match XCTAssertEqual(firstCognitoSession, secondCognitoSession) @@ -75,8 +82,11 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { func testSuccessfulSessionFetch() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let session = try await Amplify.Auth.fetchAuthSession() @@ -95,8 +105,11 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { throw XCTSkip("TODO: fix this test. We need to find a way to mock credential store") let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let session = try await Amplify.Auth.fetchAuthSession() @@ -108,7 +121,7 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { } // Manually invalidate the tokens and then try to fetch the session. - AuthSessionHelper.invalidateSession(with: self.amplifyConfiguration) + AuthSessionHelper.invalidateSession(with: amplifyConfiguration) let anotherSession = try await Amplify.Auth.fetchAuthSession() do { let authSession = anotherSession as? AuthCognitoTokensProvider @@ -116,7 +129,8 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { XCTFail("Should not receive a valid token") } catch { guard let authError = error as? AuthError, - case .sessionExpired = authError else { + case .sessionExpired = authError + else { XCTFail("Should receive a session expired error but received \(error)") return } @@ -135,8 +149,11 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { throw XCTSkip("TODO: fix this test. We need to find a way to mock credential store") let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let session = try await Amplify.Auth.fetchAuthSession() @@ -155,7 +172,8 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { XCTFail("Should not receive a valid token") } catch { guard let authError = error as? AuthError, - case .signedOut = authError else { + case .signedOut = authError + else { XCTFail("Should receive a session expired error but received \(error)") return } @@ -173,8 +191,11 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { func testMultipleSuccessfulSessionFetch() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let firstSession = try await Amplify.Auth.fetchAuthSession() @@ -205,16 +226,17 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { let identityIDExpectation = expectation(description: "Identity id should be fetched") identityIDExpectation.expectedFulfillmentCount = 100 - for index in 1...100 { + for index in 1 ... 100 { Task { // Randomly yield the task so that below execution of signOut happen - if index%6 == 0 { + if index % 6 == 0 { await Task.yield() } let firstSession = try await Amplify.Auth.fetchAuthSession() guard let cognitoSession = firstSession as? AWSAuthCognitoSession, - let _ = try? cognitoSession.identityIdResult.get() else { + let _ = try? cognitoSession.identityIdResult.get() + else { XCTFail("Could not fetch Identity ID") return } @@ -226,7 +248,7 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { _ = await Amplify.Auth.signOut() let fetchSessionExptectation = expectation(description: "Session should be fetched") fetchSessionExptectation.expectedFulfillmentCount = 50 - for _ in 1...50 { + for _ in 1 ... 50 { Task { let firstSession = try await Amplify.Auth.fetchAuthSession() XCTAssertFalse(firstSession.isSignedIn, "Session state should be signed out") @@ -265,7 +287,8 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { let didSucceed = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") session = try await Amplify.Auth.fetchAuthSession() diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedOutAuthSessionTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedOutAuthSessionTests.swift index 8722221457..caa0bdc541 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedOutAuthSessionTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedOutAuthSessionTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -@testable import Amplify import AWSCognitoAuthPlugin import AWSPluginsCore +import XCTest +@testable import Amplify class SignedOutAuthSessionTests: AWSAuthBaseTest { @@ -49,7 +49,8 @@ class SignedOutAuthSessionTests: AWSAuthBaseTest { let result = try await Amplify.Auth.fetchAuthSession() guard let cognitoResult = result as? AWSAuthCognitoSession, - let identityID1 = try? cognitoResult.identityIdResult.get() else { + let identityID1 = try? cognitoResult.identityIdResult.get() + else { XCTFail("Should retreive identity ID") return } @@ -58,7 +59,8 @@ class SignedOutAuthSessionTests: AWSAuthBaseTest { let result2 = try await Amplify.Auth.fetchAuthSession() guard let cognitoResult = result2 as? AWSAuthCognitoSession, - let identityID2 = try? cognitoResult.identityIdResult.get() else { + let identityID2 = try? cognitoResult.identityIdResult.get() + else { XCTFail("Should retreive identity ID") return } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthCustomSignInTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthCustomSignInTests.swift index 685ea89498..4535f30e3f 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthCustomSignInTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthCustomSignInTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthCustomSignInTests: AWSAuthBaseTest { @@ -58,8 +58,11 @@ class AuthCustomSignInTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let isSignedUp = try await AuthSignInHelper.signUpUser(username: username, password: password, - email: defaultTestEmail) + let isSignedUp = try await AuthSignInHelper.signUpUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(isSignedUp) var confirmationCodeForValidation = "" @@ -120,15 +123,20 @@ class AuthCustomSignInTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let isSignedUp = try await AuthSignInHelper.signUpUser(username: username, password: password, - email: defaultTestEmail) + let isSignedUp = try await AuthSignInHelper.signUpUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(isSignedUp) let option = AWSAuthSignInOptions(authFlowType: .customWithSRP) do { - let signInResult = try await Amplify.Auth.signIn(username: username, - password: password, - options: AuthSignInRequest.Options(pluginOptions: option)) + let signInResult = try await Amplify.Auth.signIn( + username: username, + password: password, + options: AuthSignInRequest.Options(pluginOptions: option) + ) XCTAssertTrue(signInResult.isSignedIn, "SignIn should be complete") } catch { XCTFail("Should successfully login") @@ -138,9 +146,11 @@ class AuthCustomSignInTests: AWSAuthBaseTest { let srpOption = AWSAuthSignInOptions(authFlowType: .userSRP) do { - let signInResult = try await Amplify.Auth.signIn(username: username, - password: password, - options: AuthSignInRequest.Options(pluginOptions: srpOption)) + let signInResult = try await Amplify.Auth.signIn( + username: username, + password: password, + options: AuthSignInRequest.Options(pluginOptions: srpOption) + ) XCTAssertTrue(signInResult.isSignedIn, "SignIn should be complete") } catch { XCTFail("SignIn with a valid username/password should not fail \(error)") @@ -193,9 +203,11 @@ class AuthCustomSignInTests: AWSAuthBaseTest { var confirmationCodeForValidation = "" let option = AWSAuthSignInOptions(authFlowType: .custom) do { - let signInResult = try await Amplify.Auth.signIn(username: username, - password: password, - options: AuthSignInRequest.Options(pluginOptions: option)) + let signInResult = try await Amplify.Auth.signIn( + username: username, + password: password, + options: AuthSignInRequest.Options(pluginOptions: option) + ) if case .confirmSignInWithCustomChallenge(let additionalInfo) = signInResult.nextStep { confirmationCodeForValidation = additionalInfo?["code"] ?? "" } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthSRPSignInTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthSRPSignInTests.swift index ffbecc10d4..7931d83d4d 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthSRPSignInTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthSRPSignInTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -@testable import Amplify import AWSCognitoAuthPlugin import AWSPluginsCore +import XCTest +@testable import Amplify class AuthSRPSignInTests: AWSAuthBaseTest { @@ -33,9 +33,11 @@ class AuthSRPSignInTests: AWSAuthBaseTest { func testSuccessfulSignIn() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.signUpUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.signUpUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "Signup operation failed") do { let signInResult = try await Amplify.Auth.signIn(username: username, password: password) @@ -56,9 +58,11 @@ class AuthSRPSignInTests: AWSAuthBaseTest { func testSignInWithWrongPassword() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.signUpUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.signUpUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "Signup operation failed") do { @@ -129,8 +133,11 @@ class AuthSRPSignInTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.signUpUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.signUpUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "Signup operation failed") let awsAuthSignInOptions = AWSAuthSignInOptions(metadata: ["mySignInData": "myvalue"]) @@ -186,8 +193,11 @@ class AuthSRPSignInTests: AWSAuthBaseTest { func testSignInWhenAlreadySignedIn() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") do { @@ -264,10 +274,12 @@ class AuthSRPSignInTests: AWSAuthBaseTest { userAttributes: [ AuthUserAttribute(.email, value: defaultTestEmail) ], - metadata: nil) + metadata: nil + ) let result = try await Amplify.Auth.confirmSignIn( challengeResponse: newPassword, - options: .init(pluginOptions: pluginOptions)) + options: .init(pluginOptions: pluginOptions) + ) if case .done = result.nextStep { confirmOperationExpectation.fulfill() } @@ -311,7 +323,8 @@ class AuthSRPSignInTests: AWSAuthBaseTest { let didSucceed = try await AuthSignInHelper.signUpUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "Signup operation failed") do { let signInResult = try await Amplify.Auth.signIn(username: username, password: password) diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignOutTests/AuthSignOutTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignOutTests/AuthSignOutTests.swift index 6b69e9d322..43330d0cc8 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignOutTests/AuthSignOutTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignOutTests/AuthSignOutTests.swift @@ -40,9 +40,11 @@ class AuthSignOutTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "Signup operation failed") @@ -61,9 +63,11 @@ class AuthSignOutTests: AWSAuthBaseTest { func testNonGlobalSignOut() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "Signup operation failed") print("calling signOut...") try await signOut(globalSignOut: false) diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthConfirmSignUpTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthConfirmSignUpTests.swift index b706fcf957..47cbf0df80 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthConfirmSignUpTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthConfirmSignUpTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthConfirmSignUpTests: AWSAuthBaseTest { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthResendSignUpCodeTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthResendSignUpCodeTests.swift index f6965e61b5..6ae7b26823 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthResendSignUpCodeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthResendSignUpCodeTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthResendSignUpCodeTests: AWSAuthBaseTest { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthSignUpTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthSignUpTests.swift index 73ce715670..877f858d84 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthSignUpTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthSignUpTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthSignUpTests: AWSAuthBaseTest { @@ -24,10 +24,13 @@ class AuthSignUpTests: AWSAuthBaseTest { let password = "P123@\(UUID().uuidString)" let options = AuthSignUpRequest.Options(userAttributes: [ - AuthUserAttribute(.email, value: defaultTestEmail)]) - let signUpResult = try await Amplify.Auth.signUp(username: username, - password: password, - options: options) + AuthUserAttribute(.email, value: defaultTestEmail) + ]) + let signUpResult = try await Amplify.Auth.signUp( + username: username, + password: password, + options: options + ) XCTAssertTrue(signUpResult.isSignUpComplete, "Signup should be complete") } @@ -37,7 +40,7 @@ class AuthSignUpTests: AWSAuthBaseTest { let signUpExpectation = expectation(description: "Sign up completed") signUpExpectation.expectedFulfillmentCount = 2 - for _ in 0.. AmplifyConfiguration { do { return try ConfigurationHelper.retrieveAmplifyConfiguration( diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/ContentView.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/ContentView.swift index 715142da7d..d7103bad7c 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/ContentView.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/ContentView.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import SwiftUI import Amplify +import SwiftUI struct ContentView: View { @@ -17,7 +17,7 @@ struct ContentView: View { NavigationView { if !loading { VStack { - if self.username != nil { + if username != nil { SignedInView(username: $username) } else { SignedOutView() @@ -28,7 +28,7 @@ struct ContentView: View { }.onAppear { Task { - await self.configureAuth() + await configureAuth() } } } @@ -36,11 +36,11 @@ struct ContentView: View { func configureAuth() async { do { let user = try await Amplify.Auth.getCurrentUser() - self.username = user.username + username = user.username } catch { - self.username = nil + username = nil } - self.loading = false + loading = false } } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/AuthError+Info.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/AuthError+Info.swift index 4538e239ed..6644c676bb 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/AuthError+Info.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/AuthError+Info.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoAuthPlugin +import Foundation extension AuthError { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/ConfigurationHelper.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/ConfigurationHelper.swift index 7881ee5d31..4425a429d6 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/ConfigurationHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/ConfigurationHelper.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation class ConfigurationHelper { @@ -42,7 +42,8 @@ class ConfigurationHelper { "AppClientId": userPooldAppClientID, "Region": region ] - ]]] + ]] + ] ) return AmplifyConfiguration(auth: authConfiguration) } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignUpView.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignUpView.swift index e21bb3c942..cc9fe17e0f 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignUpView.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignUpView.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import SwiftUI import Amplify +import SwiftUI struct SignUpView: View { @@ -44,11 +44,11 @@ struct SignUpView: View { } .accessibility(identifier: Identifiers.signUpButton) Spacer() - if let error = self.errorLabel { + if let error = errorLabel { Text("Error occured: \(error)") .accessibilityLabel(Identifiers.errorLabel) } - if let successLabel = self.successLabel { + if let successLabel { Text("SignUp Succeeded \(successLabel)") .accessibilityLabel(Identifiers.successLabel) } @@ -57,8 +57,8 @@ struct SignUpView: View { } func signUp() async { - self.successLabel = nil - self.errorLabel = nil + successLabel = nil + errorLabel = nil print("Password \(password)") do { let options = AuthSignUpRequest.Options(userAttributes: [.init(.email, value: username)]) @@ -68,13 +68,13 @@ struct SignUpView: View { options: options ) if signUpResult.isSignUpComplete { - self.successLabel = "Complete" + successLabel = "Complete" } else { - self.errorLabel = "SignUp is not complete: \(signUpResult.nextStep)" + errorLabel = "SignUp is not complete: \(signUpResult.nextStep)" } } catch { print("Unexpected error: \(error)") - self.errorLabel = error.info() + errorLabel = error.info() } } } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedInView.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedInView.swift index 6fea279a8d..2361c25bfc 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedInView.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedInView.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import SwiftUI import Amplify import AWSCognitoAuthPlugin +import SwiftUI struct SignedInView: View { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedOutView.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedOutView.swift index 5fa41255f9..17b426b927 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedOutView.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedOutView.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import SwiftUI import Amplify +import SwiftUI struct SignedOutView: View { @@ -42,11 +42,11 @@ struct SignedOutView: View { } .accessibility(identifier: Identifiers.signUpNav) Spacer() - if let error = self.errorLabel { + if let error = errorLabel { Text("Error occured: \(error)") .accessibilityLabel(Identifiers.errorLabel) } - if let successLabel = self.successLabel { + if let successLabel { Text("Succeeded: \(successLabel)") .accessibilityLabel(Identifiers.successLabel) } @@ -59,11 +59,11 @@ struct SignedOutView: View { do { let signInResult = try await Amplify.Auth.signInWithWebUI(presentationAnchor: anchor) if signInResult.isSignedIn { - self.successLabel = "SignedIn" + successLabel = "SignedIn" } } catch { print("Unexpected error: \(error)") - self.errorLabel = error.info() + errorLabel = error.info() } } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/AuthenticationTest/HostedUISignInTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/AuthenticationTest/HostedUISignInTests.swift index 8bfc88e1e0..650865b1c8 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/AuthenticationTest/HostedUISignInTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/AuthenticationTest/HostedUISignInTests.swift @@ -26,7 +26,7 @@ class HostedUISignInTests: UITestCase { .dismissSignInAlert() .signIn(username: username, password: password) .testSignInSucceeded() - + } func testSignInWithoutPresentationAnchorSuccess() throws { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/AuthenticatedScreen.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/AuthenticatedScreen.swift index e184c1e758..c064594f52 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/AuthenticatedScreen.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/AuthenticatedScreen.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest struct AuthenticatedScreen: Screen { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/SignInScreen.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/SignInScreen.swift index 26d1584c2d..9d46a4f7de 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/SignInScreen.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/SignInScreen.swift @@ -51,16 +51,16 @@ struct SignInScreen: Screen { func signIn(username: String, password: String) -> Self { - let signInTextFieldName: String + let signInTextFieldName // Ideally we align the provisioning of Gen1 and Gen2 backends // to create a HostedUI endpoint that has the same username text field. // The Gen1 steps are updated in the README already, we re-provision the backend // in Gen1 according to those steps, this check can be removed and expect // "Email Email" to be the text field. - if useGen2Configuration { - signInTextFieldName = "Email Email" + = if useGen2Configuration { + "Email Email" } else { - signInTextFieldName = "Username" + "Username" } _ = app.webViews.textFields[signInTextFieldName].waitForExistence(timeout: 60) diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/UITestCase.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/UITestCase.swift index 86e4450d4a..1f2512c3c8 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/UITestCase.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/UITestCase.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest protocol Screen { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/API/AWSAppSyncConfiguration.swift b/AmplifyPlugins/Core/AWSPluginsCore/API/AWSAppSyncConfiguration.swift index e7d41af6d7..ac93bc3e99 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/API/AWSAppSyncConfiguration.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/API/AWSAppSyncConfiguration.swift @@ -11,7 +11,7 @@ import Foundation /// Hold necessary AWS AppSync configuration values to interact with the AppSync API public struct AWSAppSyncConfiguration { - + /// The region of the AWS AppSync API public let region: String @@ -32,13 +32,15 @@ public struct AWSAppSyncConfiguration { guard let dataCategory = resolvedConfiguration.data else { throw ConfigurationError.invalidAmplifyOutputsFile( - "Missing data category", "", nil) + "Missing data category", "", nil + ) } self.region = dataCategory.awsRegion guard let endpoint = URL(string: dataCategory.url) else { throw ConfigurationError.invalidAmplifyOutputsFile( - "Missing region from data category", "", nil) + "Missing region from data category", "", nil + ) } self.endpoint = endpoint self.apiKey = dataCategory.apiKey diff --git a/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift b/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift index f3035b76f0..d496276231 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Plugin specific options type /// @@ -20,8 +20,10 @@ public struct AWSAPIPluginDataStoreOptions { /// name of the model public let modelName: String - public init(authType: AWSAuthorizationType?, - modelName: String) { + public init( + authType: AWSAuthorizationType?, + modelName: String + ) { self.authType = authType self.modelName = modelName } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift b/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift index b6f83ec2b3..a6a11decb4 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Plugin specific options type /// @@ -37,8 +37,10 @@ public struct AWSPluginOptions { /// name of the model public let modelName: String? - public init(authType: AWSAuthorizationType?, - modelName: String) { + public init( + authType: AWSAuthorizationType?, + modelName: String + ) { self.authType = authType self.modelName = modelName } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift index d53920f158..15d338b1dc 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import Combine import Amplify +import Combine +import Foundation /// Represents different auth strategies supported by a client /// interfacing with an AppSync backend @@ -56,7 +56,7 @@ public protocol AuthorizationTypeIterator { /// Total number of values var count: Int { get } - + /// Whether iterator has next available `AuthorizationType` to return or not var hasNext: Bool { get } @@ -85,7 +85,7 @@ public struct AWSAuthorizationTypeIterator: AuthorizationTypeIterator, Sequence, public var count: Int { _count } - + public var hasNext: Bool { _position < _count } @@ -95,7 +95,7 @@ public struct AWSAuthorizationTypeIterator: AuthorizationTypeIterator, Sequence, _position += 1 return value } - + return nil } } @@ -108,15 +108,19 @@ public struct AWSAuthorizationTypeIterator: AuthorizationTypeIterator, Sequence, /// registered as interceptor for the API public class AWSDefaultAuthModeStrategy: AuthModeStrategy { public weak var authDelegate: AuthModeStrategyDelegate? - required public init() {} + public required init() {} - public func authTypesFor(schema: ModelSchema, - operation: ModelOperation) -> AWSAuthorizationTypeIterator { + public func authTypesFor( + schema: ModelSchema, + operation: ModelOperation + ) -> AWSAuthorizationTypeIterator { return AWSAuthorizationTypeIterator(withValues: [.inferred]) } - public func authTypesFor(schema: ModelSchema, - operations: [ModelOperation]) -> AWSAuthorizationTypeIterator { + public func authTypesFor( + schema: ModelSchema, + operations: [ModelOperation] + ) -> AWSAuthorizationTypeIterator { return AWSAuthorizationTypeIterator(withValues: [.inferred]) } } @@ -129,7 +133,7 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { private typealias AuthPriority = Int - required public init() {} + public required init() {} private static func defaultAuthTypeFor(authStrategy: AuthStrategy) -> AWSAuthorizationType { switch authStrategy { @@ -210,8 +214,10 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { /// - schema: model schema /// - operation: model operation /// - Returns: an iterator for the applicable auth rules - public func authTypesFor(schema: ModelSchema, - operation: ModelOperation) async -> AWSAuthorizationTypeIterator { + public func authTypesFor( + schema: ModelSchema, + operation: ModelOperation + ) async -> AWSAuthorizationTypeIterator { return await authTypesFor(schema: schema, operations: [operation]) } @@ -220,19 +226,21 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { /// - schema: model schema /// - operations: model operations /// - Returns: an iterator for the applicable auth rules - public func authTypesFor(schema: ModelSchema, - operations: [ModelOperation]) async -> AWSAuthorizationTypeIterator { + public func authTypesFor( + schema: ModelSchema, + operations: [ModelOperation] + ) async -> AWSAuthorizationTypeIterator { var sortedRules = operations .flatMap { schema.authRules.filter(modelOperation: $0) } - .reduce(into: [AuthRule](), { array, rule in + .reduce(into: [AuthRule]()) { array, rule in if !array.contains(rule) { array.append(rule) } - }) + } .sorted(by: AWSMultiAuthModeStrategy.comparator) // if there isn't a user signed in, returns only public or custom rules - if let authDelegate = authDelegate, await !authDelegate.isUserLoggedIn() { + if let authDelegate, await !authDelegate.isUserLoggedIn() { sortedRules = sortedRules.filter { rule in return rule.allow == .public || rule.allow == .custom } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift index b15b4b7d6c..338fdfaf7a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public class AWSAuthService: AWSAuthServiceBehavior { @@ -44,8 +44,12 @@ public class AWSAuthService: AWSAuthServiceBehavior { guard let claimsData = encodedData else { return .failure( - .validation("", "Cannot get claims in `Data` form. Token is not valid base64 encoded string.", - "", nil)) + .validation( + "", + "Cannot get claims in `Data` form. Token is not valid base64 encoded string.", + "", + nil + )) } let jsonObject: Any? @@ -53,14 +57,22 @@ public class AWSAuthService: AWSAuthServiceBehavior { jsonObject = try JSONSerialization.jsonObject(with: claimsData, options: []) } catch { return .failure( - .validation("", "Cannot get claims in `Data` form. Token is not valid JSON string.", - "", error)) + .validation( + "", + "Cannot get claims in `Data` form. Token is not valid JSON string.", + "", + error + )) } guard let convertedDictionary = jsonObject as? [String: AnyObject] else { return .failure( - .validation("", "Cannot get claims in `Data` form. Unable to convert to [String: AnyObject].", - "", nil)) + .validation( + "", + "Cannot get claims in `Data` form. Unable to convert to [String: AnyObject].", + "", + nil + )) } return .success(convertedDictionary) } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift index 1c23190588..2c18a89648 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public protocol AWSAuthServiceBehavior: AnyObject { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift index 36d71a87e8..6351485758 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Defines the contract for an AuthSession that can vend AWS credentials and store a user ID /// (`sub`) for the underlying OIDC-compliant authentication provider such as Cognito user pools. @@ -19,13 +19,13 @@ import Amplify /// successfully completed a `signIn` flow, and has not subsequently signed out. public protocol AWSAuthSessionBehavior: AuthSession { - /// The concrete type holding the OIDC tokens from the authentication provider. + /// The concrete type holding the OIDC tokens from the authentication provider. /// Generally, this type will have at least methods for retrieving an identity token and an access token. associatedtype Tokens /// The result of the most recent attempt to get AWS Credentials. There is no guarantee that the credentials /// are not expired, but conforming types may have logic in place to automatically refresh the credentials. - /// The credentials may be fore either the unauthenticated or authenticated role, depending on the + /// The credentials may be fore either the unauthenticated or authenticated role, depending on the /// configuration of the identity pool and the tokens used to retrieve the identity ID from Cognito. /// /// If the most recent attempt caused an error, the result will contain the details of the error. @@ -34,7 +34,7 @@ public protocol AWSAuthSessionBehavior: AuthSession { // swiftlint:disable line_length /// The result of the most recent attempt to get a /// [Cognito identity pool identity ID](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html#CognitoIdentity-GetId-response-IdentityId). - /// The identityID may represent either an unauthenticated or authenticated identity, + /// The identityID may represent either an unauthenticated or authenticated identity, /// depending on the configuration of the identity pool and the tokens used to /// retrieve the identity ID from Cognito. /// @@ -49,7 +49,7 @@ public protocol AWSAuthSessionBehavior: AuthSession { /// If the most recent attempt caused an error, the result will contain the details of the error. var userSubResult: Result { get } - /// The result of the most recent attempt to get the current user's `sub` (unique User ID). + /// The result of the most recent attempt to get the current user's `sub` (unique User ID). /// Depending on the underlying implementation, /// the details of the tokens may vary, but it is expected that the type will have at least methods for /// retrieving an identity token and an access token. diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthorizationType.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthorizationType.swift index 10e03c70a9..ebd4e05d4d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthorizationType.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthorizationType.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation // swiftlint:disable line_length @@ -49,8 +49,8 @@ extension AWSAuthorizationType: CaseIterable { } extension AWSAuthorizationType: Codable { } /// Indicates whether the authotization type requires the auth plugin to operate. -extension AWSAuthorizationType { - public var requiresAuthPlugin: Bool { +public extension AWSAuthorizationType { + var requiresAuthPlugin: Bool { switch self { case .none, .apiKey, .openIDConnect, .function: return false diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AmplifyAuthorizationType.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AmplifyAuthorizationType.swift index 18a90e3106..562a2f9c87 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AmplifyAuthorizationType.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AmplifyAuthorizationType.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation /// - Warning: Although this has `public` access, it is intended for internal use and should not be used directly diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AuthAWSCredentialsProvider.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AuthAWSCredentialsProvider.swift index 9739e1066f..d254f8b7f2 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AuthAWSCredentialsProvider.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AuthAWSCredentialsProvider.swift @@ -17,14 +17,13 @@ public extension AuthAWSCredentialsProvider where Self: AWSAuthSessionBehavior { /// Return the most recent Result of fetching the AWS Credentials. If the temporary credentials are expired, returns /// a `AuthError.sessionExpired` failure. func getAWSCredentials() -> Result { - let result: Result - switch awsCredentialsResult { - case .failure(let error): result = .failure(error) + let result: Result = switch awsCredentialsResult { + case .failure(let error): .failure(error) case .success(let tempCreds): if tempCreds.expiration > Date() { - result = .success(tempCreds) + .success(tempCreds) } else { - result = .failure(AuthError.sessionExpired("AWS Credentials are expired", "")) + .failure(AuthError.sessionExpired("AWS Credentials are expired", "")) } } return result diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Configuration/AWSAuthorizationConfiguration.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Configuration/AWSAuthorizationConfiguration.swift index cf7c78395a..57168ab230 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Configuration/AWSAuthorizationConfiguration.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Configuration/AWSAuthorizationConfiguration.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public enum AWSAuthorizationConfiguration { case none @@ -21,9 +21,11 @@ public enum AWSAuthorizationConfiguration { extension AWSAuthorizationConfiguration { private static func awsIAMAuthorizationConfiguration(region: String?) throws -> AWSAuthorizationConfiguration { - guard let region = region else { - throw PluginError.pluginConfigurationError("Region is not set for IAM", - "Set the region") + guard let region else { + throw PluginError.pluginConfigurationError( + "Region is not set for IAM", + "Set the region" + ) } return .awsIAM(AWSIAMConfiguration(region: region)) } @@ -31,7 +33,7 @@ extension AWSAuthorizationConfiguration { private static func apiKeyAuthorizationConfiguration(apiKey: String?) throws -> AWSAuthorizationConfiguration { - guard let apiKey = apiKey else { + guard let apiKey else { throw PluginError.pluginConfigurationError( "Could not get `ApiKey` from plugin configuration", """ @@ -53,9 +55,11 @@ extension AWSAuthorizationConfiguration { /// - Throws: if the region is not valid and `authType` is `iam` /// or if `apiKey` is not valid and `authType` is `apiKey` /// - Returns: an `AWSAuthorizationConfiguration` according to the provided `authType` - public static func makeConfiguration(authType: AWSAuthorizationType, - region: String?, - apiKey: String?) throws -> AWSAuthorizationConfiguration { + public static func makeConfiguration( + authType: AWSAuthorizationType, + region: String?, + apiKey: String? + ) throws -> AWSAuthorizationConfiguration { switch authType { case .none: return .none diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift index 3b7ccee072..7cc6f37e33 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift @@ -24,11 +24,11 @@ extension KeychainStatus: CustomStringConvertible { self = .success case -128: self = .userCanceled - case -25299: + case -25_299: self = .duplicateItem - case -25300: + case -25_300: self = .itemNotFound - case -34018: + case -34_018: self = .missingEntitlement default: self = .unexpectedError(status) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift index b82d0c434b..0a96cf57ed 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation import Security -import Amplify // swiftlint:disable identifier_name public protocol KeychainStoreBehavior { @@ -233,7 +233,7 @@ public struct KeychainStore: KeychainStoreBehavior { } extension KeychainStore { - struct Constants { + enum Constants { /** Class Key Constant */ static let Class = String(kSecClass) static let ClassGenericPassword = String(kSecClassGenericPassword) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreAttributes.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreAttributes.swift index a638b2879b..bbbab1d275 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreAttributes.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreAttributes.swift @@ -24,7 +24,7 @@ extension KeychainStoreAttributes { KeychainStore.Constants.UseDataProtectionKeyChain: kCFBooleanTrue ] - if let accessGroup = accessGroup { + if let accessGroup { query[KeychainStore.Constants.AttributeAccessGroup] = accessGroup } return query diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel+Codable.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel+Codable.swift index 911e93d357..b83f334295 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel+Codable.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Custom implementation of Codable for AnyModel stores the instance as its JSON string representation and uses the /// ModelRegistry utilities to deserialize it diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel+Subscript.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel+Subscript.swift index 044b8c4b04..4cf0c0f2ec 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel+Subscript.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel+Subscript.swift @@ -10,15 +10,15 @@ /// ```swift /// let id = model["id"] /// ``` -extension AnyModel { +public extension AnyModel { - public subscript(_ key: String) -> Any? { + subscript(_ key: String) -> Any? { let mirror = Mirror(reflecting: instance) let property = mirror.children.first { $0.label == key } return property?.value } - public subscript(_ key: CodingKey) -> Any? { + subscript(_ key: CodingKey) -> Any? { return self[key.stringValue] } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel.swift index c6646a606a..d739bde176 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public struct AnyModel: Model { public let id: String @@ -33,24 +33,26 @@ public struct AnyModel: Model { } } -extension AnyModel { +public extension AnyModel { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case instance case modelName } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { definition in + static let schema = defineSchema { definition in let anyModel = AnyModel.keys - definition.attributes(.isSystem, - .primaryKey(fields: [anyModel.id])) + definition.attributes( + .isSystem, + .primaryKey(fields: [anyModel.id]) + ) definition.fields( .field(anyModel.id, is: .required, ofType: .string), diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift index 0cf0f79d04..384e2564c6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public typealias IdentityClaimsDictionary = [String: AnyObject] @@ -37,19 +37,25 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { /// - authRuleDecoratorInput: decorator input /// - authType: authentication type, if provided will be used to filter the auth rules based on the provider field. /// Only use when multi-auth is enabled. - public init(_ authRuleDecoratorInput: AuthRuleDecoratorInput, - authType: AWSAuthorizationType? = nil) { + public init( + _ authRuleDecoratorInput: AuthRuleDecoratorInput, + authType: AWSAuthorizationType? = nil + ) { self.input = authRuleDecoratorInput self.authType = authType } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { let authRules = modelSchema.authRules .filterBy(authType: authType) .filterBy(ownerFieldType: .string, modelSchema: modelSchema) @@ -59,19 +65,24 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { var decorateDocument = document let readRestrictingStaticGroups = authRules.groupClaimsToReadRestrictingStaticGroups() - authRules.forEach { authRule in - decorateDocument = decorateAuthStrategy(document: decorateDocument, - authRule: authRule, - readRestrictingStaticGroups: readRestrictingStaticGroups) + for authRule in authRules { + decorateDocument = decorateAuthStrategy( + document: decorateDocument, + authRule: authRule, + readRestrictingStaticGroups: readRestrictingStaticGroups + ) } return decorateDocument } - private func decorateAuthStrategy(document: SingleDirectiveGraphQLDocument, - authRule: AuthRule, - readRestrictingStaticGroups: [String: Set]) -> SingleDirectiveGraphQLDocument { + private func decorateAuthStrategy( + document: SingleDirectiveGraphQLDocument, + authRule: AuthRule, + readRestrictingStaticGroups: [String: Set] + ) -> SingleDirectiveGraphQLDocument { guard authRule.allow == .owner, - var selectionSet = document.selectionSet else { + var selectionSet = document.selectionSet + else { return document } @@ -81,12 +92,16 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { if case let .subscription(_, claims) = input, let tokenClaims = claims, authRule.isReadRestrictingOwner() && - isNotInReadRestrictingStaticGroup(jwtTokenClaims: tokenClaims, - readRestrictingStaticGroups: readRestrictingStaticGroups) { + isNotInReadRestrictingStaticGroup( + jwtTokenClaims: tokenClaims, + readRestrictingStaticGroups: readRestrictingStaticGroups + ) { var inputs = document.inputs - let identityClaimValue = resolveIdentityClaimValue(identityClaim: authRule.identityClaimOrDefault(), - claims: tokenClaims) - if let identityClaimValue = identityClaimValue { + let identityClaimValue = resolveIdentityClaimValue( + identityClaim: authRule.identityClaimOrDefault(), + claims: tokenClaims + ) + if let identityClaimValue { inputs[ownerField] = GraphQLDocumentInput(type: "String!", value: .scalar(identityClaimValue)) } return document.copy(inputs: inputs, selectionSet: selectionSet) @@ -106,8 +121,10 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { return document.copy(selectionSet: selectionSet) } - private func isNotInReadRestrictingStaticGroup(jwtTokenClaims: IdentityClaimsDictionary, - readRestrictingStaticGroups: [String: Set]) -> Bool { + private func isNotInReadRestrictingStaticGroup( + jwtTokenClaims: IdentityClaimsDictionary, + readRestrictingStaticGroups: [String: Set] + ) -> Bool { for (groupClaim, readRestrictingStaticGroupsPerClaim) in readRestrictingStaticGroups { let groupsFromClaim = groupsFrom(jwtTokenClaims: jwtTokenClaims, groupClaim: groupClaim) let doesNotBelongToGroupsFromClaim = readRestrictingStaticGroupsPerClaim.isEmpty || @@ -121,8 +138,10 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { return true } - private func groupsFrom(jwtTokenClaims: IdentityClaimsDictionary, - groupClaim: String) -> Set { + private func groupsFrom( + jwtTokenClaims: IdentityClaimsDictionary, + groupClaim: String + ) -> Set { var groupSet = Set() if let groups = (jwtTokenClaims[groupClaim] as? NSArray) as Array? { for group in groups { @@ -146,11 +165,13 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { } /// First finds the first `model` SelectionSet. Then, only append it when the `ownerField` does not exist. - private func appendOwnerFieldToSelectionSetIfNeeded(selectionSet: SelectionSet, - ownerField: String) -> SelectionSet { + private func appendOwnerFieldToSelectionSetIfNeeded( + selectionSet: SelectionSet, + ownerField: String + ) -> SelectionSet { var selectionSetModel = selectionSet while selectionSetModel.value.fieldType != .model { - selectionSetModel.children.forEach { selectionSet in + for selectionSet in selectionSetModel.children { if selectionSet.value.fieldType == .model { selectionSetModel = selectionSet } @@ -158,7 +179,7 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { } - let containersOwnerField = selectionSetModel.children.contains { (field) -> Bool in + let containersOwnerField = selectionSetModel.children.contains { field -> Bool in if let fieldName = field.value.name, fieldName == ownerField { return true } @@ -175,7 +196,7 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { private extension AuthRule { func ownerField(inSchema schema: ModelSchema) -> ModelField? { - guard let fieldName = self.ownerField else { + guard let fieldName = ownerField else { return nil } return schema.field(withName: fieldName) @@ -184,7 +205,7 @@ private extension AuthRule { private extension AuthRules { func filterBy(authType: AWSAuthorizationType?) -> AuthRules { - guard let authType = authType else { + guard let authType else { return self } @@ -199,8 +220,10 @@ private extension AuthRules { } } - func filterBy(ownerFieldType: ModelFieldType, - modelSchema: ModelSchema) -> AuthRules { + func filterBy( + ownerFieldType: ModelFieldType, + modelSchema: ModelSchema + ) -> AuthRules { return filter { guard let modelField = $0.ownerField(inSchema: modelSchema) else { // if we couldn't find the owner field means it has been implicitly diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift index 7d17b01e57..455d8f35c1 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift @@ -19,30 +19,36 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { private let graphQLType: GraphQLOperationType private var primaryKeysOnly: Bool - public init(version: Int? = nil, - lastSync: Int64? = nil, - graphQLType: GraphQLOperationType, - primaryKeysOnly: Bool = true) { + public init( + version: Int? = nil, + lastSync: Int64? = nil, + graphQLType: GraphQLOperationType, + primaryKeysOnly: Bool = true + ) { self.version = version self.lastSync = lastSync self.graphQLType = graphQLType self.primaryKeysOnly = primaryKeysOnly } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { var primaryKeysOnly = primaryKeysOnly if primaryKeysOnly && ModelRegistry.modelType(from: modelSchema.name)?.rootPath == nil { primaryKeysOnly = false } var inputs = document.inputs - if let version = version, + if let version, case .mutation = document.operationType, var input = inputs["input"], case var .object(value) = input.value { @@ -52,7 +58,7 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { inputs["input"] = input } - if let lastSync = lastSync, case .query = document.operationType { + if let lastSync, case .query = document.operationType { inputs["lastSync"] = GraphQLDocumentInput(type: "AWSTimestamp", value: .scalar(lastSync)) } @@ -69,9 +75,11 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { case deletedFieldOnly } /// Append the correct conflict resolution fields for `model` and `pagination` selection sets. - private func addConflictResolution(selectionSet: SelectionSet, - primaryKeysOnly: Bool, - includeSyncMetadataFields: SyncMetadataFields = .full) { + private func addConflictResolution( + selectionSet: SelectionSet, + primaryKeysOnly: Bool, + includeSyncMetadataFields: SyncMetadataFields = .full + ) { var includeSyncMetadataFields = includeSyncMetadataFields switch selectionSet.value.fieldType { case .value, .embedded: @@ -93,23 +101,27 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { if !primaryKeysOnly || graphQLType == .mutation { // Continue to add version fields for all levels, for backwards compatibility // Reduce the selection set only when the type is "subscription" and "query" - // (specifically for syncQuery). Selection set for mutation should not be reduced + // (specifically for syncQuery). Selection set for mutation should not be reduced // because it needs to be the full selection set to send mutation events to older iOS clients, // which do not have the reduced subscription selection set. // subscriptions and sync query is to receive data, so it can be reduced to allow decoding to the // LazyReference type. - selectionSet.children.forEach { child in - addConflictResolution(selectionSet: child, - primaryKeysOnly: primaryKeysOnly, - includeSyncMetadataFields: .full) + for child in selectionSet.children { + addConflictResolution( + selectionSet: child, + primaryKeysOnly: primaryKeysOnly, + includeSyncMetadataFields: .full + ) } } else { // Only add all the sync metadata fields once. Once this was done once, `includeSyncMetadataFields` // should be set to `.deletedFieldOnly` and passed down to the recursive call stack. - selectionSet.children.forEach { child in - addConflictResolution(selectionSet: child, - primaryKeysOnly: primaryKeysOnly, - includeSyncMetadataFields: includeSyncMetadataFields) + for child in selectionSet.children { + addConflictResolution( + selectionSet: child, + primaryKeysOnly: primaryKeysOnly, + includeSyncMetadataFields: includeSyncMetadataFields + ) } } } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/DirectiveNameDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/DirectiveNameDecorator.swift index 5776552be9..9e2ec3671a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/DirectiveNameDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/DirectiveNameDecorator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Replaces the directive name of the GraphQL document based on Amplify GraphQL operation types such as "get", "list", /// "sync", "create", "update", "delete", "onCreate", "onUpdate", and "onDelete". The GraphQL name is constructed based @@ -35,23 +35,27 @@ public struct DirectiveNameDecorator: ModelBasedGraphQLDocumentDecorator { self.subscriptionType = type } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { - if let queryType = queryType { + if let queryType { return document.copy(name: modelSchema.graphQLName(queryType: queryType)) } - if let mutationType = mutationType { + if let mutationType { return document.copy(name: modelSchema.graphQLName(mutationType: mutationType)) } - if let subscriptionType = subscriptionType { + if let subscriptionType { return document.copy(name: modelSchema.graphQLName(subscriptionType: subscriptionType)) } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift index bd78aad37f..6d7dea2894 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift @@ -18,13 +18,17 @@ public struct FilterDecorator: ModelBasedGraphQLDocumentDecorator { self.filter = filter } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { guard !filter.isEmpty else { return document.copy(inputs: document.inputs) } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/IncludeAssociationDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/IncludeAssociationDecorator.swift index 66da65a63d..8ee92d10ab 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/IncludeAssociationDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/IncludeAssociationDecorator.swift @@ -18,13 +18,17 @@ public struct IncludeAssociationDecorator: ModelBasedGraphQLDocumentDecorator { self.includedAssociations = includedAssociations } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { return decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { if includedAssociations.isEmpty { return document } @@ -32,7 +36,7 @@ public struct IncludeAssociationDecorator: ModelBasedGraphQLDocumentDecorator { return document } - includedAssociations.forEach { association in + for association in includedAssociations { // we don't include the root reference because it refers to the root model // fields in the selection set, only the nested/included ones are needed if let associationSelectionSet = association.asSelectionSet(includeRoot: false) { @@ -82,7 +86,7 @@ extension PropertyContainerPath { let selectionSets = nodesInPath(node: self).map(getSelectionSet(node:)) return selectionSets.dropFirst().reduce(selectionSets.first) { partialResult, selectionSet in - guard let partialResult = partialResult else { + guard let partialResult else { return selectionSet } selectionSet.replaceChild(partialResult) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift index 8a848b48a9..328da76ab0 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift @@ -5,17 +5,21 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public protocol ModelBasedGraphQLDocumentDecorator { @available(*, deprecated, message: """ Decorating using Model.Type is deprecated, instead use modelSchema method. """) - func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument + func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument - func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument + func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift index 7a7ef66cfb..ef6b871951 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Decorate the GraphQL document with the data from an instance of the model. This is added as a single parameter /// called "input" that can be referenced by other decorators to append additional document inputs. This decorator @@ -21,21 +21,25 @@ public struct ModelDecorator: ModelBasedGraphQLDocumentDecorator { self.mutationType = mutationType } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { var inputs = document.inputs var graphQLInput = model.graphQLInputForMutation(modelSchema, mutationType: mutationType) if !modelSchema.authRules.isEmpty { - modelSchema.authRules.forEach { authRule in + for authRule in modelSchema.authRules { if authRule.allow == .owner { let ownerField = authRule.getOwnerFieldOrDefault() - graphQLInput = graphQLInput.filter { (field, value) -> Bool in + graphQLInput = graphQLInput.filter { field, value -> Bool in if field == ownerField, value == nil { return false } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift index 07a9a2d523..df7c5595a7 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Decorate the GraphQLDocument with the value of `ModelIdentifier` for a "delete" mutation or "get" query. public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { @@ -17,8 +17,10 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { var firstField = true self.identifierFields = model.identifier(schema: schema).fields.compactMap { fieldName, _ in - guard let value = model.graphQLInputForPrimaryKey(modelFieldName: fieldName, - modelSchema: schema) else { + guard let value = model.graphQLInputForPrimaryKey( + modelFieldName: fieldName, + modelSchema: schema + ) else { return nil } if firstField { @@ -32,7 +34,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { public init(identifierFields: [(name: String, value: Persistable)]) { var firstField = true - identifierFields.forEach { name, value in + for (name, value) in identifierFields { self.identifierFields.append((name: name, value: Self.convert(persistable: value), type: firstField == true ? "ID!" : "String!")) firstField = false } @@ -40,10 +42,10 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { public init(identifiers: [LazyReferenceIdentifier]) { var firstField = true - identifiers.forEach({ identifier in - self.identifierFields.append((name: identifier.name, value: identifier.value, type: firstField == true ? "ID!": "String!")) + for identifier in identifiers { + identifierFields.append((name: identifier.name, value: identifier.value, type: firstField == true ? "ID!" : "String!")) firstField = false - }) + } } @available(*, deprecated, message: "Use init(model:schema:)") @@ -56,7 +58,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { let identifier = (name: ModelIdentifierFormat.Default.name, value: id, type: "ID!") var identifierFields = [identifier] - if let fields = fields { + if let fields { identifierFields.append(contentsOf: fields.map { key, value in (name: key, value: value, type: "String!") }) @@ -64,13 +66,17 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { self.identifierFields = identifierFields } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { var inputs = document.inputs if case .mutation = document.operationType { @@ -94,7 +100,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { } } -fileprivate extension ModelIdDecorator { +private extension ModelIdDecorator { private static func convert(persistable: Persistable) -> GraphQLDocumentValueRepresentable { switch persistable { case let data as Double: diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/PaginationDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/PaginationDecorator.swift index bfe683ee55..3de8605169 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/PaginationDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/PaginationDecorator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Decorate the document input with "limit" and "nextToken". Also paginates the selection set with pagination fields. public struct PaginationDecorator: ModelBasedGraphQLDocumentDecorator { @@ -19,29 +19,35 @@ public struct PaginationDecorator: ModelBasedGraphQLDocumentDecorator { self.nextToken = nextToken } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { var inputs = document.inputs - if let limit = limit { + if let limit { inputs["limit"] = GraphQLDocumentInput(type: "Int", value: .scalar(limit)) } else { inputs["limit"] = GraphQLDocumentInput(type: "Int", value: .scalar(1_000)) } - if let nextToken = nextToken { + if let nextToken { inputs["nextToken"] = GraphQLDocumentInput(type: "String", value: .scalar(nextToken)) } if let selectionSet = document.selectionSet { - return document.copy(inputs: inputs, - selectionSet: withPagination(selectionSet: selectionSet)) + return document.copy( + inputs: inputs, + selectionSet: withPagination(selectionSet: selectionSet) + ) } return document.copy(inputs: inputs) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift index ca03962ded..e681be161c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift @@ -5,16 +5,18 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// A concrete implementation of `SingleDirectiveGraphQLDocument` that represents a mutation operation. public struct GraphQLMutation: SingleDirectiveGraphQLDocument { - public init(operationType: GraphQLOperationType, - name: String, - inputs: [GraphQLParameterName: GraphQLDocumentInput], - selectionSet: SelectionSet?) { + public init( + operationType: GraphQLOperationType, + name: String, + inputs: [GraphQLParameterName: GraphQLDocumentInput], + selectionSet: SelectionSet? + ) { self.operationType = operationType self.name = name self.inputs = inputs diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift index 2f86d9cb44..1c7b60732f 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift @@ -5,16 +5,18 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// A concrete implementation of `SingleDirectiveGraphQLDocument` that represents a query operation. public struct GraphQLQuery: SingleDirectiveGraphQLDocument { - public init(operationType: GraphQLOperationType, - name: String, - inputs: [GraphQLParameterName: GraphQLDocumentInput], - selectionSet: SelectionSet?) { + public init( + operationType: GraphQLOperationType, + name: String, + inputs: [GraphQLParameterName: GraphQLDocumentInput], + selectionSet: SelectionSet? + ) { self.operationType = operationType self.name = name self.inputs = inputs diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLSubscription.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLSubscription.swift index d2cfdf77a0..a558138dc3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLSubscription.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLSubscription.swift @@ -11,10 +11,12 @@ import Foundation /// A concrete implementation of `SingleDirectiveGraphQLDocument` that represents a subscription operation. public struct GraphQLSubscription: SingleDirectiveGraphQLDocument { - public init(operationType: GraphQLOperationType, - name: String, - inputs: [GraphQLParameterName: GraphQLDocumentInput], - selectionSet: SelectionSet?) { + public init( + operationType: GraphQLOperationType, + name: String, + inputs: [GraphQLParameterName: GraphQLDocumentInput], + selectionSet: SelectionSet? + ) { self.operationType = operationType self.name = name self.inputs = inputs diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift index a737d57d2f..7247580d35 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Helps construct a `SingleDirectiveGraphQLDocument`. Collects instances of the decorators and applies the changes /// on the document. @@ -54,7 +54,7 @@ public struct ModelBasedGraphQLDocumentBuilder { public mutating func build() -> SingleDirectiveGraphQLDocument { let decoratedDocument = decorators.reduce(document) { doc, decorator in - decorator.decorate(doc, modelSchema: self.modelSchema) + decorator.decorate(doc, modelSchema: modelSchema) } return decoratedDocument diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift index a219bf3ad7..2fad197f59 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift @@ -32,37 +32,43 @@ public protocol SingleDirectiveGraphQLDocument { var selectionSet: SelectionSet? { get set } /// Simple constructor to be implemented by the concrete types, used by the `copy` method. - init(operationType: GraphQLOperationType, - name: String, - inputs: [GraphQLParameterName: GraphQLDocumentInput], - selectionSet: SelectionSet?) + init( + operationType: GraphQLOperationType, + name: String, + inputs: [GraphQLParameterName: GraphQLDocumentInput], + selectionSet: SelectionSet? + ) } // Provides default implementation -extension SingleDirectiveGraphQLDocument { +public extension SingleDirectiveGraphQLDocument { /// Method to create a deep copy of the document, useful for `ModelBasedGraphQLDocumentDecorator` decorators /// when decorating a document and returning a new document. - public func copy(operationType: GraphQLOperationType? = nil, - name: String? = nil, - inputs: [GraphQLParameterName: GraphQLDocumentInput]? = nil, - selectionSet: SelectionSet? = nil) -> Self { - - return Self.init(operationType: operationType ?? self.operationType, - name: name ?? self.name, - inputs: inputs ?? self.inputs, - selectionSet: selectionSet ?? self.selectionSet) + func copy( + operationType: GraphQLOperationType? = nil, + name: String? = nil, + inputs: [GraphQLParameterName: GraphQLDocumentInput]? = nil, + selectionSet: SelectionSet? = nil + ) -> Self { + + return Self.init( + operationType: operationType ?? self.operationType, + name: name ?? self.name, + inputs: inputs ?? self.inputs, + selectionSet: selectionSet ?? self.selectionSet + ) } /// Returns nil when there are no `inputs`. Otherwise, consolidates the `inputs` /// into a single object that can be used for the GraphQL request. - public var variables: [String: Any]? { + var variables: [String: Any]? { if inputs.isEmpty { return nil } var variables = [String: Any]() - inputs.forEach { input in + for input in inputs { switch input.value.value { case .object(let values): variables.updateValue(values, forKey: input.key) @@ -78,7 +84,7 @@ extension SingleDirectiveGraphQLDocument { } /// Provides default construction of the graphQL document based on the components of the document. - public var stringValue: String { + var stringValue: String { let selectionSetString = selectionSet?.stringValue(indentSize: 2) ?? "" @@ -106,7 +112,7 @@ extension SingleDirectiveGraphQLDocument { return """ \(operationType.rawValue) \(name.pascalCased())\(variableInputTypes.isEmpty ? "" : "(\(variableInputTypes))") { - \(name)(\(inputParameters.map({ "\($0.0): \($0.1)"}).joined(separator: ", "))) { + \(name)(\(inputParameters.map { "\($0.0): \($0.1)"}.joined(separator: ", "))) { \(selectionSetString) } } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift index 44af846765..613b75e2ca 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift @@ -15,42 +15,56 @@ public typealias MutationSyncResult = MutationSync /// publicly exposed to developers protocol ModelSyncGraphQLRequestFactory { - static func query(modelName: String, - byId id: String, - authType: AWSAuthorizationType?) -> GraphQLRequest - - static func createMutation(of model: Model, - modelSchema: ModelSchema, - version: Int?, - authType: AWSAuthorizationType?) -> GraphQLRequest - - static func updateMutation(of model: Model, - modelSchema: ModelSchema, - where filter: GraphQLFilter?, - version: Int?, - authType: AWSAuthorizationType?) -> GraphQLRequest - - static func deleteMutation(of model: Model, - modelSchema: ModelSchema, - where filter: GraphQLFilter?, - version: Int?, - authType: AWSAuthorizationType?) -> GraphQLRequest - - static func subscription(to modelSchema: ModelSchema, - subscriptionType: GraphQLSubscriptionType, - authType: AWSAuthorizationType?) -> GraphQLRequest - - static func subscription(to modelSchema: ModelSchema, - subscriptionType: GraphQLSubscriptionType, - claims: IdentityClaimsDictionary, - authType: AWSAuthorizationType?) -> GraphQLRequest - - static func syncQuery(modelSchema: ModelSchema, - where predicate: QueryPredicate?, - limit: Int?, - nextToken: String?, - lastSync: Int64?, - authType: AWSAuthorizationType?) -> GraphQLRequest + static func query( + modelName: String, + byId id: String, + authType: AWSAuthorizationType? + ) -> GraphQLRequest + + static func createMutation( + of model: Model, + modelSchema: ModelSchema, + version: Int?, + authType: AWSAuthorizationType? + ) -> GraphQLRequest + + static func updateMutation( + of model: Model, + modelSchema: ModelSchema, + where filter: GraphQLFilter?, + version: Int?, + authType: AWSAuthorizationType? + ) -> GraphQLRequest + + static func deleteMutation( + of model: Model, + modelSchema: ModelSchema, + where filter: GraphQLFilter?, + version: Int?, + authType: AWSAuthorizationType? + ) -> GraphQLRequest + + static func subscription( + to modelSchema: ModelSchema, + subscriptionType: GraphQLSubscriptionType, + authType: AWSAuthorizationType? + ) -> GraphQLRequest + + static func subscription( + to modelSchema: ModelSchema, + subscriptionType: GraphQLSubscriptionType, + claims: IdentityClaimsDictionary, + authType: AWSAuthorizationType? + ) -> GraphQLRequest + + static func syncQuery( + modelSchema: ModelSchema, + where predicate: QueryPredicate?, + limit: Int?, + nextToken: String?, + lastSync: Int64?, + authType: AWSAuthorizationType? + ) -> GraphQLRequest } @@ -58,12 +72,16 @@ protocol ModelSyncGraphQLRequestFactory { /// as `version` and `lastSync` and returns a model that has been erased to `AnyModel`. extension GraphQLRequest: ModelSyncGraphQLRequestFactory { - public static func query(modelName: String, - byId id: String, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: modelName, - operationType: .query, - primaryKeysOnly: false) + public static func query( + modelName: String, + byId id: String, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: modelName, + operationType: .query, + primaryKeysOnly: false + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: ModelIdDecorator(id: id)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .query)) @@ -73,85 +91,111 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { let awsPluginOptions = AWSAPIPluginDataStoreOptions(authType: authType, modelName: modelName) let requestOptions = GraphQLRequest.Options(pluginOptions: awsPluginOptions) - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult?.self, - decodePath: document.name, - options: requestOptions) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult?.self, + decodePath: document.name, + options: requestOptions + ) } - public static func createMutation(of model: Model, - version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func createMutation( + of model: Model, + version: Int? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { createMutation(of: model, modelSchema: model.schema, version: version, authType: authType) } - public static func updateMutation(of model: Model, - where filter: GraphQLFilter? = nil, - version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func updateMutation( + of model: Model, + where filter: GraphQLFilter? = nil, + version: Int? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { updateMutation(of: model, modelSchema: model.schema, where: filter, version: version, authType: authType) } - public static func subscription(to modelType: Model.Type, - subscriptionType: GraphQLSubscriptionType, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func subscription( + to modelType: Model.Type, + subscriptionType: GraphQLSubscriptionType, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { subscription(to: modelType.schema, subscriptionType: subscriptionType, authType: authType) } - public static func subscription(to modelType: Model.Type, - subscriptionType: GraphQLSubscriptionType, - claims: IdentityClaimsDictionary, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func subscription( + to modelType: Model.Type, + subscriptionType: GraphQLSubscriptionType, + claims: IdentityClaimsDictionary, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { subscription(to: modelType.schema, subscriptionType: subscriptionType, claims: claims, authType: authType) } - public static func syncQuery(modelType: Model.Type, - where predicate: QueryPredicate? = nil, - limit: Int? = nil, - nextToken: String? = nil, - lastSync: Int64? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - syncQuery(modelSchema: modelType.schema, - where: predicate, - limit: limit, - nextToken: nextToken, - lastSync: lastSync, - authType: authType) + public static func syncQuery( + modelType: Model.Type, + where predicate: QueryPredicate? = nil, + limit: Int? = nil, + nextToken: String? = nil, + lastSync: Int64? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + syncQuery( + modelSchema: modelType.schema, + where: predicate, + limit: limit, + nextToken: nextToken, + lastSync: lastSync, + authType: authType + ) } - public static func createMutation(of model: Model, - modelSchema: ModelSchema, - version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func createMutation( + of model: Model, + modelSchema: ModelSchema, + version: Int? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { createOrUpdateMutation(of: model, modelSchema: modelSchema, type: .create, version: version, authType: authType) } - public static func updateMutation(of model: Model, - modelSchema: ModelSchema, - where filter: GraphQLFilter? = nil, - version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - createOrUpdateMutation(of: model, - modelSchema: modelSchema, - where: filter, - type: .update, - version: version, - authType: authType) + public static func updateMutation( + of model: Model, + modelSchema: ModelSchema, + where filter: GraphQLFilter? = nil, + version: Int? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + createOrUpdateMutation( + of: model, + modelSchema: modelSchema, + where: filter, + type: .update, + version: version, + authType: authType + ) } - public static func deleteMutation(of model: Model, - modelSchema: ModelSchema, - where filter: GraphQLFilter? = nil, - version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: modelSchema.name, - operationType: .mutation, - primaryKeysOnly: false) + public static func deleteMutation( + of model: Model, + modelSchema: ModelSchema, + where filter: GraphQLFilter? = nil, + version: Int? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: modelSchema.name, + operationType: .mutation, + primaryKeysOnly: false + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) - documentBuilder.add(decorator: ModelIdDecorator(model: model, - schema: modelSchema)) - if let filter = filter { + documentBuilder.add(decorator: ModelIdDecorator( + model: model, + schema: modelSchema + )) + if let filter { documentBuilder.add(decorator: FilterDecorator(filter: filter)) } documentBuilder.add(decorator: ConflictResolutionDecorator(version: version, graphQLType: .mutation, primaryKeysOnly: false)) @@ -161,20 +205,26 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { let awsPluginOptions = AWSAPIPluginDataStoreOptions(authType: authType, modelName: modelSchema.name) let requestOptions = GraphQLRequest.Options(pluginOptions: awsPluginOptions) - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult.self, - decodePath: document.name, - options: requestOptions) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult.self, + decodePath: document.name, + options: requestOptions + ) } - public static func subscription(to modelSchema: ModelSchema, - subscriptionType: GraphQLSubscriptionType, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func subscription( + to modelSchema: ModelSchema, + subscriptionType: GraphQLSubscriptionType, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, - operationType: .subscription, - primaryKeysOnly: true) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelSchema, + operationType: .subscription, + primaryKeysOnly: true + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: subscriptionType)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription, primaryKeysOnly: true)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(subscriptionType, nil), authType: authType)) @@ -182,21 +232,27 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { let awsPluginOptions = AWSAPIPluginDataStoreOptions(authType: authType, modelName: modelSchema.name) let requestOptions = GraphQLRequest.Options(pluginOptions: awsPluginOptions) - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult.self, - decodePath: document.name, - options: requestOptions) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult.self, + decodePath: document.name, + options: requestOptions + ) } - public static func subscription(to modelSchema: ModelSchema, - subscriptionType: GraphQLSubscriptionType, - claims: IdentityClaimsDictionary, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, - operationType: .subscription, - primaryKeysOnly: true) + public static func subscription( + to modelSchema: ModelSchema, + subscriptionType: GraphQLSubscriptionType, + claims: IdentityClaimsDictionary, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelSchema, + operationType: .subscription, + primaryKeysOnly: true + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: subscriptionType)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription, primaryKeysOnly: true)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(subscriptionType, claims), authType: authType)) @@ -207,22 +263,28 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { modelName: modelSchema.name ) let requestOptions = GraphQLRequest.Options(pluginOptions: awsPluginOptions) - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult.self, - decodePath: document.name, - options: requestOptions) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult.self, + decodePath: document.name, + options: requestOptions + ) } - public static func syncQuery(modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil, - limit: Int? = nil, - nextToken: String? = nil, - lastSync: Int64? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, - operationType: .query, - primaryKeysOnly: true) + public static func syncQuery( + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil, + limit: Int? = nil, + nextToken: String? = nil, + lastSync: Int64? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelSchema, + operationType: .query, + primaryKeysOnly: true + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) if let predicate = optimizePredicate(predicate) { documentBuilder.add(decorator: FilterDecorator(filter: predicate.graphQLFilter(for: modelSchema))) @@ -235,27 +297,33 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { let awsPluginOptions = AWSAPIPluginDataStoreOptions(authType: authType, modelName: modelSchema.name) let requestOptions = GraphQLRequest.Options(pluginOptions: awsPluginOptions) - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: SyncQueryResult.self, - decodePath: document.name, - options: requestOptions) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: SyncQueryResult.self, + decodePath: document.name, + options: requestOptions + ) } // MARK: Private methods - private static func createOrUpdateMutation(of model: Model, - modelSchema: ModelSchema, - where filter: GraphQLFilter? = nil, - type: GraphQLMutationType, - version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: modelSchema.name, - operationType: .mutation, - primaryKeysOnly: false) + private static func createOrUpdateMutation( + of model: Model, + modelSchema: ModelSchema, + where filter: GraphQLFilter? = nil, + type: GraphQLMutationType, + version: Int? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: modelSchema.name, + operationType: .mutation, + primaryKeysOnly: false + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: type)) documentBuilder.add(decorator: ModelDecorator(model: model, mutationType: type)) - if let filter = filter { + if let filter { documentBuilder.add(decorator: FilterDecorator(filter: filter)) } documentBuilder.add(decorator: ConflictResolutionDecorator(version: version, graphQLType: .mutation, primaryKeysOnly: false)) @@ -265,11 +333,13 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { let awsPluginOptions = AWSAPIPluginDataStoreOptions(authType: authType, modelName: modelSchema.name) let requestOptions = GraphQLRequest.Options(pluginOptions: awsPluginOptions) - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult.self, - decodePath: document.name, - options: requestOptions) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult.self, + decodePath: document.name, + options: requestOptions + ) } /// This function tries to optimize provided `QueryPredicate` to perform a DynamoDB query instead of a scan. @@ -278,7 +348,7 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { /// If the provided group is of type AND, the optimization will occur. /// If the top level group is OR or NOT, the optimization is not possible anyway. private static func optimizePredicate(_ predicate: QueryPredicate?) -> QueryPredicate? { - guard let predicate = predicate else { + guard let predicate else { return nil } if predicate as? QueryPredicateGroup != nil { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift index 7338fab830..47e3557d0a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift @@ -32,11 +32,13 @@ protocol ModelGraphQLRequestFactory { /// - Returns: a valid `GraphQLRequest` instance /// /// - seealso: `GraphQLQuery`, `GraphQLQueryType.list` - static func list(_ modelType: M.Type, - where predicate: QueryPredicate?, - includes: IncludedAssociations, - limit: Int?, - authMode: AWSAuthorizationType?) -> GraphQLRequest> + static func list( + _ modelType: M.Type, + where predicate: QueryPredicate?, + includes: IncludedAssociations, + limit: Int?, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest> /// Creates a `GraphQLRequest` that represents a query that expects a single value as a result. /// The request will be created with the correct correct document based on the `ModelSchema` and @@ -49,21 +51,27 @@ protocol ModelGraphQLRequestFactory { /// - Returns: a valid `GraphQLRequest` instance /// /// - seealso: `GraphQLQuery`, `GraphQLQueryType.get` - static func get(_ modelType: M.Type, - byId id: String, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest - - static func get(_ modelType: M.Type, - byIdentifier id: String, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func get( + _ modelType: M.Type, + byId id: String, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest + + static func get( + _ modelType: M.Type, + byIdentifier id: String, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default - static func get(_ modelType: M.Type, - byIdentifier id: ModelIdentifier, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func get( + _ modelType: M.Type, + byIdentifier id: ModelIdentifier, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest where M: ModelIdentifiable // MARK: Mutation @@ -76,12 +84,14 @@ protocol ModelGraphQLRequestFactory { /// - predicate: a predicate passed as the condition to apply the mutation /// - type: the mutation type, either `.create`, `.update`, or `.delete` /// - Returns: a valid `GraphQLRequest` instance - static func mutation(of model: M, - modelSchema: ModelSchema, - where predicate: QueryPredicate?, - includes: IncludedAssociations, - type: GraphQLMutationType, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func mutation( + of model: M, + modelSchema: ModelSchema, + where predicate: QueryPredicate?, + includes: IncludedAssociations, + type: GraphQLMutationType, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest /// Creates a `GraphQLRequest` that represents a create mutation /// for a given `model` instance. @@ -90,9 +100,11 @@ protocol ModelGraphQLRequestFactory { /// - model: the model instance populated with values /// - Returns: a valid `GraphQLRequest` instance /// - seealso: `GraphQLRequest.mutation(of:where:type:)` - static func create(_ model: M, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func create( + _ model: M, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest /// Creates a `GraphQLRequest` that represents an update mutation /// for a given `model` instance. @@ -102,10 +114,12 @@ protocol ModelGraphQLRequestFactory { /// - predicate: a predicate passed as the condition to apply the mutation /// - Returns: a valid `GraphQLRequest` instance /// - seealso: `GraphQLRequest.mutation(of:where:type:)` - static func update(_ model: M, - where predicate: QueryPredicate?, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func update( + _ model: M, + where predicate: QueryPredicate?, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest /// Creates a `GraphQLRequest` that represents a delete mutation /// for a given `model` instance. @@ -115,10 +129,12 @@ protocol ModelGraphQLRequestFactory { /// - predicate: a predicate passed as the condition to apply the mutation /// - Returns: a valid `GraphQLRequest` instance /// - seealso: `GraphQLRequest.mutation(of:where:type:)` - static func delete(_ model: M, - where predicate: QueryPredicate?, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func delete( + _ model: M, + where predicate: QueryPredicate?, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest // MARK: Subscription @@ -132,10 +148,12 @@ protocol ModelGraphQLRequestFactory { /// - Returns: a valid `GraphQLRequest` instance /// /// - seealso: `GraphQLSubscription`, `GraphQLSubscriptionType` - static func subscription(of: M.Type, - type: GraphQLSubscriptionType, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func subscription( + of: M.Type, + type: GraphQLSubscriptionType, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest } // MARK: - Extension @@ -146,7 +164,7 @@ protocol ModelGraphQLRequestFactory { /// This is particularly useful when using the GraphQL API to interact /// with static types that conform to the `Model` protocol. extension GraphQLRequest: ModelGraphQLRequestFactory { - private static func modelSchema(for model: M) -> ModelSchema { + private static func modelSchema(for model: some Model) -> ModelSchema { let modelType = ModelRegistry.modelType(from: model.modelName) ?? Swift.type(of: model) return modelType.schema } @@ -154,96 +172,124 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { public static func create( _ model: M, includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { return create( model, modelSchema: modelSchema(for: model), includes: includes, - authMode: authMode) + authMode: authMode + ) } - public static func update(_ model: M, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func update( + _ model: M, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { return update( model, modelSchema: modelSchema(for: model), where: predicate, includes: includes, - authMode: authMode) + authMode: authMode + ) } - public static func delete(_ model: M, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func delete( + _ model: M, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { return delete( model, modelSchema: modelSchema(for: model), - where: predicate, + where: predicate, includes: includes, - authMode: authMode) + authMode: authMode + ) } - public static func create(_ model: M, - modelSchema: ModelSchema, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - return mutation(of: model, - modelSchema: modelSchema, - includes: includes, - type: .create, - authMode: authMode) + public static func create( + _ model: M, + modelSchema: ModelSchema, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + return mutation( + of: model, + modelSchema: modelSchema, + includes: includes, + type: .create, + authMode: authMode + ) } - public static func update(_ model: M, - modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - return mutation(of: model, - modelSchema: modelSchema, - where: predicate, - includes: includes, - type: .update, - authMode: authMode) + public static func update( + _ model: M, + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + return mutation( + of: model, + modelSchema: modelSchema, + where: predicate, + includes: includes, + type: .update, + authMode: authMode + ) } - public static func delete(_ model: M, - modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - return mutation(of: model, - modelSchema: modelSchema, - where: predicate, - includes: includes, - type: .delete, - authMode: authMode) + public static func delete( + _ model: M, + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + return mutation( + of: model, + modelSchema: modelSchema, + where: predicate, + includes: includes, + type: .delete, + authMode: authMode + ) } - public static func mutation(of model: M, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - type: GraphQLMutationType, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - mutation(of: model, - modelSchema: model.schema, - where: predicate, - includes: includes, - type: type, - authMode: authMode) + public static func mutation( + of model: M, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + type: GraphQLMutationType, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + mutation( + of: model, + modelSchema: model.schema, + where: predicate, + includes: includes, + type: type, + authMode: authMode + ) } - public static func mutation(of model: M, - modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - type: GraphQLMutationType, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, - operationType: .mutation) + public static func mutation( + of model: M, + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + type: GraphQLMutationType, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelSchema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: type)) if let modelPath = M.rootPath as? ModelPath { @@ -255,32 +301,40 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { case .create: documentBuilder.add(decorator: ModelDecorator(model: model, mutationType: type)) case .delete: - documentBuilder.add(decorator: ModelIdDecorator(model: model, - schema: modelSchema)) - if let predicate = predicate { + documentBuilder.add(decorator: ModelIdDecorator( + model: model, + schema: modelSchema + )) + if let predicate { documentBuilder.add(decorator: FilterDecorator(filter: predicate.graphQLFilter(for: modelSchema))) } case .update: documentBuilder.add(decorator: ModelDecorator(model: model, mutationType: type)) - if let predicate = predicate { + if let predicate { documentBuilder.add(decorator: FilterDecorator(filter: predicate.graphQLFilter(for: modelSchema))) } } let document = documentBuilder.build() - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: M.self, - decodePath: document.name, - authMode: authMode) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: M.self, + decodePath: document.name, + authMode: authMode + ) } - public static func get(_ modelType: M.Type, - byId id: String, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .query) + public static func get( + _ modelType: M.Type, + byId id: String, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) if let modelPath = modelType.rootPath as? ModelPath { @@ -291,28 +345,36 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { documentBuilder.add(decorator: ModelIdDecorator(id: id)) let document = documentBuilder.build() - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: M?.self, - decodePath: document.name, - authMode: authMode) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: M?.self, + decodePath: document.name, + authMode: authMode + ) } - public static func get(_ modelType: M.Type, - byIdentifier id: String, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + public static func get( + _ modelType: M.Type, + byIdentifier id: String, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { return .get(modelType, byId: id, includes: includes, authMode: authMode) } - public static func get(_ modelType: M.Type, - byIdentifier id: ModelIdentifier, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + public static func get( + _ modelType: M.Type, + byIdentifier id: ModelIdentifier, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest where M: ModelIdentifiable { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) if let modelPath = modelType.rootPath as? ModelPath { @@ -322,21 +384,27 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { documentBuilder.add(decorator: ModelIdDecorator(identifierFields: id.fields)) let document = documentBuilder.build() - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: M?.self, - decodePath: document.name, - authMode: authMode) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: M?.self, + decodePath: document.name, + authMode: authMode + ) } - public static func list(_ modelType: M.Type, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - limit: Int? = nil, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest> { + public static func list( + _ modelType: M.Type, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + limit: Int? = nil, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest> { let primaryKeysOnly = (M.rootPath != nil) ? true : false - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) if let modelPath = modelType.rootPath as? ModelPath { @@ -344,26 +412,32 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { documentBuilder.add(decorator: IncludeAssociationDecorator(associations)) } - if let predicate = predicate { + if let predicate { documentBuilder.add(decorator: FilterDecorator(filter: predicate.graphQLFilter(for: modelType.schema))) } documentBuilder.add(decorator: PaginationDecorator(limit: limit)) let document = documentBuilder.build() - return GraphQLRequest>(document: document.stringValue, - variables: document.variables, - responseType: List.self, - decodePath: document.name, - authMode: authMode) + return GraphQLRequest>( + document: document.stringValue, + variables: document.variables, + responseType: List.self, + decodePath: document.name, + authMode: authMode + ) } - public static func subscription(of modelType: M.Type, - type: GraphQLSubscriptionType, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + public static func subscription( + of modelType: M.Type, + type: GraphQLSubscriptionType, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: type)) if let modelPath = modelType.rootPath as? ModelPath { @@ -373,10 +447,12 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { let document = documentBuilder.build() - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: modelType, - decodePath: document.name, - authMode: authMode) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: modelType, + decodePath: document.name, + authMode: authMode + ) } } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift index 72d6c1bcde..9c181f2d5c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift @@ -7,11 +7,11 @@ import Amplify -extension AuthRuleProvider { +public extension AuthRuleProvider { /// Returns corresponding `AWSAuthorizationType` for each `AuthRuleProvider` /// - Returns: AWS authorization type - public func toAWSAuthorizationType() -> AWSAuthorizationType { + func toAWSAuthorizationType() -> AWSAuthorizationType { var authType: AWSAuthorizationType switch self { case .apiKey: @@ -31,7 +31,7 @@ extension AuthRuleProvider { extension AuthRule { func getOwnerFieldOrDefault() -> String { - guard let ownerField = ownerField else { + guard let ownerField else { return "owner" } return ownerField @@ -53,7 +53,7 @@ extension AuthRule { } public func identityClaimOrDefault() -> String { - guard let identityClaim = self.identityClaim else { + guard let identityClaim else { return "username" } if identityClaim == "cognito:username" { @@ -63,7 +63,7 @@ extension AuthRule { } } -extension Array where Element == AuthRule { +extension [AuthRule] { // This function returns a map of all of the read restricting static groups defined for your app's schema // Example 1: Single group with implicit read restriction @@ -95,7 +95,7 @@ extension Array where Element == AuthRule { let readRestrictingGroupRules = filter { $0.isReadRestrictingStaticGroup() } for groupRule in readRestrictingGroupRules { let groupClaim = groupRule.groupClaim ?? "cognito:groups" - groupRule.groups.forEach { group in + for group in groupRule.groups { if var existingSet = readRestrictingStaticGroupsMap[groupClaim] { existingSet.insert(group) readRestrictingStaticGroupsMap[groupClaim] = existingSet diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift index 7b78a2dc47..4908fbca39 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation typealias GraphQLInput = [String: Any?] @@ -20,8 +20,10 @@ extension Model { private func fieldsForMutation(_ modelSchema: ModelSchema) -> [(ModelField, Any?)] { modelSchema.sortedFields.compactMap { field in guard !field.isReadOnly, - let fieldValue = getFieldValue(for: field.name, - modelSchema: modelSchema) else { + let fieldValue = getFieldValue( + for: field.name, + modelSchema: modelSchema + ) else { return nil } return (field, fieldValue) @@ -86,10 +88,12 @@ extension Model { input[name] = (value as? EnumPersistable)?.rawValue case .model(let associateModelName): // get the associated model target names and their values - let associatedModelIds = associatedModelIdentifierFields(fromModelValue: value, - field: modelField, - associatedModelName: associateModelName, - mutationType: mutationType) + let associatedModelIds = associatedModelIdentifierFields( + fromModelValue: value, + field: modelField, + associatedModelName: associateModelName, + mutationType: mutationType + ) for (fieldName, fieldValue) in associatedModelIds { input.updateValue(fieldValue, forKey: fieldName) } @@ -113,8 +117,10 @@ extension Model { /// Retrieve the custom primary key's value used for the GraphQL input. /// Only a subset of data types are applicable as custom indexes such as /// `date`, `dateTime`, `time`, `enum`, `string`, `double`, and `int`. - func graphQLInputForPrimaryKey(modelFieldName: ModelFieldName, - modelSchema: ModelSchema) -> String? { + func graphQLInputForPrimaryKey( + modelFieldName: ModelFieldName, + modelSchema: ModelSchema + ) -> String? { guard let modelField = modelSchema.field(withName: modelFieldName) else { return nil @@ -127,10 +133,11 @@ extension Model { } // swiftlint:disable:next syntactic_sugar + // swiftformat:disable typeSugar guard case .some(Optional.some(let value)) = fieldValue else { return nil } - + // swiftformat:enable typeSugar switch modelField.type { case .date, .dateTime, .time: if let date = value as? TemporalSpec { @@ -157,10 +164,12 @@ extension Model { /// - modelSchema: model schema /// - Returns: an array of key-value pairs where `key` is the field name /// and `value` its value in the associated model - private func associatedModelIdentifierFields(fromModelValue value: Any, - field: ModelField, - associatedModelName: String, - mutationType: GraphQLMutationType) -> [(String, Persistable?)] { + private func associatedModelIdentifierFields( + fromModelValue value: Any, + field: ModelField, + associatedModelName: String, + mutationType: GraphQLMutationType + ) -> [(String, Persistable?)] { guard let associateModelSchema = ModelRegistry.modelSchema(from: associatedModelName) else { preconditionFailure("Associated model \(associatedModelName) not found.") } @@ -199,13 +208,13 @@ extension Model { } else if let lazyModel = value as? (any _LazyReferenceValue) { switch lazyModel._state { case .notLoaded(let identifiers): - if let identifiers = identifiers { + if let identifiers { return identifiers.map { identifier in return identifier.value } } case .loaded(let model): - if let model = model { + if let model { return model.identifier(schema: modelSchema).values } } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift index 86f1d9445a..a88ed8907d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift @@ -16,17 +16,17 @@ extension ModelSchema { let graphQLName: String switch queryType { case .list: - if let listPluralName = listPluralName { + if let listPluralName { graphQLName = queryType.rawValue + listPluralName - } else if let pluralName = pluralName { + } else if let pluralName { graphQLName = queryType.rawValue + pluralName } else { graphQLName = (queryType.rawValue + name).pluralize() } case .sync: - if let syncPluralName = syncPluralName { + if let syncPluralName { graphQLName = queryType.rawValue + syncPluralName - } else if let pluralName = pluralName { + } else if let pluralName { graphQLName = queryType.rawValue + pluralName } else { graphQLName = (queryType.rawValue + name).pluralize() diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift index c7e6735920..ab0b8668f5 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public typealias GraphQLFilter = [String: Any] @@ -20,12 +20,16 @@ public struct GraphQLFilterConverter { /// Serialize the translated GraphQL query variable object to JSON string. /// - Warning: Although this has `public` access, it is intended for internal use and should not be used directly /// by host applications. The behavior of this may change without warning. - public static func toJSON(_ queryPredicate: QueryPredicate, - modelSchema: ModelSchema, - options: JSONSerialization.WritingOptions = []) throws -> String { + public static func toJSON( + _ queryPredicate: QueryPredicate, + modelSchema: ModelSchema, + options: JSONSerialization.WritingOptions = [] + ) throws -> String { let graphQLFilterData = - try JSONSerialization.data(withJSONObject: queryPredicate.graphQLFilter(for: modelSchema), - options: options) + try JSONSerialization.data( + withJSONObject: queryPredicate.graphQLFilter(for: modelSchema), + options: options + ) guard let serializedString = String(data: graphQLFilterData, encoding: .utf8) else { return Fatal.preconditionFailure(""" @@ -41,10 +45,14 @@ public struct GraphQLFilterConverter { Use `toJSON(_:modelSchema:options)` instead. See https://github.com/aws-amplify/amplify-ios/pull/965 for more details. """) /// Serialize the translated GraphQL query variable object to JSON string. - public static func toJSON(_ queryPredicate: QueryPredicate, - options: JSONSerialization.WritingOptions = []) throws -> String { - let graphQLFilterData = try JSONSerialization.data(withJSONObject: queryPredicate.graphQLFilter, - options: options) + public static func toJSON( + _ queryPredicate: QueryPredicate, + options: JSONSerialization.WritingOptions = [] + ) throws -> String { + let graphQLFilterData = try JSONSerialization.data( + withJSONObject: queryPredicate.graphQLFilter, + options: options + ) guard let serializedString = String(data: graphQLFilterData, encoding: .utf8) else { return Fatal.preconditionFailure(""" @@ -68,11 +76,11 @@ public struct GraphQLFilterConverter { } /// Extension to translate a `QueryPredicate` into a GraphQL query variables object -extension QueryPredicate { +public extension QueryPredicate { /// - Warning: Although this has `public` access, it is intended for internal use and should not be used directly /// by host applications. The behavior of this may change without warning. - public func graphQLFilter(for modelSchema: ModelSchema?) -> GraphQLFilter { + func graphQLFilter(for modelSchema: ModelSchema?) -> GraphQLFilter { if let operation = self as? QueryPredicateOperation { return operation.graphQLFilter(for: modelSchema) } else if let group = self as? QueryPredicateGroup { @@ -88,7 +96,7 @@ extension QueryPredicate { @available(*, deprecated, message: """ Use `graphQLFilter(for:)` instead. See https://github.com/aws-amplify/amplify-ios/pull/965 for more details. """) - public var graphQLFilter: GraphQLFilter { + var graphQLFilter: GraphQLFilter { if let operation = self as? QueryPredicateOperation { return operation.graphQLFilter(for: nil) } else if let group = self as? QueryPredicateGroup { @@ -113,7 +121,7 @@ extension QueryPredicateOperation: GraphQLFilterConvertible { func graphQLFilter(for modelSchema: ModelSchema?) -> GraphQLFilter { let filterValue = [self.operator.graphQLOperator: self.operator.value] - guard let modelSchema = modelSchema else { + guard let modelSchema else { return [field: filterValue] } return [columnName(modelSchema): filterValue] @@ -150,7 +158,7 @@ extension QueryPredicateGroup: GraphQLFilterConvertible { switch type { case .and, .or: var graphQLPredicateOperation = [logicalOperator: [Any]()] - predicates.forEach { predicate in + for predicate in predicates { graphQLPredicateOperation[logicalOperator]?.append(predicate.graphQLFilter(for: modelSchema)) } return graphQLPredicateOperation @@ -196,7 +204,7 @@ extension QueryOperator { switch self { case .notEqual(let value), .equals(let value): - if let value = value { + if let value { return value.graphQLValue() } @@ -221,7 +229,7 @@ extension QueryOperator { } extension Persistable { - internal func graphQLValue() -> Any { + func graphQLValue() -> Any { switch self { case is Bool: return self diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift index b926808de4..8a0d8d2bf3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public typealias SelectionSet = Tree @@ -43,11 +43,11 @@ extension SelectionSet { } func withModelFields(_ fields: [ModelField], recursive: Bool = true, primaryKeysOnly: Bool) { - fields.forEach { field in + for field in fields { if field.isEmbeddedType, let embeddedTypeSchema = field.embeddedTypeSchema { let child = SelectionSet(value: .init(name: field.name, fieldType: .embedded)) child.withEmbeddableFields(embeddedTypeSchema.sortedFields) - self.addChild(settingParentOf: child) + addChild(settingParentOf: child) } else if field._isBelongsToOrHasOne, let associatedModelName = field.associatedModelName, let schema = ModelRegistry.modelSchema(from: associatedModelName) { @@ -64,10 +64,10 @@ extension SelectionSet { child.withModelFields(schema.graphQLFields, recursive: recursive, primaryKeysOnly: primaryKeysOnly) } - self.addChild(settingParentOf: child) + addChild(settingParentOf: child) } } else { - self.addChild(settingParentOf: .init(value: .init(name: field.graphQLName, fieldType: .value))) + addChild(settingParentOf: .init(value: .init(name: field.graphQLName, fieldType: .value))) } } @@ -75,13 +75,13 @@ extension SelectionSet { } func withEmbeddableFields(_ fields: [ModelField]) { - fields.forEach { field in + for field in fields { if field.isEmbeddedType, let embeddedTypeSchema = field.embeddedTypeSchema { let child = SelectionSet(value: .init(name: field.name, fieldType: .embedded)) child.withEmbeddableFields(embeddedTypeSchema.sortedFields) - self.addChild(settingParentOf: child) + addChild(settingParentOf: child) } else { - self.addChild(settingParentOf: .init(value: .init(name: field.name, fieldType: .value))) + addChild(settingParentOf: .init(value: .init(name: field.name, fieldType: .value))) } } addChild(settingParentOf: .init(value: .typename)) @@ -112,12 +112,12 @@ extension SelectionSet { case .model, .pagination, .embedded: if let name = value.name { result.append(indent + name + " {") - children.forEach { innerSelectionSetField in + for innerSelectionSetField in children { result.append(innerSelectionSetField.stringValue(indentSize: indentSize + 1)) } result.append(indent + "}") } else { - children.forEach { innerSelectionSetField in + for innerSelectionSetField in children { result.append(innerSelectionSetField.stringValue(indentSize: indentSize)) } } @@ -125,7 +125,7 @@ extension SelectionSet { let doubleIndent = String(repeating: indentValue, count: indentSize + 1) result.append(indent + (value.name ?? "") + " {") result.append(doubleIndent + "items {") - children.forEach { innerSelectionSetField in + for innerSelectionSetField in children { result.append(innerSelectionSetField.stringValue(indentSize: indentSize + 2)) } result.append(doubleIndent + "}") @@ -181,7 +181,7 @@ extension SelectionSet { let name = selectionSet.value.name ?? "" if let existingField = findChild(byName: name) { var replaceFields: [SelectionSet] = [] - selectionSet.children.forEach { child in + for child in selectionSet.children { if child.value.fieldType != .value, let childName = child.value.name { if existingField.findChild(byName: childName) != nil { existingField.merge(with: child) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata+Schema.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata+Schema.swift index 99ec90c255..14675f4b99 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata+Schema.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata+Schema.swift @@ -8,21 +8,21 @@ import Amplify import Foundation -extension ModelSyncMetadata { +public extension ModelSyncMetadata { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case lastSync case syncPredicate } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { definition in + static let schema = defineSchema { definition in definition.attributes(.isSystem) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift index d6723f4835..fe17daa10c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift @@ -17,9 +17,11 @@ public struct ModelSyncMetadata: Model { /// The sync predicate for this model, extracted out from the sync expression. public var syncPredicate: String? - public init(id: String, - lastSync: Int64? = nil, - syncPredicate: String? = nil) { + public init( + id: String, + lastSync: Int64? = nil, + syncPredicate: String? = nil + ) { self.id = id self.lastSync = lastSync self.syncPredicate = syncPredicate diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSync.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSync.swift index 8348ac5132..1e2bf1f054 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSync.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSync.swift @@ -37,12 +37,14 @@ public struct MutationSync: Decodable { guard case let .string(modelName) = json["__typename"] else { throw DataStoreError.decodingError( "The key `__typename` was not found", - "Check if the parsed JSON contains the expected `__typename`") + "Check if the parsed JSON contains the expected `__typename`" + ) } guard let actualModelType = ModelRegistry.modelType(from: modelName) else { throw DataStoreError.decodingError( "Model named `\(modelName)` could not be resolved.", - "Make sure `\(modelName)` was registered using `ModelRegistry.register`") + "Make sure `\(modelName)` was registered using `ModelRegistry.register`" + ) } let model = try actualModelType.init(from: decoder) guard let anyModel = try model.eraseToAnyModel() as? ModelType else { @@ -52,7 +54,8 @@ public struct MutationSync: Decodable { Please take a look at https://github.com/aws-amplify/amplify-ios/issues to see if there are any existing issues that match your scenario, and file an issue with the details of the bug if there isn't. - """) + """ + ) } self.model = anyModel resolvedModelName = modelName @@ -67,10 +70,10 @@ public struct MutationSync: Decodable { // TODO query name could be useful for the message, but re-creating it here is not great let queryName = modelType.schema.syncPluralName ?? modelType.schema.pluralName ?? modelType.modelName throw DataStoreError.decodingError( - """ + """ Error decoding the the sync metadata from the delta sync query result. """, - """ + """ The sync metadata should contain fields named `_deleted`, `_lastChangedAt` and `_version`. Check your sync`\(queryName)` query and make sure it returns the correct set of sync fields. """ @@ -84,10 +87,12 @@ public struct MutationSync: Decodable { let modelIdentifier = model.identifier(schema: modelSchema).stringValue - self.syncMetadata = MutationSyncMetadata(modelId: modelIdentifier, - modelName: resolvedModelName, - deleted: deleted, - lastChangedAt: Int64(lastChangedAt), - version: Int(version)) + self.syncMetadata = MutationSyncMetadata( + modelId: modelIdentifier, + modelName: resolvedModelName, + deleted: deleted, + lastChangedAt: Int64(lastChangedAt), + version: Int(version) + ) } } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift index 718e3348f6..86e49d3fd6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift @@ -8,22 +8,22 @@ import Amplify import Foundation -extension MutationSyncMetadata { +public extension MutationSyncMetadata { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case deleted case lastChangedAt case version } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { definition in + static let schema = defineSchema { definition in let sync = MutationSyncMetadata.keys definition.attributes(.isSystem) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/PaginatedList.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/PaginatedList.swift index 1458988802..5b31f43057 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/PaginatedList.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/PaginatedList.swift @@ -28,18 +28,18 @@ public struct PaginatedList: Decodable { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let optimisticDecodedResults = try values.decode([OptimisticDecoded>].self, forKey: .items) - items = optimisticDecodedResults.compactMap { try? $0.result.get() } - nextToken = try values.decode(String?.self, forKey: .nextToken) - startedAt = try values.decode(Int64?.self, forKey: .startedAt) + self.items = optimisticDecodedResults.compactMap { try? $0.result.get() } + self.nextToken = try values.decode(String?.self, forKey: .nextToken) + self.startedAt = try values.decode(Int64?.self, forKey: .startedAt) } } -fileprivate struct OptimisticDecoded: Decodable { +private struct OptimisticDecoded: Decodable { let result: Result init(from decoder: Decoder) throws { - result = Result(catching: { + self.result = Result(catching: { try T(from: decoder) }) } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/AmplifyNetworkMonitor.swift b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/AmplifyNetworkMonitor.swift index 85801c4bd5..22a0a5546a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/AmplifyNetworkMonitor.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/AmplifyNetworkMonitor.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Network import Combine +import Network @_spi(WebSocket) public final class AmplifyNetworkMonitor { @@ -28,7 +28,7 @@ public final class AmplifyNetworkMonitor { } public init(on interface: NWInterface.InterfaceType? = nil) { - monitor = interface.map(NWPathMonitor.init(requiredInterfaceType:)) ?? NWPathMonitor() + self.monitor = interface.map(NWPathMonitor.init(requiredInterfaceType:)) ?? NWPathMonitor() monitor.pathUpdateHandler = { [weak self] path in self?.subject.send(path.status == .satisfied ? .online : .offline) } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/RetryWithJitter.swift b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/RetryWithJitter.swift index 9da51cb03f..502301fdb1 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/RetryWithJitter.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/RetryWithJitter.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation @_spi(WebSocket) @@ -17,7 +16,7 @@ public actor RetryWithJitter { let max: UInt var retryCount: UInt = 0 - init(base: UInt = 25, max: UInt = 6400) { + init(base: UInt = 25, max: UInt = 6_400) { self.base = base self.max = max } @@ -28,16 +27,16 @@ public actor RetryWithJitter { func next() -> UInt { let expo = min(max, powerOf2(count: retryCount) * base) retryCount += 1 - return UInt.random(in: 0..( +public extension RetryWithJitter { + static func execute( maxRetryCount: UInt = 8, shouldRetryOnError: (Swift.Error) -> Bool = { _ in true }, _ operation: @escaping () async throws -> Output @@ -51,7 +50,7 @@ extension RetryWithJitter { let backoffInterval = retryCount == 0 ? 0 : await retryWithJitter.next() do { try await Task.sleep(nanoseconds: UInt64(backoffInterval) * 1_000_000) - return .success(try await operation()) + return try await .success(operation()) } catch { print("[RetryWithJitter] operation failed with error \(error), retrying(\(retryCount))") if shouldRetryOnError(error) { @@ -65,7 +64,7 @@ extension RetryWithJitter { } } -fileprivate func powerOf2(count: UInt) -> UInt { +private func powerOf2(count: UInt) -> UInt { count == 0 ? 1 : 2 * powerOf2(count: count - 1) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketClient.swift b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketClient.swift index e2e8c85503..7c6c0601ec 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketClient.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketClient.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Amplify import Combine +import Foundation /** WebSocketClient wraps URLSessionWebSocketTask and offers @@ -40,7 +39,7 @@ public final actor WebSocketClient: NSObject { /// The underlying URLSessionWebSocketTask private var connection: URLSessionWebSocketTask? { willSet { - self.connection?.cancel(with: .goingAway, reason: nil) + connection?.cancel(with: .goingAway, reason: nil) } } @@ -50,11 +49,11 @@ public final actor WebSocketClient: NSObject { private var autoRetryOnConnectionFailure: Bool /// Data stream for downstream subscribers to engage with public var publisher: AnyPublisher { - self.subject.eraseToAnyPublisher() + subject.eraseToAnyPublisher() } public var isConnected: Bool { - self.connection?.state == .running + connection?.state == .running } /** @@ -107,7 +106,7 @@ public final actor WebSocketClient: NSObject { autoConnectOnNetworkStatusChange: Bool = false, autoRetryOnConnectionFailure: Bool = false ) async { - guard self.connection?.state != .running else { + guard connection?.state != .running else { log.debug("[WebSocketClient] WebSocket is already in connecting state") return } @@ -116,7 +115,7 @@ public final actor WebSocketClient: NSObject { self.autoConnectOnNetworkStatusChange = autoConnectOnNetworkStatusChange self.autoRetryOnConnectionFailure = autoRetryOnConnectionFailure - await self.createConnectionAndRead() + await createConnectionAndRead() } /** @@ -125,14 +124,14 @@ public final actor WebSocketClient: NSObject { This will halt all automatic processes and attempt to gracefully close the connection. */ public func disconnect() { - guard self.connection?.state == .running else { + guard connection?.state == .running else { log.debug("[WebSocketClient] client should be in connected state to trigger disconnect") return } - self.autoConnectOnNetworkStatusChange = false - self.autoRetryOnConnectionFailure = false - self.connection?.cancel(with: .goingAway, reason: nil) + autoConnectOnNetworkStatusChange = false + autoRetryOnConnectionFailure = false + connection?.cancel(with: .goingAway, reason: nil) } /** @@ -142,7 +141,7 @@ public final actor WebSocketClient: NSObject { */ public func write(message: String) async throws { log.debug("[WebSocketClient] WebSocket write message string: \(message)") - try await self.connection?.send(.string(message)) + try await connection?.send(.string(message)) } /** @@ -152,15 +151,15 @@ public final actor WebSocketClient: NSObject { */ public func write(message: Data) async throws { log.debug("[WebSocketClient] WebSocket write message data: \(message)") - try await self.connection?.send(.data(message)) + try await connection?.send(.data(message)) } private func createWebSocketConnection() async -> URLSessionWebSocketTask { - let decoratedURL = (await self.interceptor?.interceptConnection(url: self.url)) ?? self.url + let decoratedURL = await (interceptor?.interceptConnection(url: url)) ?? url var urlRequest = URLRequest(url: decoratedURL) - self.handshakeHttpHeaders.forEach { urlRequest.setValue($0.value, forHTTPHeaderField: $0.key) } + handshakeHttpHeaders.forEach { urlRequest.setValue($0.value, forHTTPHeaderField: $0.key) } - urlRequest = await self.interceptor?.interceptConnection(request: urlRequest) ?? urlRequest + urlRequest = await interceptor?.interceptConnection(request: urlRequest) ?? urlRequest let urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: nil) return urlSession.webSocketTask(with: urlRequest) @@ -168,19 +167,19 @@ public final actor WebSocketClient: NSObject { private func createConnectionAndRead() async { log.debug("[WebSocketClient] Creating new connection and starting read") - self.connection = await createWebSocketConnection() + connection = await createWebSocketConnection() // Perform reading from a WebSocket in a separate task recursively to avoid blocking the execution. Task { await self.startReadMessage() } - self.connection?.resume() + connection?.resume() } /** Recusively read WebSocket data frames and publish to data stream. */ private func startReadMessage() async { - guard let connection = self.connection else { + guard let connection else { log.debug("[WebSocketClient] WebSocket connection doesn't exist") return } @@ -209,32 +208,32 @@ public final actor WebSocketClient: NSObject { } } - await self.startReadMessage() + await startReadMessage() } } // MARK: - URLSession delegate extension WebSocketClient: URLSessionWebSocketDelegate { - nonisolated public func urlSession( + public nonisolated func urlSession( _ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String? ) { log.debug("[WebSocketClient] Websocket connected") - self.subject.send(.connected) + subject.send(.connected) } - nonisolated public func urlSession( + public nonisolated func urlSession( _ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? ) { log.debug("[WebSocketClient] Websocket disconnected") - self.subject.send(.disconnected(closeCode, reason.flatMap { String(data: $0, encoding: .utf8) })) + subject.send(.disconnected(closeCode, reason.flatMap { String(data: $0, encoding: .utf8) })) } - nonisolated public func urlSession( + public nonisolated func urlSession( _ session: URLSession, task: URLSessionTask, didCompleteWithError error: Swift.Error? @@ -250,15 +249,15 @@ extension WebSocketClient: URLSessionWebSocketDelegate { switch (nsError.domain, nsError.code) { case (NSURLErrorDomain.self, NSURLErrorNetworkConnectionLost), // connection lost (NSPOSIXErrorDomain.self, Int(ECONNABORTED)): // background to foreground - self.subject.send(.error(WebSocketClient.Error.connectionLost)) + subject.send(.error(WebSocketClient.Error.connectionLost)) Task { [weak self] in await self?.networkMonitor.updateState(.offline) } case (NSURLErrorDomain.self, NSURLErrorCancelled): log.debug("Skipping NSURLErrorCancelled error") - self.subject.send(.error(WebSocketClient.Error.connectionCancelled)) + subject.send(.error(WebSocketClient.Error.connectionCancelled)) default: - self.subject.send(.error(error)) + subject.send(.error(error)) } } } @@ -278,18 +277,18 @@ extension WebSocketClient { private func onNetworkStateChange( _ stateChange: (AmplifyNetworkMonitor.State, AmplifyNetworkMonitor.State) ) async { - guard self.autoConnectOnNetworkStatusChange == true else { + guard autoConnectOnNetworkStatusChange == true else { return } switch stateChange { case (.online, .offline): log.debug("[WebSocketClient] NetworkMonitor - Device went offline") - self.connection?.cancel(with: .invalid, reason: nil) - self.subject.send(.disconnected(.invalid, nil)) + connection?.cancel(with: .invalid, reason: nil) + subject.send(.disconnected(.invalid, nil)) case (.offline, .online): log.debug("[WebSocketClient] NetworkMonitor - Device back online") - await self.createConnectionAndRead() + await createConnectionAndRead() default: break } @@ -311,7 +310,7 @@ extension WebSocketClient { } .store(in: &cancelables) - self.resetRetryCountOnConnected() + resetRetryCountOnConnected() } private func resetRetryCountOnConnected() { @@ -330,7 +329,7 @@ extension WebSocketClient { } private func retryOnCloseCode(_ closeCode: URLSessionWebSocketTask.CloseCode) async { - guard self.autoRetryOnConnectionFailure == true else { + guard autoRetryOnConnectionFailure == true else { return } @@ -357,9 +356,9 @@ extension WebSocketClient: DefaultLogger { extension WebSocketClient: Resettable { public func reset() async { - self.subject.send(completion: .finished) - self.autoConnectOnNetworkStatusChange = false - self.autoRetryOnConnectionFailure = false + subject.send(completion: .finished) + autoConnectOnNetworkStatusChange = false + autoRetryOnConnectionFailure = false cancelables = Set() } } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketEvent.swift b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketEvent.swift index 35c101dd6e..8bb6d32e32 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketEvent.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketEvent.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation @_spi(WebSocket) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketInterceptor.swift b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketInterceptor.swift index 351119ff03..2122e5c3d7 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketInterceptor.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketInterceptor.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation @_spi(WebSocket) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketNetworkMonitorProtocol.swift b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketNetworkMonitorProtocol.swift index 3966e7ab9d..82b275494c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketNetworkMonitorProtocol.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketNetworkMonitorProtocol.swift @@ -5,9 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Combine +import Foundation @_spi(WebSocket) public protocol WebSocketNetworkMonitorProtocol { diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/API/AWSAppSyncConfigurationTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/API/AWSAppSyncConfigurationTests.swift index 42813dc3f7..4c3141f98d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/API/AWSAppSyncConfigurationTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/API/AWSAppSyncConfigurationTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore +import XCTest @_spi(InternalAmplifyConfiguration) @testable import Amplify final class AWSAppSyncConfigurationTests: XCTestCase { @@ -18,7 +18,8 @@ final class AWSAppSyncConfigurationTests: XCTestCase { modelIntrospection: nil, apiKey: "apiKey123", defaultAuthorizationType: .amazonCognitoUserPools, - authorizationTypes: [.apiKey, .awsIAM])) + authorizationTypes: [.apiKey, .awsIAM] + )) let encoder = JSONEncoder() let data = try! encoder.encode(config) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift index 8674e962cb..32a41d8d7b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift @@ -89,9 +89,11 @@ class AuthModeStrategyTests: XCTestCase { let authMode = AWSMultiAuthModeStrategy() let delegate = UnauthenticatedUserDelegate() authMode.authDelegate = delegate - - var authTypesIterator = await authMode.authTypesFor(schema: ModelWithOwnerAndPublicAuth.schema, - operation: .create) + + var authTypesIterator = await authMode.authTypesFor( + schema: ModelWithOwnerAndPublicAuth.schema, + operation: .create + ) XCTAssertEqual(authTypesIterator.count, 1) XCTAssertEqual(authTypesIterator.next()?.awsAuthType, .apiKey) } @@ -101,8 +103,10 @@ class AuthModeStrategyTests: XCTestCase { // Then: applicable auth types returned respect the priority rules func testMultiAuthPriorityWithCustomStrategy() async { let authMode = AWSMultiAuthModeStrategy() - var authTypesIterator = await authMode.authTypesFor(schema: ModelWithCustomStrategy.schema, - operation: .create) + var authTypesIterator = await authMode.authTypesFor( + schema: ModelWithCustomStrategy.schema, + operation: .create + ) XCTAssertEqual(authTypesIterator.count, 3) XCTAssertEqual(authTypesIterator.next()?.awsAuthType, .function) XCTAssertEqual(authTypesIterator.next()?.awsAuthType, .amazonCognitoUserPools) @@ -117,8 +121,10 @@ class AuthModeStrategyTests: XCTestCase { let delegate = UnauthenticatedUserDelegate() authMode.authDelegate = delegate - var authTypesIterator = await authMode.authTypesFor(schema: ModelWithCustomStrategy.schema, - operation: .create) + var authTypesIterator = await authMode.authTypesFor( + schema: ModelWithCustomStrategy.schema, + operation: .create + ) XCTAssertEqual(authTypesIterator.count, 2) XCTAssertEqual(authTypesIterator.next()?.awsAuthType, .function) XCTAssertEqual(authTypesIterator.next()?.awsAuthType, .awsIAM) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelMultipleOwnerAuthRuleTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelMultipleOwnerAuthRuleTests.swift index b6ae079862..a9a50bce1a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelMultipleOwnerAuthRuleTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelMultipleOwnerAuthRuleTests.swift @@ -9,6 +9,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSPluginsCore + /* type ModelMultipleOwner @model @auth(rules: [ @@ -26,9 +27,11 @@ public struct ModelMultipleOwner: Model { public let id: String public var content: String public var editors: [String]? - public init(id: String = UUID().uuidString, - content: String, - editors: [String]? = []) { + public init( + id: String = UUID().uuidString, + content: String, + editors: [String]? = [] + ) { self.id = id self.content = content self.editors = editors @@ -71,11 +74,13 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { override func tearDown() { ModelRegistry.reset() } - + // Ensure that the `owner` field is added to the model fields func testModelMultipleOwner_CreateMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -97,8 +102,10 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelMultipleOwner_DeleteMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -120,8 +127,10 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelMultipleOwner_UpdateMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -143,8 +152,10 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelMultipleOwner_GetQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: AuthRuleDecorator(.query)) let document = documentBuilder.build() @@ -166,8 +177,10 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // A List query is a paginated selection set, make sure the `owner` field is added to the model fields func testModelMultipleOwner_ListQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: AuthRuleDecorator(.query)) @@ -191,8 +204,10 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { } func testModelMultipleOwner_SyncQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .query)) @@ -219,13 +234,17 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { XCTAssertEqual(document.name, "syncModelMultipleOwners") XCTAssertEqual(document.stringValue, expectedQueryDocument) } - + // Only the 'owner' inherently has `.create` operation, requiring the subscription operation to contain the input func testModelMultipleOwner_OnCreateSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -251,10 +270,14 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // Each owner with `.update` operation requires the ownerField on the corresponding subscription operation func testModelMultipleOwner_OnUpdateSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onUpdate, claims))) let document = documentBuilder.build() @@ -280,10 +303,14 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // Only the 'owner' inherently has `.delete` operation, requiring the subscription operation to contain the input func testModelMultipleOwner_OnDeleteSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, claims))) let document = documentBuilder.build() diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift index 778945a24f..d31f860e4c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift @@ -23,8 +23,10 @@ import XCTest public struct ModelReadUpdateField: Model { public let id: String public var content: String - public init(id: String = UUID().uuidString, - content: String) { + public init( + id: String = UUID().uuidString, + content: String + ) { self.id = id self.content = content } @@ -41,7 +43,8 @@ public struct ModelReadUpdateField: Model { ] model.fields( .id(), - .field(modelReadUpdateField.content, is: .required, ofType: .string)) + .field(modelReadUpdateField.content, is: .required, ofType: .string) + ) } } @@ -57,8 +60,10 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelReadUpdateField_CreateMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -79,8 +84,10 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelReadUpdateField_DeleteMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -101,8 +108,10 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelReadUpdateField_UpdateMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -123,8 +132,10 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelReadUpdateField_GetQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: AuthRuleDecorator(.query)) let document = documentBuilder.build() @@ -145,8 +156,10 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // A List query is a paginated selection set, make sure the `owner` field is added to the model fields func testModelReadUpdateField_ListQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: AuthRuleDecorator(.query)) @@ -169,8 +182,10 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { } func testModelReadUpdateField_SyncQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .query)) @@ -199,10 +214,14 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // The owner auth rule contains `.create` operation, requiring the subscription operation to contain the input func testModelReadUpdateField_OnCreateSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -223,10 +242,14 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // Others can `.update` this model, which means the update subscription does not require owner input func testModelReadUpdateField_OnUpdateSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onUpdate, claims))) let document = documentBuilder.build() @@ -246,10 +269,14 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // The owner auth rule contains `.delete` operation, requiring the subscription operation to contain the input func testModelReadUpdateField_OnDeleteSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, claims))) let document = documentBuilder.build() diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift index a1d37b50fd..a321edca6e 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift @@ -32,9 +32,11 @@ public struct OIDCGroupPost: Model { public var title: String public var owner: String? - public init(id: String = UUID().uuidString, - title: String, - owner: String? = nil) { + public init( + id: String = UUID().uuidString, + title: String, + owner: String? = nil + ) { self.id = id self.title = title self.owner = owner @@ -52,23 +54,27 @@ public struct OIDCGroupPost: Model { let oIDCGroupPost = OIDCGroupPost.keys model.authRules = [ - rule(allow: .owner, - ownerField: "owner", - identityClaim: "sub", - operations: [.create, .update, .delete, .read]), - rule(allow: .groups, - groupClaim: "https://myapp.com/claims/groups", - groups: ["Admins"], - operations: [.create, .update, .delete, .read]) + rule( + allow: .owner, + ownerField: "owner", + identityClaim: "sub", + operations: [.create, .update, .delete, .read] + ), + rule( + allow: .groups, + groupClaim: "https://myapp.com/claims/groups", + groups: ["Admins"], + operations: [.create, .update, .delete, .read] + ) ] model.listPluralName = "OIDCGroupPosts" model.syncPluralName = "OIDCGroupPosts" model.fields( - .id(), - .field(oIDCGroupPost.title, is: .required, ofType: .string), - .field(oIDCGroupPost.owner, is: .optional, ofType: .string) + .id(), + .field(oIDCGroupPost.title, is: .required, ofType: .string), + .field(oIDCGroupPost.owner, is: .optional, ofType: .string) ) } } @@ -83,10 +89,14 @@ class ModelWithOwnerAuthAndGroupWithGroupClaim: XCTestCase { } func testOnCreateSubscription_NoGroupInfoPassed() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -110,11 +120,15 @@ class ModelWithOwnerAuthAndGroupWithGroupClaim: XCTestCase { } func testOnCreateSubscription_InAdminsGroup() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://myapp.com/claims/groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://myapp.com/claims/groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -134,11 +148,15 @@ class ModelWithOwnerAuthAndGroupWithGroupClaim: XCTestCase { } func testOnCreateSubscription_InAdminsGroupAndAnother() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://myapp.com/claims/groups": ["Admins", "Users"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://myapp.com/claims/groups": ["Admins", "Users"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -158,11 +176,15 @@ class ModelWithOwnerAuthAndGroupWithGroupClaim: XCTestCase { } func testOnCreateSubscription_NotInAdminsGroup() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://myapp.com/claims/groups": ["Users"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://myapp.com/claims/groups": ["Users"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift index 03ac101b21..e302631d99 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift @@ -34,9 +34,11 @@ public struct OIDCMultiGroupPost: Model { public var title: String public var owner: String? - public init(id: String = UUID().uuidString, - title: String, - owner: String? = nil) { + public init( + id: String = UUID().uuidString, + title: String, + owner: String? = nil + ) { self.id = id self.title = title self.owner = owner @@ -54,18 +56,24 @@ public struct OIDCMultiGroupPost: Model { let oIDCMultiGroupPost = OIDCMultiGroupPost.keys model.authRules = [ - rule(allow: .owner, - ownerField: "owner", - identityClaim: "sub", - operations: [.create, .update, .delete, .read]), - rule(allow: .groups, - groupClaim: "https://myapp.com/claims/groups", - groups: ["Admins"], - operations: [.create, .update, .delete, .read]), - rule(allow: .groups, - groupClaim: "https://differentapp.com/claims/groups", - groups: ["Moderators", "Editors"], - operations: [.create, .update, .delete, .read]) + rule( + allow: .owner, + ownerField: "owner", + identityClaim: "sub", + operations: [.create, .update, .delete, .read] + ), + rule( + allow: .groups, + groupClaim: "https://myapp.com/claims/groups", + groups: ["Admins"], + operations: [.create, .update, .delete, .read] + ), + rule( + allow: .groups, + groupClaim: "https://differentapp.com/claims/groups", + groups: ["Moderators", "Editors"], + operations: [.create, .update, .delete, .read] + ) ] model.listPluralName = "OIDCMultiGroupPosts" model.syncPluralName = "OIDCMultiGroupPosts" @@ -87,10 +95,14 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { } func testOnCreateSubscription_NoGroupInfoPassed() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCMultiGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCMultiGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -110,17 +122,23 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { XCTFail("The document doesn't contain variables") return } - XCTAssertEqual(variables["owner"] as? String, - "123e4567-dead-beef-a456-426614174000", - "owner should exist since there were no groups present in the claims to match the schema") + XCTAssertEqual( + variables["owner"] as? String, + "123e4567-dead-beef-a456-426614174000", + "owner should exist since there were no groups present in the claims to match the schema" + ) } func testOnCreateSubscription_InDifferentAppWithModerators() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://differentapp.com/claims/groups": ["Moderators"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCMultiGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://differentapp.com/claims/groups": ["Moderators"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCMultiGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -136,16 +154,22 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { """ XCTAssertEqual(document.name, "onCreateOIDCMultiGroupPost") XCTAssertEqual(document.stringValue, expectedQueryDocument) - XCTAssertTrue(document.variables.isEmpty, - "variables should be empty since claim group value matches the auth rule schema") + XCTAssertTrue( + document.variables.isEmpty, + "variables should be empty since claim group value matches the auth rule schema" + ) } func testOnCreateSubscription_InDifferentAppWithModeratorsAndEditors() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://differentapp.com/claims/groups": ["Moderators", "Editors"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCMultiGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://differentapp.com/claims/groups": ["Moderators", "Editors"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCMultiGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -161,16 +185,22 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { """ XCTAssertEqual(document.name, "onCreateOIDCMultiGroupPost") XCTAssertEqual(document.stringValue, expectedQueryDocument) - XCTAssertTrue(document.variables.isEmpty, - "variables should be empty since claim group value matches the auth rule schema") + XCTAssertTrue( + document.variables.isEmpty, + "variables should be empty since claim group value matches the auth rule schema" + ) } func testOnCreateSubscription_InDifferentAppWithAdminsFromMyApp() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://myapp.com/claims/groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCMultiGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://myapp.com/claims/groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCMultiGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -186,16 +216,22 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { """ XCTAssertEqual(document.name, "onCreateOIDCMultiGroupPost") XCTAssertEqual(document.stringValue, expectedQueryDocument) - XCTAssertTrue(document.variables.isEmpty, - "variables should be empty since claim group value matches the auth rule schema") + XCTAssertTrue( + document.variables.isEmpty, + "variables should be empty since claim group value matches the auth rule schema" + ) } func testOnCreateSubscription_InAdminsGroupInDifferentClaim() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://differentapp.com/claims/groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCMultiGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://differentapp.com/claims/groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCMultiGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -215,17 +251,23 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { XCTFail("The document doesn't contain variables") return } - XCTAssertEqual(variables["owner"] as? String, - "123e4567-dead-beef-a456-426614174000", - "owner should exist since `Admins` is part of myapp.com, not differntapp.com") + XCTAssertEqual( + variables["owner"] as? String, + "123e4567-dead-beef-a456-426614174000", + "owner should exist since `Admins` is part of myapp.com, not differntapp.com" + ) } func testOnCreateSubscription_InGroupButNotInSchema() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://differentapp.com/claims/groups": ["Users"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCMultiGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://differentapp.com/claims/groups": ["Users"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCMultiGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -245,8 +287,10 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { XCTFail("The document doesn't contain variables") return } - XCTAssertEqual(variables["owner"] as? String, - "123e4567-dead-beef-a456-426614174000", - "owner should exist since `Users` is not part of differentapp.com") + XCTAssertEqual( + variables["owner"] as? String, + "123e4567-dead-beef-a456-426614174000", + "owner should exist since `Users` is not part of differentapp.com" + ) } } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerFieldAuthRuleTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerFieldAuthRuleTests.swift index 7e0856eced..7967b8e730 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerFieldAuthRuleTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerFieldAuthRuleTests.swift @@ -24,8 +24,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // Since the owner field already exists on the model, ensure that it is not added again func testModelWithOwnerField_CreateMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -46,8 +48,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // Since the owner field already exists on the model, ensure that it is not added again func testModelWithOwnerField_DeleteMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -68,8 +72,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // Since the owner field already exists on the model, ensure that it is not added again func testModelWithOwnerField_UpdateMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -90,8 +96,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // Since the owner field already exists on the model, ensure that it is not added again func testModelWithOwnerField_GetQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: AuthRuleDecorator(.query)) let document = documentBuilder.build() @@ -112,8 +120,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // Since the owner field already exists on the model, ensure that it is not added again func testModelWithOwnerField_ListQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: AuthRuleDecorator(.query)) @@ -136,8 +146,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { } func testModelWithOwnerField_SyncQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .query)) @@ -166,10 +178,14 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // The owner auth rule contains `.create` operation, requiring the subscription operation to contain the input func testModelWithOwnerField_OnCreateSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -194,10 +210,14 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // The owner auth rule contains `.update` operation, requiring the subscription operation to contain the input func testModelWithOwnerField_OnUpdateSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onUpdate, claims))) let document = documentBuilder.build() @@ -222,10 +242,14 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // The owner auth rule contains `.delete` operation, requiring the subscription operation to contain the input func testModelWithOwnerField_OnDeleteSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, claims))) let document = documentBuilder.build() @@ -249,8 +273,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { } func testModelWithMultipleAuthRules_Subscription() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithMultipleAuthRules.schema, - operationType: .subscription) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithMultipleAuthRules.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, nil))) let document = documentBuilder.build() @@ -269,11 +295,15 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { } func testModelWithMultipleAuthRulesAPIKey_Subscription() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithMultipleAuthRules.schema, - operationType: .subscription) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithMultipleAuthRules.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) - documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, nil), - authType: .apiKey)) + documentBuilder.add(decorator: AuthRuleDecorator( + .subscription(.onCreate, nil), + authType: .apiKey + )) let document = documentBuilder.build() let expectedQueryDocument = """ subscription OnCreateModelWithMultipleAuthRules { @@ -290,8 +320,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { } func testModelWithOIDCOwner_Subscription() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOIDCOwnerField.schema, - operationType: .subscription) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOIDCOwnerField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, nil))) let document = documentBuilder.build() @@ -326,9 +358,11 @@ public struct ModelWithOwnerField: Model { public let id: String public var content: String public var author: String? - public init(id: String = UUID().uuidString, - content: String, - author: String?) { + public init( + id: String = UUID().uuidString, + content: String, + author: String? + ) { self.id = id self.content = content self.author = author @@ -348,7 +382,8 @@ public struct ModelWithOwnerField: Model { model.fields( .id(), .field(modelWithOwnerField.content, is: .required, ofType: .string), - .field(modelWithOwnerField.author, is: .optional, ofType: .string)) + .field(modelWithOwnerField.author, is: .optional, ofType: .string) + ) } } @@ -366,9 +401,11 @@ public struct ModelWithOIDCOwnerField: Model { public let id: String public var content: String public var author: String? - public init(id: String = UUID().uuidString, - content: String, - author: String?) { + public init( + id: String = UUID().uuidString, + content: String, + author: String? + ) { self.id = id self.content = content self.author = author @@ -388,7 +425,8 @@ public struct ModelWithOIDCOwnerField: Model { model.fields( .id(), .field(modelWithOwnerField.content, is: .required, ofType: .string), - .field(modelWithOwnerField.author, is: .optional, ofType: .string)) + .field(modelWithOwnerField.author, is: .optional, ofType: .string) + ) } } @@ -412,9 +450,11 @@ public struct ModelWithMultipleAuthRules: Model { public let id: String public var content: String public var author: String? - public init(id: String = UUID().uuidString, - content: String, - author: String?) { + public init( + id: String = UUID().uuidString, + content: String, + author: String? + ) { self.id = id self.content = content self.author = author @@ -435,6 +475,7 @@ public struct ModelWithMultipleAuthRules: Model { model.fields( .id(), .field(modelWithMultipleAuthRules.content, is: .required, ofType: .string), - .field(modelWithMultipleAuthRules.author, is: .optional, ofType: .string)) + .field(modelWithMultipleAuthRules.author, is: .optional, ofType: .string) + ) } } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/IncludeAssociationDecoratorTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/IncludeAssociationDecoratorTests.swift index a2098a2a69..ca9c861d4d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/IncludeAssociationDecoratorTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/IncludeAssociationDecoratorTests.swift @@ -37,9 +37,11 @@ class IncludeAssociationDecoratorTests: XCTestCase { for modelType: M.Type, includes includedAssociations: IncludedAssociations = { _ in [] } ) -> String { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .query, - primaryKeysOnly: true) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .query, + primaryKeysOnly: true + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) guard let modelPath = modelType.rootPath as? ModelPath else { XCTFail("Model path for \(modelType.modelName) not found. Make sure it was defined for the model") diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLCreateMutationTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLCreateMutationTests.swift index f528dfb1c0..777427dfb7 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLCreateMutationTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLCreateMutationTests.swift @@ -33,10 +33,12 @@ class GraphQLCreateMutationTests: XCTestCase { /// - it contains an `input` of type `CreatePostInput` /// - it has a list of fields with no nested models func testCreateGraphQLMutationFromSimpleModel() { - let post = Post(title: "title", - content: "content", - createdAt: .now(), - status: .private) + let post = Post( + title: "title", + content: "content", + createdAt: .now(), + status: .private + ) var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Post.schema, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: ModelDecorator(model: post, mutationType: .create)) @@ -118,7 +120,7 @@ class GraphQLCreateMutationTests: XCTestCase { } XCTAssertEqual(input["commentPostId"] as? String, post.id) } - + /// - Given: a `Model` instance /// - When: /// - the model is of type `Comment` @@ -276,7 +278,7 @@ class GraphQLCreateMutationTests: XCTestCase { } XCTAssertEqual(input["commentPostId"] as? String, post.id) } - + /// - Given: a `Model` instance /// - When: /// - the model is of type `Comment` @@ -341,8 +343,10 @@ class GraphQLCreateMutationTests: XCTestCase { func testCreateGraphQLMutationFromModelWithReadonlyFields() { let recordCover = RecordCover(artist: "artist") let record = Record(name: "name", description: "description", cover: recordCover) - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Record.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: Record.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: ModelDecorator(model: record, mutationType: .create)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .mutation)) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLDeleteMutationTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLDeleteMutationTests.swift index 8cacb82de6..71de7ba07d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLDeleteMutationTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLDeleteMutationTests.swift @@ -122,8 +122,10 @@ class GraphQLDeleteMutationTests: XCTestCase { func testDeleteGraphQLMutationModelWithReadOnlyFields() { let recordCover = RecordCover(artist: "artist") let record = Record(name: "name", description: "description", cover: recordCover) - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Record.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: Record.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: ModelDecorator(model: record, mutationType: .create)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .mutation)) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLGetQueryTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLGetQueryTests.swift index fb753b4c60..3c1e17ae14 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLGetQueryTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLGetQueryTests.swift @@ -129,7 +129,7 @@ class GraphQLGetQueryTests: XCTestCase { } XCTAssertEqual(variables["id"] as? String, "id") } - + /// - Given: a `Model` type /// - When: /// - the model is of type `Comment` @@ -208,7 +208,7 @@ class GraphQLGetQueryTests: XCTestCase { } XCTAssertEqual(variables["id"] as? String, "id") } - + func testGetGraphQLQueryFromModelWithAssociationAndSyncEnabled() { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Comment.schema, operationType: .query, primaryKeysOnly: false) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLListQueryTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLListQueryTests.swift index fc2cc77bbe..45283364d7 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLListQueryTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLListQueryTests.swift @@ -78,8 +78,10 @@ class GraphQLListQueryTests: XCTestCase { } // Test filter for a valid JSON format - let filterJSON = try? JSONSerialization.data(withJSONObject: filter, - options: .prettyPrinted) + let filterJSON = try? JSONSerialization.data( + withJSONObject: filter, + options: .prettyPrinted + ) XCTAssertNotNil(filterJSON) let expectedFilterJSON = """ @@ -119,8 +121,10 @@ class GraphQLListQueryTests: XCTestCase { let comment4 = Comment4.keys let predicate = comment4.id == "comment4Id" && comment4.post == "post4Id" - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Comment4.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: Comment4.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: FilterDecorator(filter: predicate.graphQLFilter(for: Comment4.schema))) @@ -153,8 +157,10 @@ class GraphQLListQueryTests: XCTestCase { } // Test filter for a valid JSON format - let filterJSON = try? JSONSerialization.data(withJSONObject: filter, - options: .prettyPrinted) + let filterJSON = try? JSONSerialization.data( + withJSONObject: filter, + options: .prettyPrinted + ) XCTAssertNotNil(filterJSON) let expectedFilterJSON = """ @@ -220,7 +226,7 @@ class GraphQLListQueryTests: XCTestCase { } /** - - Given: + - Given: - A Post schema with optional field 'draft' - When: - Using list query to filter records that either don't have 'draft' field or have 'null' value @@ -271,8 +277,10 @@ class GraphQLListQueryTests: XCTestCase { } // Test filter for a valid JSON format - let filterJSON = try? JSONSerialization.data(withJSONObject: filter, - options: .prettyPrinted) + let filterJSON = try? JSONSerialization.data( + withJSONObject: filter, + options: .prettyPrinted + ) XCTAssertNotNil(filterJSON) let expectedFilterJSON = """ diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLSubscriptionTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLSubscriptionTests.swift index 5724898aaf..112e7bf07e 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLSubscriptionTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLSubscriptionTests.swift @@ -93,9 +93,11 @@ class GraphQLSubscriptionTests: XCTestCase { /// - check if the generated GraphQL document is a valid subscription /// - it has a list of fields with no nested models func testOnCreateGraphQLSubscriptionFromModelWithAssociation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Comment.schema, - operationType: .subscription, - primaryKeysOnly: true) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: Comment.schema, + operationType: .subscription, + primaryKeysOnly: true + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) let document = documentBuilder.build() let expectedQueryDocument = """ @@ -118,9 +120,11 @@ class GraphQLSubscriptionTests: XCTestCase { } func testOnCreateGraphQLSubscriptionFromModelWithAssociationWithSyncEnabled() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Comment.schema, - operationType: .subscription, - primaryKeysOnly: true) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: Comment.schema, + operationType: .subscription, + primaryKeysOnly: true + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) let document = documentBuilder.build() diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLSyncQueryTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLSyncQueryTests.swift index f8d225a8c4..cda1596c28 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLSyncQueryTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLSyncQueryTests.swift @@ -81,9 +81,11 @@ class GraphQLSyncQueryTests: XCTestCase { } func testSyncGraphQLQueryForComment() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Comment.schema, - operationType: .query, - primaryKeysOnly: true) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: Comment.schema, + operationType: .query, + primaryKeysOnly: true + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) documentBuilder.add(decorator: PaginationDecorator(limit: 100, nextToken: "token")) documentBuilder.add(decorator: ConflictResolutionDecorator(lastSync: 123, graphQLType: .query, primaryKeysOnly: true)) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLUpdateMutationTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLUpdateMutationTests.swift index 21cb53634d..521b631b09 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLUpdateMutationTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLUpdateMutationTests.swift @@ -126,8 +126,10 @@ class GraphQLUpdateMutationTests: XCTestCase { func testUpdateGraphQLMutationModelWithReadOnlyFields() { let recordCover = RecordCover(artist: "artist") let record = Record(name: "name", description: "description", cover: recordCover) - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Record.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: Record.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: ModelDecorator(model: record, mutationType: .update)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .mutation)) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestAnyModelWithSyncTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestAnyModelWithSyncTests.swift index 7af997bad4..4ce7b01057 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestAnyModelWithSyncTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestAnyModelWithSyncTests.swift @@ -63,8 +63,10 @@ class GraphQLRequestAnyModelWithSyncTests: XCTestCase { func testCreateMutationGraphQLRequest() throws { let post = Post(title: "title", content: "content", createdAt: .now()) - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: post.modelName, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: post.modelName, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: ModelDecorator(model: post, mutationType: .create)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .mutation)) @@ -106,8 +108,10 @@ class GraphQLRequestAnyModelWithSyncTests: XCTestCase { func testUpdateMutationGraphQLRequest() throws { let post = Post(title: "title", content: "content", createdAt: .now()) - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: post.modelName, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: post.modelName, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: ModelDecorator(model: post, mutationType: .update)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .mutation)) @@ -149,8 +153,10 @@ class GraphQLRequestAnyModelWithSyncTests: XCTestCase { func testDeleteMutationGraphQLRequest() throws { let post = Post(title: "title", content: "content", createdAt: .now()) - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: post.modelName, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: post.modelName, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: ModelIdDecorator(id: post.id)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .mutation)) @@ -192,8 +198,10 @@ class GraphQLRequestAnyModelWithSyncTests: XCTestCase { func testCreateSubscriptionGraphQLRequest() throws { let modelType = Post.self as Model.Type - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) let document = documentBuilder.build() @@ -215,8 +223,10 @@ class GraphQLRequestAnyModelWithSyncTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) @@ -257,10 +267,12 @@ class GraphQLRequestAnyModelWithSyncTests: XCTestCase { } """ - let request = GraphQLRequest.syncQuery(modelSchema: modelType.schema, - limit: limit, - nextToken: nextToken, - lastSync: lastSync) + let request = GraphQLRequest.syncQuery( + modelSchema: modelType.schema, + limit: limit, + nextToken: nextToken, + lastSync: lastSync + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) @@ -289,7 +301,8 @@ class GraphQLRequestAnyModelWithSyncTests: XCTestCase { where: predicate, limit: limit, nextToken: nextToken, - lastSync: lastSync) + lastSync: lastSync + ) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") @@ -319,7 +332,8 @@ class GraphQLRequestAnyModelWithSyncTests: XCTestCase { where: predicate, limit: limit, nextToken: nextToken, - lastSync: lastSync) + lastSync: lastSync + ) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestAuthIdentityClaimTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestAuthIdentityClaimTests.swift index 46bd969398..ee5078717c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestAuthIdentityClaimTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestAuthIdentityClaimTests.swift @@ -22,10 +22,14 @@ class GraphQLRequestAuthIdentityClaimTests: XCTestCase { func testOnCreateSubscriptionGraphQLRequestCustomIdentityClaim() throws { let modelType = ScenarioATest6Post.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) @@ -43,9 +47,11 @@ class GraphQLRequestAuthIdentityClaimTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) @@ -63,8 +69,10 @@ class GraphQLRequestAuthIdentityClaimTests: XCTestCase { func testOnUpdateSubscriptionGraphQLRequestCustomIdentityClaim() throws { let modelType = ScenarioATest6Post.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: modelType, operationType: .subscription) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) @@ -83,9 +91,11 @@ class GraphQLRequestAuthIdentityClaimTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onUpdate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onUpdate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) @@ -99,8 +109,10 @@ class GraphQLRequestAuthIdentityClaimTests: XCTestCase { func testOnDeleteSubscriptionGraphQLRequestCustomIdentityClaim() throws { let modelType = ScenarioATest6Post.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: modelType, operationType: .subscription) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) @@ -119,9 +131,11 @@ class GraphQLRequestAuthIdentityClaimTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onDelete, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onDelete, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestAuthRuleTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestAuthRuleTests.swift index 7c24a3182a..bcb1a0e846 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestAuthRuleTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestAuthRuleTests.swift @@ -181,10 +181,14 @@ class GraphQLRequestAuthRuleTests: XCTestCase { func testOnCreateSubscriptionGraphQLRequest() throws { let modelType = Article.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) @@ -204,9 +208,11 @@ class GraphQLRequestAuthRuleTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) @@ -224,10 +230,14 @@ class GraphQLRequestAuthRuleTests: XCTestCase { func testOnUpdateSubscriptionGraphQLRequest() throws { let modelType = Article.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onUpdate, claims))) @@ -247,9 +257,11 @@ class GraphQLRequestAuthRuleTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onUpdate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onUpdate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) @@ -263,8 +275,10 @@ class GraphQLRequestAuthRuleTests: XCTestCase { func testOnDeleteSubscriptionGraphQLRequest() throws { let modelType = Article.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, operationType: .subscription) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) @@ -285,9 +299,11 @@ class GraphQLRequestAuthRuleTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onDelete, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onDelete, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) @@ -330,10 +346,12 @@ class GraphQLRequestAuthRuleTests: XCTestCase { } """ - let request = GraphQLRequest.syncQuery(modelSchema: modelType.schema, - limit: limit, - nextToken: nextToken, - lastSync: lastSync) + let request = GraphQLRequest.syncQuery( + modelSchema: modelType.schema, + limit: limit, + nextToken: nextToken, + lastSync: lastSync + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeJSONTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeJSONTests.swift index 5b2e3f60eb..f23e5bd2fc 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeJSONTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeJSONTests.swift @@ -16,48 +16,76 @@ class GraphQLRequestEmbeddableTypeJSONTests: XCTestCase { override func setUp() { let sectionName = ModelField(name: "name", type: .string, isRequired: true) let sectionNumber = ModelField(name: "number", type: .double, isRequired: true) - let sectionSchema = ModelSchema(name: "Section", - fields: [sectionName.name: sectionName, - sectionNumber.name: sectionNumber]) + let sectionSchema = ModelSchema( + name: "Section", + fields: [ + sectionName.name: sectionName, + sectionNumber.name: sectionNumber + ] + ) let colorName = ModelField(name: "name", type: .string, isRequired: true) let colorR = ModelField(name: "red", type: .int, isRequired: true) let colorG = ModelField(name: "green", type: .int, isRequired: true) let colorB = ModelField(name: "blue", type: .int, isRequired: true) - let colorSchema = ModelSchema(name: "Color", listPluralName: "Colors", syncPluralName: "Colors", - fields: [colorName.name: colorName, - colorR.name: colorR, - colorG.name: colorG, - colorB.name: colorB]) + let colorSchema = ModelSchema( + name: "Color", + listPluralName: "Colors", + syncPluralName: "Colors", + fields: [ + colorName.name: colorName, + colorR.name: colorR, + colorG.name: colorG, + colorB.name: colorB + ] + ) let categoryName = ModelField(name: "name", type: .string, isRequired: true) - let categoryColor = ModelField(name: "color", - type: .embeddedCollection(of: DynamicEmbedded.self, schema: colorSchema), - isRequired: true) - let categorySchema = ModelSchema(name: "Category", listPluralName: "Categories", syncPluralName: "Categories", - fields: [categoryName.name: categoryName, - categoryColor.name: categoryColor]) + let categoryColor = ModelField( + name: "color", + type: .embeddedCollection(of: DynamicEmbedded.self, schema: colorSchema), + isRequired: true + ) + let categorySchema = ModelSchema( + name: "Category", + listPluralName: "Categories", + syncPluralName: "Categories", + fields: [ + categoryName.name: categoryName, + categoryColor.name: categoryColor + ] + ) let todoId = ModelFieldDefinition.id("id").modelField let todoName = ModelField(name: "name", type: .string, isRequired: true) let todoDescription = ModelField(name: "description", type: .string) - let todoCategories = ModelField(name: "categories", - type: .embeddedCollection(of: DynamicEmbedded.self, schema: categorySchema)) - let todoSection = ModelField(name: "section", - type: .embedded(type: DynamicEmbedded.self, schema: sectionSchema)) + let todoCategories = ModelField( + name: "categories", + type: .embeddedCollection(of: DynamicEmbedded.self, schema: categorySchema) + ) + let todoSection = ModelField( + name: "section", + type: .embedded(type: DynamicEmbedded.self, schema: sectionSchema) + ) let todoStickies = ModelField(name: "stickies", type: .embedded(type: String.self)) - let todoSchema = ModelSchema(name: "Todo", - listPluralName: "Todos", - syncPluralName: "Todos", - fields: [todoId.name: todoId, - todoName.name: todoName, - todoDescription.name: todoDescription, - todoCategories.name: todoCategories, - todoSection.name: todoSection, - todoStickies.name: todoStickies]) + let todoSchema = ModelSchema( + name: "Todo", + listPluralName: "Todos", + syncPluralName: "Todos", + fields: [ + todoId.name: todoId, + todoName.name: todoName, + todoDescription.name: todoDescription, + todoCategories.name: todoCategories, + todoSection.name: todoSection, + todoStickies.name: todoStickies + ] + ) - ModelRegistry.register(modelType: DynamicModel.self, - modelSchema: todoSchema) { (_, _) -> Model in + ModelRegistry.register( + modelType: DynamicModel.self, + modelSchema: todoSchema + ) { _, _ -> Model in return DynamicModel(id: "1", map: [:]) } } @@ -67,24 +95,30 @@ class GraphQLRequestEmbeddableTypeJSONTests: XCTestCase { } func testCreateTodoGraphQLRequest() { - let color1 = ["name": JSONValue.string("color1"), - "red": JSONValue.number(1), - "green": JSONValue.number(2), - "blue": JSONValue.number(3)] - let color2 = ["name": JSONValue.string("color1"), - "red": JSONValue.number(12), - "green": JSONValue.number(13), - "blue": JSONValue.number(14)] + let color1 = [ + "name": JSONValue.string("color1"), + "red": JSONValue.number(1), + "green": JSONValue.number(2), + "blue": JSONValue.number(3) + ] + let color2 = [ + "name": JSONValue.string("color1"), + "red": JSONValue.number(12), + "green": JSONValue.number(13), + "blue": JSONValue.number(14) + ] let category1 = ["name": JSONValue.string("green"), "color": JSONValue.object(color1)] let category2 = ["name": JSONValue.string("red"), "color": JSONValue.object(color2)] let section = ["name": JSONValue.string("section"), "number": JSONValue.number(1.1)] - let todo = ["name": JSONValue.string("my first todo"), - "description": JSONValue.string("todo description"), - "categories": JSONValue.array([JSONValue.object(category1), JSONValue.object(category2)]), - "section": JSONValue.object(section)] + let todo = [ + "name": JSONValue.string("my first todo"), + "description": JSONValue.string("todo description"), + "categories": JSONValue.array([JSONValue.object(category1), JSONValue.object(category2)]), + "section": JSONValue.object(section) + ] let todoModel = DynamicModel(map: todo) let documentStringValue = """ diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeTests.swift index b974ea1c79..9ee63921bf 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeTests.swift @@ -27,10 +27,12 @@ class GraphQLRequestEmbeddableTypeTests: XCTestCase { let category1 = Category(name: "green", color: color1) let category2 = Category(name: "red", color: color2) let section = Section(name: "section", number: 1.1) - let todo = Todo(name: "my first todo", - description: "todo description", - categories: [category1, category2], - section: section) + let todo = Todo( + name: "my first todo", + description: "todo description", + categories: [category1, category2], + section: section + ) let documentStringValue = """ mutation CreateTodo($input: CreateTodoInput!) { createTodo(input: $input) { @@ -76,68 +78,116 @@ class GraphQLRequestEmbeddableTypeTests: XCTestCase { class GraphQLRequestJSONNonModelTests: XCTestCase { override func setUp() { - let sectionName = ModelField(name: "name", - type: .string, - isRequired: true) - let sectionNumber = ModelField(name: "number", - type: .double, - isRequired: true) - let sectionSchema = ModelSchema(name: "Section", - fields: [sectionName.name: sectionName, - sectionNumber.name: sectionNumber]) - - let colorName = ModelField(name: "name", - type: .string, - isRequired: true) - let colorR = ModelField(name: "red", - type: .int, - isRequired: true) - let colorG = ModelField(name: "green", - type: .int, - isRequired: true) - let colorB = ModelField(name: "blue", - type: .int, - isRequired: true) - let colorSchema = ModelSchema(name: "Color", listPluralName: "Colors", syncPluralName: "Colors", - fields: [colorName.name: colorName, - colorR.name: colorR, - colorG.name: colorG, - colorB.name: colorB]) - - let categoryName = ModelField(name: "name", - type: .string, - isRequired: true) - let categoryColor = ModelField(name: "color", - type: .embeddedCollection(of: DynamicEmbedded.self, schema: colorSchema), - isRequired: true) - let categorySchema = ModelSchema(name: "Category", listPluralName: "Categories", syncPluralName: "Categories", - fields: [categoryName.name: categoryName, - categoryColor.name: categoryColor]) + let sectionName = ModelField( + name: "name", + type: .string, + isRequired: true + ) + let sectionNumber = ModelField( + name: "number", + type: .double, + isRequired: true + ) + let sectionSchema = ModelSchema( + name: "Section", + fields: [ + sectionName.name: sectionName, + sectionNumber.name: sectionNumber + ] + ) + + let colorName = ModelField( + name: "name", + type: .string, + isRequired: true + ) + let colorR = ModelField( + name: "red", + type: .int, + isRequired: true + ) + let colorG = ModelField( + name: "green", + type: .int, + isRequired: true + ) + let colorB = ModelField( + name: "blue", + type: .int, + isRequired: true + ) + let colorSchema = ModelSchema( + name: "Color", + listPluralName: "Colors", + syncPluralName: "Colors", + fields: [ + colorName.name: colorName, + colorR.name: colorR, + colorG.name: colorG, + colorB.name: colorB + ] + ) + + let categoryName = ModelField( + name: "name", + type: .string, + isRequired: true + ) + let categoryColor = ModelField( + name: "color", + type: .embeddedCollection(of: DynamicEmbedded.self, schema: colorSchema), + isRequired: true + ) + let categorySchema = ModelSchema( + name: "Category", + listPluralName: "Categories", + syncPluralName: "Categories", + fields: [ + categoryName.name: categoryName, + categoryColor.name: categoryColor + ] + ) let todoId = ModelFieldDefinition.id("id").modelField - let todoName = ModelField(name: "name", - type: .string, - isRequired: true) - let todoDescription = ModelField(name: "description", - type: .string) - let todoCategories = ModelField(name: "categories", - type: .embeddedCollection(of: DynamicEmbedded.self, schema: categorySchema)) - let todoSection = ModelField(name: "section", - type: .embedded(type: DynamicEmbedded.self, schema: sectionSchema)) - let todoStickies = ModelField(name: "stickies", - type: .embedded(type: String.self)) - let todoSchema = ModelSchema(name: "Todo", - listPluralName: "Todos", - syncPluralName: "Todos", - fields: [todoId.name: todoId, - todoName.name: todoName, - todoDescription.name: todoDescription, - todoCategories.name: todoCategories, - todoSection.name: todoSection, - todoStickies.name: todoStickies]) - - ModelRegistry.register(modelType: DynamicModel.self, - modelSchema: todoSchema) { (_, _) -> Model in + let todoName = ModelField( + name: "name", + type: .string, + isRequired: true + ) + let todoDescription = ModelField( + name: "description", + type: .string + ) + let todoCategories = ModelField( + name: "categories", + type: .embeddedCollection(of: DynamicEmbedded.self, schema: categorySchema) + ) + let todoSection = ModelField( + name: "section", + type: .embedded(type: DynamicEmbedded.self, schema: sectionSchema) + ) + let todoStickies = ModelField( + name: "stickies", + type: .embedded(type: String.self) + ) + let todoSchema = ModelSchema( + name: "Todo", + listPluralName: "Todos", + syncPluralName: "Todos", + fields: [ + todoId.name: todoId, + todoName.name: todoName, + todoDescription.name: todoDescription, + todoCategories.name: todoCategories, + todoSection.name: todoSection, + todoStickies.name: todoStickies + ] + ) + + ModelRegistry.register( + modelType: DynamicModel.self, + modelSchema: todoSchema + ) { _, _ -> Model in return DynamicModel(id: "1", map: [:]) } } @@ -147,24 +197,30 @@ class GraphQLRequestJSONNonModelTests: XCTestCase { } func testCreateTodoGraphQLRequest() { - let color1 = ["name": JSONValue.string("color1"), - "red": JSONValue.number(1), - "green": JSONValue.number(2), - "blue": JSONValue.number(3)] - let color2 = ["name": JSONValue.string("color1"), - "red": JSONValue.number(12), - "green": JSONValue.number(13), - "blue": JSONValue.number(14)] + let color1 = [ + "name": JSONValue.string("color1"), + "red": JSONValue.number(1), + "green": JSONValue.number(2), + "blue": JSONValue.number(3) + ] + let color2 = [ + "name": JSONValue.string("color1"), + "red": JSONValue.number(12), + "green": JSONValue.number(13), + "blue": JSONValue.number(14) + ] let category1 = ["name": JSONValue.string("green"), "color": JSONValue.object(color1)] let category2 = ["name": JSONValue.string("red"), "color": JSONValue.object(color2)] let section = ["name": JSONValue.string("section"), "number": JSONValue.number(1.1)] - let todo = ["name": JSONValue.string("my first todo"), - "description": JSONValue.string("todo description"), - "categories": JSONValue.array([JSONValue.object(category1), JSONValue.object(category2)]), - "section": JSONValue.object(section)] + let todo = [ + "name": JSONValue.string("my first todo"), + "description": JSONValue.string("todo description"), + "categories": JSONValue.array([JSONValue.object(category1), JSONValue.object(category2)]), + "section": JSONValue.object(section) + ] let todoModel = DynamicModel(map: todo) let documentStringValue = """ diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOptionalAssociationTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOptionalAssociationTests.swift index f5155e6adb..e5c80d604d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOptionalAssociationTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOptionalAssociationTests.swift @@ -48,7 +48,7 @@ class GraphQLRequestOptionalAssociationTests: XCTestCase { XCTAssertEqual(input["name"] as? String, user.name) } - + func testCreateUserFollowingGraphQLRequest() { let user1 = User(name: "user1") let user2 = User(name: "user2") diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOwnerAndGroupTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOwnerAndGroupTests.swift index 581e744dc3..17b1faff10 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOwnerAndGroupTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOwnerAndGroupTests.swift @@ -25,11 +25,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnCreateSubscriptionScenarioBInAdmins() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) @@ -48,9 +52,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -59,11 +65,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnUpdateSubscriptionScenarioBInAdmins() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onUpdate, claims))) @@ -82,9 +92,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onUpdate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onUpdate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -93,11 +105,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnDeleteSubscriptionScenarioBInAdmins() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, claims))) @@ -116,9 +132,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onDelete, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onDelete, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -127,11 +145,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnCreateSubscriptionScenarioBInAdminsAndAnotherGroup() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["Admins", "GroupX"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["Admins", "GroupX"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) @@ -150,9 +172,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -161,11 +185,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnCreateSubscriptionScenarioBNotInAdmins() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["GroupX"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["GroupX"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) @@ -184,9 +212,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -203,11 +233,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnUpdateSubscriptionScenarioBNotInAdmins() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["GroupX"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["GroupX"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onUpdate, claims))) @@ -226,9 +260,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onUpdate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onUpdate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -245,11 +281,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnDeleteSubscriptionScenarioBNotInAdmins() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["GroupX"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["GroupX"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, claims))) @@ -268,9 +308,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onDelete, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onDelete, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -287,12 +329,16 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnDeleteSubscriptionScenarioBNoGroupClaim() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary // Specifically, leave this out: // "cognito:groups": ["GroupX"]] - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, claims))) @@ -311,9 +357,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onDelete, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onDelete, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -330,11 +378,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnCreateSubscriptionScenarioBMGroupInAdmins() { let modelType = OGCScenarioBMGroupPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) @@ -353,9 +405,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -364,11 +418,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnCreateSubscriptionScenarioBMGroupInAdminsAndAnotherGroup() { let modelType = OGCScenarioBMGroupPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["Admins", "GroupX"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["Admins", "GroupX"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) @@ -387,9 +445,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyTests.swift index 3ed2d970fe..c4dd31205a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyTests.swift @@ -22,8 +22,10 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { func testQueryGraphQLRequest() throws { let order = CustomerOrder(orderId: "testOrderId", email: "testEmail@provider.com") - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: order.modelName, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: order.modelName, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: ModelIdDecorator(id: order.id, fields: ["orderId": "testOrderId"])) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .query)) @@ -44,10 +46,12 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { XCTAssertEqual(document.stringValue, documentStringValue) - let request = GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult.self, - decodePath: document.name) + let request = GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult.self, + decodePath: document.name + ) XCTAssertEqual(request.document, document.stringValue) XCTAssert(request.responseType == MutationSyncResult.self) @@ -61,8 +65,10 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { func testCreateMutationGraphQLRequest() throws { let order = CustomerOrder(orderId: "testOrderId", email: "testEmail@provider.com") - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: order.modelName, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: order.modelName, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: ModelDecorator(model: order, mutationType: .create)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .mutation)) @@ -112,8 +118,10 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { func testUpdateMutationGraphQLRequest() throws { let order = CustomerOrder(orderId: "testOrderId", email: "testEmail@provider.com") - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: order.modelName, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: order.modelName, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: ModelDecorator(model: order, mutationType: .create)) documentBuilder.add(decorator: ConflictResolutionDecorator(version: 1, lastSync: nil, graphQLType: .mutation)) @@ -139,9 +147,11 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { return } - let request = GraphQLRequest.updateMutation(of: order, - modelSchema: order.schema, - version: 1) + let request = GraphQLRequest.updateMutation( + of: order, + modelSchema: order.schema, + version: 1 + ) XCTAssertEqual(request.document, document.stringValue) XCTAssert(request.responseType == MutationSyncResult.self) @@ -168,8 +178,10 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { func testDeleteMutationGraphQLRequest() throws { let order = CustomerOrder(orderId: "testOrderId", email: "testEmail@provider.com") - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: order.modelName, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: order.modelName, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: ModelIdDecorator(model: order)) documentBuilder.add(decorator: ConflictResolutionDecorator(version: 1, lastSync: nil, graphQLType: .mutation)) @@ -195,9 +207,11 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { return } - let request = GraphQLRequest.deleteMutation(of: order, - modelSchema: order.schema, - version: 1) + let request = GraphQLRequest.deleteMutation( + of: order, + modelSchema: order.schema, + version: 1 + ) XCTAssertEqual(request.document, document.stringValue) XCTAssert(request.responseType == MutationSyncResult.self) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests.swift index 694dcc8600..5b709c00ea 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests.swift @@ -22,16 +22,20 @@ class GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests: XCTestCase { } func testDeleteMutationGraphQLRequestWithDateInPK() throws { - let customer = CustomerWithMultipleFieldsinPK(dob: Temporal.DateTime.now(), - date: Temporal.Date.now(), - time: Temporal.Time.now(), - phoneNumber: 1_234_567, - priority: Priority.high, - height: 6.1, - firstName: "John", - lastName: "Doe") - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: customer.modelName, - operationType: .mutation) + let customer = CustomerWithMultipleFieldsinPK( + dob: Temporal.DateTime.now(), + date: Temporal.Date.now(), + time: Temporal.Time.now(), + phoneNumber: 1_234_567, + priority: Priority.high, + height: 6.1, + firstName: "John", + lastName: "Doe" + ) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: customer.modelName, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: ModelIdDecorator(model: customer)) documentBuilder.add(decorator: ConflictResolutionDecorator(version: 1, lastSync: nil, graphQLType: .mutation)) @@ -64,9 +68,11 @@ class GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests: XCTestCase { return } - let request = GraphQLRequest.deleteMutation(of: customer, - modelSchema: customer.schema, - version: 1) + let request = GraphQLRequest.deleteMutation( + of: customer, + modelSchema: customer.schema, + version: 1 + ) XCTAssertEqual(request.document, document.stringValue) XCTAssert(request.responseType == MutationSyncResult.self) @@ -100,8 +106,10 @@ class GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests: XCTestCase { } func testOnCreateSubscriptionGraphQLRequestWithDateInPK() throws { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: CustomerWithMultipleFieldsinPK.modelName, - operationType: .subscription) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: CustomerWithMultipleFieldsinPK.modelName, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) let document = documentBuilder.build() @@ -128,8 +136,10 @@ class GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests: XCTestCase { """ XCTAssertEqual(document.stringValue, documentStringValue) - let request = GraphQLRequest.subscription(to: CustomerWithMultipleFieldsinPK.self, - subscriptionType: .onCreate) + let request = GraphQLRequest.subscription( + to: CustomerWithMultipleFieldsinPK.self, + subscriptionType: .onCreate + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) } @@ -138,8 +148,10 @@ class GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests: XCTestCase { let nextToken = "nextToken" let limit = 100 let lastSync: Int64 = 123 - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: CustomerWithMultipleFieldsinPK.modelName, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: CustomerWithMultipleFieldsinPK.modelName, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) documentBuilder.add(decorator: PaginationDecorator(limit: limit, nextToken: nextToken)) documentBuilder.add(decorator: ConflictResolutionDecorator(lastSync: lastSync, graphQLType: .query)) @@ -171,10 +183,12 @@ class GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests: XCTestCase { """ XCTAssertEqual(document.stringValue, documentStringValue) - let request = GraphQLRequest.syncQuery(modelSchema: CustomerWithMultipleFieldsinPK.schema, - limit: limit, - nextToken: nextToken, - lastSync: lastSync) + let request = GraphQLRequest.syncQuery( + modelSchema: CustomerWithMultipleFieldsinPK.schema, + limit: limit, + nextToken: nextToken, + lastSync: lastSync + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/MockAWSAuthUser.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/MockAWSAuthUser.swift index 0c09bd927b..2eb1591ad3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/MockAWSAuthUser.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/MockAWSAuthUser.swift @@ -6,6 +6,7 @@ // import Amplify + public struct MockAWSAuthUser: AuthUser { /// The username for the logged in user diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/AuthRuleExtensionTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/AuthRuleExtensionTests.swift index 7f284e404f..c73a14ea5c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/AuthRuleExtensionTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/AuthRuleExtensionTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify import AWSPluginsCore +import XCTest class AuthRuleExtensionTests: XCTestCase { func testAuthRuleProviderToAWSAuth() throws { diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelGraphQLTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelGraphQLTests.swift index 0a19109c59..e22e87f6ea 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelGraphQLTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelGraphQLTests.swift @@ -39,13 +39,15 @@ class ModelGraphQLTests: XCTestCase { func testPostModelToGraphQLInputSuccess() throws { let date: Temporal.DateTime = .now() let status = PostStatus.published - let post = Post(id: "id", - title: "title", - content: "content", - createdAt: date, - draft: true, - rating: 5.0, - status: status) + let post = Post( + id: "id", + title: "title", + content: "content", + createdAt: date, + draft: true, + rating: 5.0, + status: status + ) let graphQLInput = post.graphQLInputForMutation(Post.schema, mutationType: .update) @@ -63,10 +65,12 @@ class ModelGraphQLTests: XCTestCase { func testTodoModelToGraphQLInputSuccess() { let color = Color(name: "red", red: 255, green: 0, blue: 0) let category = Category(name: "green", color: color) - let todo = Todo(name: "name", - description: "description", - categories: [category], - stickies: ["stickie1"]) + let todo = Todo( + name: "name", + description: "description", + categories: [category], + stickies: ["stickie1"] + ) let graphQLInput = todo.graphQLInputForMutation(Todo.schema, mutationType: .create) @@ -175,22 +179,30 @@ class ModelGraphQLTests: XCTestCase { } func testModelWithAssociationAndCompositePrimaryKey() { - let owner = ModelCompositePkWithAssociation(id: "id2", - dob: Temporal.DateTime.now(), - name: "name") - let childModel = ModelCompositePkBelongsTo(id: "id1", - dob: Temporal.DateTime.now(), - name: "name", - owner: owner) + let owner = ModelCompositePkWithAssociation( + id: "id2", + dob: Temporal.DateTime.now(), + name: "name" + ) + let childModel = ModelCompositePkBelongsTo( + id: "id1", + dob: Temporal.DateTime.now(), + name: "name", + owner: owner + ) let graphQLInput = childModel.graphQLInputForMutation(childModel.schema, mutationType: .create) XCTAssertEqual(graphQLInput["id"] as? String, childModel.id) XCTAssertEqual(graphQLInput["dob"] as? String, childModel.dob.iso8601String) XCTAssertEqual(graphQLInput["name"] as? String, childModel.name) - XCTAssertEqual(graphQLInput["modelCompositePkWithAssociationOtherModelsId"] as? String, - owner.id) - XCTAssertEqual(graphQLInput["modelCompositePkWithAssociationOtherModelsDob"] as? Temporal.DateTime, - owner.dob) + XCTAssertEqual( + graphQLInput["modelCompositePkWithAssociationOtherModelsId"] as? String, + owner.id + ) + XCTAssertEqual( + graphQLInput["modelCompositePkWithAssociationOtherModelsDob"] as? Temporal.DateTime, + owner.dob + ) } func testModelWithHasManyAssociationAndCompositePrimaryKey() { @@ -206,9 +218,11 @@ class ModelGraphQLTests: XCTestCase { func testModelWithHasManyUnidirectionalAssociationAndCompositePrimaryKey() { let parent = PostWithCompositeKeyUnidirectional(title: "title") - let childModel = CommentWithCompositeKeyUnidirectional(content: "comment", - postWithCompositeKeyUnidirectionalCommentsId: parent.id, - postWithCompositeKeyUnidirectionalCommentsTitle: parent.title) + let childModel = CommentWithCompositeKeyUnidirectional( + content: "comment", + postWithCompositeKeyUnidirectionalCommentsId: parent.id, + postWithCompositeKeyUnidirectionalCommentsTitle: parent.title + ) let graphQLInput = childModel.graphQLInputForMutation(childModel.schema, mutationType: .create) XCTAssertEqual(graphQLInput["id"] as? String, childModel.id) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelSchemaGraphQLTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelSchemaGraphQLTests.swift index fd06d64025..47e7463da1 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelSchemaGraphQLTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelSchemaGraphQLTests.swift @@ -29,8 +29,10 @@ class ModelSchemaGraphQLTests: XCTestCase { } func testGraphQLNameForWishWithPluralName() { - let wish = ModelSchema(name: "Wish", - pluralName: "Wishes") + let wish = ModelSchema( + name: "Wish", + pluralName: "Wishes" + ) XCTAssertEqual(wish.graphQLName(queryType: .get), "getWish") XCTAssertEqual(wish.graphQLName(queryType: .list), "listWishes") XCTAssertEqual(wish.graphQLName(queryType: .sync), "syncWishes") @@ -45,9 +47,11 @@ class ModelSchemaGraphQLTests: XCTestCase { } func testGraphQLNameForWishWithListPluralName() { - let wish = ModelSchema(name: "Wish", - listPluralName: "Wishes", - syncPluralName: "Wishes") + let wish = ModelSchema( + name: "Wish", + listPluralName: "Wishes", + syncPluralName: "Wishes" + ) XCTAssertEqual(wish.graphQLName(queryType: .get), "getWish") XCTAssertEqual(wish.graphQLName(queryType: .list), "listWishes") XCTAssertEqual(wish.graphQLName(queryType: .sync), "syncWishes") diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/QueryPredicateGraphQLTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/QueryPredicateGraphQLTests.swift index 2a699b0613..fd87c54ec6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/QueryPredicateGraphQLTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/QueryPredicateGraphQLTests.swift @@ -264,9 +264,11 @@ class QueryPredicateGraphQLTests: XCTestCase { ] } """ - let result = try GraphQLFilterConverter.toJSON(predicate, - modelSchema: Comment4.schema, - options: [.prettyPrinted]) + let result = try GraphQLFilterConverter.toJSON( + predicate, + modelSchema: Comment4.schema, + options: [.prettyPrinted] + ) XCTAssertEqual(result, expected) } @@ -290,9 +292,11 @@ class QueryPredicateGraphQLTests: XCTestCase { ] } """ - let result = try GraphQLFilterConverter.toJSON(predicate, - modelSchema: Project2.schema, - options: [.prettyPrinted]) + let result = try GraphQLFilterConverter.toJSON( + predicate, + modelSchema: Project2.schema, + options: [.prettyPrinted] + ) XCTAssertEqual(result, expected) } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedBoolTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedBoolTests.swift index 465ccfe256..31836ac496 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedBoolTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedBoolTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon + class QueryPredicateEvaluateGeneratedBoolTests: XCTestCase { override func setUp() { ModelRegistry.register(modelType: QPredGen.self) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDateTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDateTests.swift index 5055bf2230..210696caef 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDateTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDateTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon + // swiftlint:disable type_body_length // swiftlint:disable file_length // swiftlint:disable line_length diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDateTimeTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDateTimeTests.swift index 14728e550a..832a21e5e3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDateTimeTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDateTimeTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon + // swiftlint:disable type_body_length // swiftlint:disable file_length // swiftlint:disable type_name diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDoubleIntTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDoubleIntTests.swift index 8866439b17..a5def312af 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDoubleIntTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDoubleIntTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon + // swiftlint:disable type_body_length // swiftlint:disable file_length // swiftlint:disable type_name diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDoubleTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDoubleTests.swift index 12f54572b6..85e05e7014 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDoubleTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedDoubleTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon + // swiftlint:disable type_body_length // swiftlint:disable file_length // swiftlint:disable type_name diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedEnumTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedEnumTests.swift index c160885c40..8232761fb8 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedEnumTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedEnumTests.swift @@ -18,11 +18,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { func testEnumNotEqual_False() throws { let predicate = Post.keys.status.ne(PostStatus.published) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .published) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .published + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -31,11 +33,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { func testEnumNotEqual_True() throws { let predicate = Post.keys.status.ne(PostStatus.published) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .draft) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .draft + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -44,11 +48,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { func testEnumEquals_True() throws { let predicate = Post.keys.status.eq(PostStatus.published) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .published) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .published + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -57,11 +63,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { func testEnumEquals_False() throws { let predicate = Post.keys.status.eq(PostStatus.published) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .draft) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .draft + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -71,11 +79,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { /// Draft is not greater than published, evaluates to false func testEnumToStringGreaterThan_False() throws { let predicate = Post.keys.status.gt(PostStatus.published.rawValue) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .draft) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .draft + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -85,11 +95,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { /// Published is greater than draft, evaluates to true func testEnumToStringGreaterThan_True() throws { let predicate = Post.keys.status.gt(PostStatus.draft.rawValue) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .published) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .published + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -99,11 +111,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { /// Published is not less than draft, evalutates to false func testEnumToStringLessThan_False() throws { let predicate = Post.keys.status.lt(PostStatus.draft.rawValue) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .published) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .published + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -113,11 +127,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { /// Draft is less than publshed, evaluates to true func testEnumToStringLessThan_True() throws { let predicate = Post.keys.status.lt(PostStatus.published.rawValue) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .draft) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .draft + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedIntTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedIntTests.swift index 315c648ae1..b1aae1fd10 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedIntTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedIntTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon + // swiftlint:disable type_body_length // swiftlint:disable file_length // swiftlint:disable type_name diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedStringTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedStringTests.swift index 9408557689..f785a73937 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedStringTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedStringTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon + // swiftlint:disable type_body_length // swiftlint:disable file_length // swiftlint:disable type_name diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedTimeTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedTimeTests.swift index 9ef76a5e68..d692178d7c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedTimeTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedTimeTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon + // swiftlint:disable type_body_length // swiftlint:disable file_length // swiftlint:disable line_length diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGenerator.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGenerator.swift index 0a477d0c4b..c8a74d2a40 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGenerator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGenerator.swift @@ -203,7 +203,8 @@ class QueryPredicateGenerator: XCTestCase { func performGeneration(type1: String, type2: String, operation: String) -> Int { var count = 0 guard let values1 = typeToValuesMap[type1], - let values2 = typeToValuesMap[type2] else { + let values2 = typeToValuesMap[type2] + else { print("failed to find values map!") exit(1) } @@ -241,7 +242,8 @@ class QueryPredicateGenerator: XCTestCase { // handleBetween generates a test to check if v3 (value3) is between v1 and v2 func handleBetween(type1: String, val1: String, type2: String, val2: String, val3: String, operation: String) -> Bool { guard let oper = operationMap[operation], - let fieldName = fieldForType[type1] else { + let fieldName = fieldForType[type1] + else { print("Failed to look up operation") return false } @@ -287,20 +289,32 @@ class QueryPredicateGenerator: XCTestCase { print(" let timeNow = try Temporal.Time.init(iso8601String: \"10:16:44\")") } let v1LocalRef = val1 - .replacingOccurrences(of: "Temporal.DateTime.now()", - with: "dateTimeNow") - .replacingOccurrences(of: "Temporal.Time.now()", - with: "timeNow") + .replacingOccurrences( + of: "Temporal.DateTime.now()", + with: "dateTimeNow" + ) + .replacingOccurrences( + of: "Temporal.Time.now()", + with: "timeNow" + ) let v2LocalRef = val2 - .replacingOccurrences(of: "Temporal.DateTime.now()", - with: "dateTimeNow") - .replacingOccurrences(of: "Temporal.Time.now()", - with: "timeNow") + .replacingOccurrences( + of: "Temporal.DateTime.now()", + with: "dateTimeNow" + ) + .replacingOccurrences( + of: "Temporal.Time.now()", + with: "timeNow" + ) let v3LocalRef = val3 - .replacingOccurrences(of: "Temporal.DateTime.now()", - with: "dateTimeNow") - .replacingOccurrences(of: "Temporal.Time.now()", - with: "timeNow") + .replacingOccurrences( + of: "Temporal.DateTime.now()", + with: "dateTimeNow" + ) + .replacingOccurrences( + of: "Temporal.Time.now()", + with: "timeNow" + ) print(" let predicate = QPredGen.keys.\(fieldName).\(oper)(start: \(v1LocalRef), end: \(v2LocalRef))") if val3 != "" { @@ -338,7 +352,8 @@ class QueryPredicateGenerator: XCTestCase { func handleOtherOperations(type1: String, val1: String, type2: String, val2: String, operation: String) -> Bool { guard let oper = operationMap[operation], - let fieldName = fieldForType[type1] else { + let fieldName = fieldForType[type1] + else { print("Failed to look up operation") return false } @@ -371,15 +386,23 @@ class QueryPredicateGenerator: XCTestCase { print(" let timeNow = try Temporal.Time.init(iso8601String: \"10:16:44\")") } let v1LocalRef = val1 - .replacingOccurrences(of: "Temporal.DateTime.now()", - with: "dateTimeNow") - .replacingOccurrences(of: "Temporal.Time.now()", - with: "timeNow") + .replacingOccurrences( + of: "Temporal.DateTime.now()", + with: "dateTimeNow" + ) + .replacingOccurrences( + of: "Temporal.Time.now()", + with: "timeNow" + ) let v2LocalRef = val2 - .replacingOccurrences(of: "Temporal.DateTime.now()", - with: "dateTimeNow") - .replacingOccurrences(of: "Temporal.Time.now()", - with: "timeNow") + .replacingOccurrences( + of: "Temporal.DateTime.now()", + with: "dateTimeNow" + ) + .replacingOccurrences( + of: "Temporal.Time.now()", + with: "timeNow" + ) print(" let predicate = QPredGen.keys.\(fieldName).\(oper)(\(v1LocalRef))") @@ -393,9 +416,13 @@ class QueryPredicateGenerator: XCTestCase { print(" let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance)") print("") - if attemptToResolve(type1, - val1.replacingOccurrences(of: "\"", with: ""), type2, - val2.replacingOccurrences(of: "\"", with: ""), oper) { + if attemptToResolve( + type1, + val1.replacingOccurrences(of: "\"", with: ""), + type2, + val2.replacingOccurrences(of: "\"", with: ""), + oper + ) { print(" XCTAssert(evaluation)") } else { print(" XCTAssertFalse(evaluation)") @@ -405,9 +432,13 @@ class QueryPredicateGenerator: XCTestCase { return true } - func attemptToResolve(_ type1: String, _ val1: String, - _ type2: String, _ val2: String, - _ operation: String) -> Bool { + func attemptToResolve( + _ type1: String, + _ val1: String, + _ type2: String, + _ val2: String, + _ operation: String + ) -> Bool { if val2 == "" { return false } @@ -427,9 +458,11 @@ class QueryPredicateGenerator: XCTestCase { return false } - func attemptToResolveStringBool(_ val1: String, - _ val2: String, - _ operation: String) -> Bool { + func attemptToResolveStringBool( + _ val1: String, + _ val2: String, + _ operation: String + ) -> Bool { let rhs = val1 let lhs = val2 switch operation { @@ -455,11 +488,16 @@ class QueryPredicateGenerator: XCTestCase { } } - func attemptToResolveNumeric(_ type1: String, _ sv1: String, - _ type2: String, _ sv2: String, - _ operation: String) -> Bool { + func attemptToResolveNumeric( + _ type1: String, + _ sv1: String, + _ type2: String, + _ sv2: String, + _ operation: String + ) -> Bool { guard let val1 = Double(sv1), - let val2 = Double(sv2) else { + let val2 = Double(sv2) + else { print("FAILED attemptToResolveNumeric") return false } @@ -487,9 +525,13 @@ class QueryPredicateGenerator: XCTestCase { } } - func attemptToResolveTemporal(_ type1: String, _ sv1: String, - _ type2: String, _ sv2: String, - _ operation: String) -> Bool { + func attemptToResolveTemporal( + _ type1: String, + _ sv1: String, + _ type2: String, + _ sv2: String, + _ operation: String + ) -> Bool { // Use built-in Date to determine the assert logic let val1 = temporalToTimeMap[sv1]! let val2 = temporalToTimeMap[sv2]! @@ -515,9 +557,13 @@ class QueryPredicateGenerator: XCTestCase { } } - func attemptToResolveBetweenTemporal(_ st1: String, _ sv1: String, - _ st2: String, _ sv2: String, - _ sv3: String) -> Bool { + func attemptToResolveBetweenTemporal( + _ st1: String, + _ sv1: String, + _ st2: String, + _ sv2: String, + _ sv3: String + ) -> Bool { if sv3 == "" { return false } @@ -528,16 +574,19 @@ class QueryPredicateGenerator: XCTestCase { return val1 <= val3 && val2 >= val3 } - func attemptToResolveBetweenDouble(_ sv1: String, - _ sv2: String, - _ sv3: String) -> Bool { + func attemptToResolveBetweenDouble( + _ sv1: String, + _ sv2: String, + _ sv3: String + ) -> Bool { if sv3 == "" { return false } guard let val1 = Double(sv1), let val2 = Double(sv2), - let val3 = Double(sv3) else { + let val3 = Double(sv3) + else { print("FAILED DOUBLE!") return false } @@ -545,9 +594,11 @@ class QueryPredicateGenerator: XCTestCase { } - func attemptToResolveBetweenString(_ sv1: String, - _ sv2: String, - _ sv3: String) -> Bool { + func attemptToResolveBetweenString( + _ sv1: String, + _ sv2: String, + _ sv3: String + ) -> Bool { return sv1 <= sv3 && sv2 >= sv3 } } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateTests.swift index b897e1c1f0..5a5bd5e436 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon + class QueryPredicateEvaluateTests: XCTestCase { override func setUp() { ModelRegistry.register(modelType: QPredGen.self) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/LocalWebSocketServer.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/LocalWebSocketServer.swift index 1dc0fbd948..cea249064b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/LocalWebSocketServer.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/LocalWebSocketServer.swift @@ -5,12 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation import Network class LocalWebSocketServer { - let portNumber = UInt16.random(in: 49152..<65535) + let portNumber = UInt16.random(in: 49_152 ..< 65_535) var connections = [NWConnection]() var listener: NWListener? @@ -78,7 +77,6 @@ class LocalWebSocketServer { print("Socket in waiting state with error: \(error)") @unknown default: print("Socket in unkown state -> \(state)") - break } } @@ -88,14 +86,14 @@ class LocalWebSocketServer { } func stop() { - self.listener?.cancel() + listener?.cancel() } func sendTransientFailureToConnections() { - self.connections.forEach { + for connection in connections { var metadata = NWProtocolWebSocket.Metadata(opcode: .close) metadata.closeCode = .protocolCode(NWProtocolWebSocket.CloseCode.Defined.internalServerError) - $0.send( + connection.send( content: nil, contentContext: NWConnection.ContentContext(identifier: "WebSocket", metadata: [metadata]), completion: .idempotent diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/RetryWithJitterTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/RetryWithJitterTests.swift index 9ada954056..24d07abf2d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/RetryWithJitterTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/RetryWithJitterTests.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import XCTest @testable @_spi(WebSocket) import AWSPluginsCore @@ -17,8 +16,8 @@ class RetryWithJitterTests: XCTestCase { func testNext_returnDistinctValues() async { let retryWithJitter = RetryWithJitter() var values = Set() - for _ in 0..<20 { - values.insert(await retryWithJitter.next()) + for _ in 0 ..< 20 { + await values.insert(retryWithJitter.next()) } XCTAssert(values.count > 10) } @@ -27,8 +26,8 @@ class RetryWithJitterTests: XCTestCase { let max: UInt = 100_000 let retryWithJitter = RetryWithJitter(max: max) var values = Set() - for _ in 0..<50 { - values.insert(await retryWithJitter.next()) + for _ in 0 ..< 50 { + await values.insert(retryWithJitter.next()) } XCTAssert(values.allSatisfy { $0 < max}) } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/WebSocketClientTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/WebSocketClientTests.swift index 052f79d716..97fb5a6685 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/WebSocketClientTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/WebSocketClientTests.swift @@ -5,12 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // - -import XCTest import Combine +import XCTest @testable @_spi(WebSocket) import AWSPluginsCore -fileprivate let timeout: TimeInterval = 5 +private let timeout: TimeInterval = 5 class WebSocketClientTests: XCTestCase { var localWebSocketServer: LocalWebSocketServer? @@ -196,7 +195,7 @@ class WebSocketClientTests: XCTestCase { } -fileprivate class MockNetworkMonitor: WebSocketNetworkMonitorProtocol { +private class MockNetworkMonitor: WebSocketNetworkMonitorProtocol { typealias State = AmplifyNetworkMonitor.State let subject = PassthroughSubject() var publisher: AnyPublisher<(State, State), Never> { @@ -208,7 +207,7 @@ fileprivate class MockNetworkMonitor: WebSocketNetworkMonitorProtocol { func updateState(_ nextState: AmplifyNetworkMonitor.State) async { subject.send(nextState) } - + } @@ -216,7 +215,7 @@ private extension String { var hexaData: Data { .init(hexa) } - + private var hexa: UnfoldSequence { sequence(state: startIndex) { startIndex in // bail if we've reached the end of the string @@ -227,7 +226,7 @@ private extension String { defer { startIndex = endIndex } // convert the characters to a UInt8 - return UInt8(self[startIndex.. SmithyHTTPAPI.HTTPRequest? { + func sigV4SignedRequest( + requestBuilder: SmithyHTTPAPI.HTTPRequestBuilder, + credentialIdentityResolver: some AWSCredentialIdentityResolver, + signingName: String, + signingRegion: String, + date: Date + ) throws -> SmithyHTTPAPI.HTTPRequest? { let originalRequest = requestBuilder.build() return originalRequest } diff --git a/AmplifyPlugins/Core/AmplifyCredentials/AWSAuthCredentialsProviderBehavior.swift b/AmplifyPlugins/Core/AmplifyCredentials/AWSAuthCredentialsProviderBehavior.swift index 04339f6bf0..71175d11d2 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/AWSAuthCredentialsProviderBehavior.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/AWSAuthCredentialsProviderBehavior.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AwsCommonRuntimeKit import AWSPluginsCore +import Foundation import SmithyIdentity public protocol AWSAuthCredentialsProviderBehavior: AWSAuthServiceBehavior { diff --git a/AmplifyPlugins/Core/AmplifyCredentials/AWSAuthService+CredentialsProvider.swift b/AmplifyPlugins/Core/AmplifyCredentials/AWSAuthService+CredentialsProvider.swift index a2a7e58206..43218c469d 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/AWSAuthService+CredentialsProvider.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/AWSAuthService+CredentialsProvider.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AwsCommonRuntimeKit import AWSPluginsCore +import Foundation import SmithyIdentity extension AWSAuthService: AWSAuthCredentialsProviderBehavior { diff --git a/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSServiceConfiguration.swift b/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSServiceConfiguration.swift index bb992cba7d..b1590e8f57 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSServiceConfiguration.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSServiceConfiguration.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Convenience class that is used by Amplify to include metadata such as values for a "User-Agent" during /// server interactions. diff --git a/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSSignatureV4Signer.swift b/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSSignatureV4Signer.swift index 6182e50802..02f84c6071 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSSignatureV4Signer.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSSignatureV4Signer.swift @@ -5,20 +5,22 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSSDKHTTPAuth +import Foundation import SmithyHTTPAPI -import SmithyHTTPAuthAPI import SmithyHTTPAuth +import SmithyHTTPAuthAPI import SmithyIdentity public protocol AWSSignatureV4Signer { - func sigV4SignedRequest(requestBuilder: SmithyHTTPAPI.HTTPRequestBuilder, - credentialIdentityResolver: some AWSCredentialIdentityResolver, - signingName: Swift.String, - signingRegion: Swift.String, - date: Date) async throws -> SmithyHTTPAPI.HTTPRequest? + func sigV4SignedRequest( + requestBuilder: SmithyHTTPAPI.HTTPRequestBuilder, + credentialIdentityResolver: some AWSCredentialIdentityResolver, + signingName: Swift.String, + signingRegion: Swift.String, + date: Date + ) async throws -> SmithyHTTPAPI.HTTPRequest? } public class AmplifyAWSSignatureV4Signer: AWSSignatureV4Signer { @@ -28,35 +30,41 @@ public class AmplifyAWSSignatureV4Signer: AWSSignatureV4Signer { self.signer = signer } - public func sigV4SignedRequest(requestBuilder: SmithyHTTPAPI.HTTPRequestBuilder, - credentialIdentityResolver: some AWSCredentialIdentityResolver, - signingName: Swift.String, - signingRegion: Swift.String, - date: Date) async throws -> SmithyHTTPAPI.HTTPRequest? { + public func sigV4SignedRequest( + requestBuilder: SmithyHTTPAPI.HTTPRequestBuilder, + credentialIdentityResolver: some AWSCredentialIdentityResolver, + signingName: Swift.String, + signingRegion: Swift.String, + date: Date + ) async throws -> SmithyHTTPAPI.HTTPRequest? { do { let credentialIdentity = try await credentialIdentityResolver.getIdentity() - let flags = SigningFlags(useDoubleURIEncode: true, - shouldNormalizeURIPath: true, - omitSessionToken: false) + let flags = SigningFlags( + useDoubleURIEncode: true, + shouldNormalizeURIPath: true, + omitSessionToken: false + ) let signedBodyHeader: AWSSignedBodyHeader = .none let signedBodyValue: AWSSignedBodyValue = .empty - let signingConfig = AWSSigningConfig(credentials: credentialIdentity, - signedBodyHeader: signedBodyHeader, - signedBodyValue: signedBodyValue, - flags: flags, - date: date, - service: signingName, - region: signingRegion, - signatureType: .requestHeaders, - signingAlgorithm: .sigv4) + let signingConfig = AWSSigningConfig( + credentials: credentialIdentity, + signedBodyHeader: signedBodyHeader, + signedBodyValue: signedBodyValue, + flags: flags, + date: date, + service: signingName, + region: signingRegion, + signatureType: .requestHeaders, + signingAlgorithm: .sigv4 + ) let httpRequest = await signer.sigV4SignedRequest( requestBuilder: requestBuilder, signingConfig: signingConfig ) return httpRequest - } catch let error { + } catch { throw AuthError.unknown("Unable to sign request", error) } } diff --git a/AmplifyPlugins/Core/AmplifyCredentials/AuthTokenProvider.swift b/AmplifyPlugins/Core/AmplifyCredentials/AuthTokenProvider.swift index 39f1bd43f2..db33f39e0b 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/AuthTokenProvider.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/AuthTokenProvider.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation public protocol AuthTokenProvider { func getUserPoolAccessToken() async throws -> String diff --git a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngine.swift b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngine.swift index 6aa0bf7fee..fb6c241bd8 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngine.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngine.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation import SmithyHTTPAPI @_spi(FoundationClientEngine) diff --git a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngineError.swift b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngineError.swift index 098a452431..7850a7fab0 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngineError.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngineError.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation import SmithyHTTPAPI struct FoundationClientEngineError: AmplifyError { diff --git a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/PluginClientEngine.swift b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/PluginClientEngine.swift index 964adff859..33f769d78b 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/PluginClientEngine.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/PluginClientEngine.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import ClientRuntime +import Foundation import SmithyHTTPAPI @_spi(PluginHTTPClientEngine) diff --git a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/SdkHttpRequest+updatingUserAgent.swift b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/SdkHttpRequest+updatingUserAgent.swift index 586a7a9127..37df10cea9 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/SdkHttpRequest+updatingUserAgent.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/SdkHttpRequest+updatingUserAgent.swift @@ -9,8 +9,8 @@ import Foundation import SmithyHTTPAPI @_spi(PluginHTTPClientEngine) -extension HTTPRequest { - public func updatingUserAgent(with value: String) -> HTTPRequest { +public extension HTTPRequest { + func updatingUserAgent(with value: String) -> HTTPRequest { let userAgentKey = "User-Agent" var headers = headers headers.remove(name: userAgentKey) diff --git a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSettingClientEngine.swift b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSettingClientEngine.swift index 81eb7f6213..cfd867a4c8 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSettingClientEngine.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSettingClientEngine.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import ClientRuntime +import Foundation import SmithyHTTPAPI @_spi(PluginHTTPClientEngine) @@ -22,7 +22,7 @@ public struct UserAgentSettingClientEngine: AWSPluginExtension { @_spi(PluginHTTPClientEngine) extension UserAgentSettingClientEngine: HTTPClient { - + // CI updates the `platformName` property in `AmplifyAWSServiceConfiguration`. // We can / probably should move this in the future // as it's no longer necessary there. @@ -38,8 +38,8 @@ extension UserAgentSettingClientEngine: HTTPClient { } @_spi(PluginHTTPClientEngine) -extension HTTPClient where Self == UserAgentSettingClientEngine { - public static func userAgentEngine( +public extension HTTPClient where Self == UserAgentSettingClientEngine { + static func userAgentEngine( for configuration: ClientRuntime.DefaultHttpClientConfiguration ) -> Self { let baseClientEngine = baseClientEngine(for: configuration) diff --git a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSuffixAppender.swift b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSuffixAppender.swift index 3e0b5139ff..17c7fc6b19 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSuffixAppender.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSuffixAppender.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import SmithyHTTPAPI import Smithy +import SmithyHTTPAPI @_spi(InternalAmplifyPluginExtension) public class UserAgentSuffixAppender: AWSPluginExtension { diff --git a/AmplifyPlugins/Core/AmplifyCredentials/IAMCredentialProvider.swift b/AmplifyPlugins/Core/AmplifyCredentials/IAMCredentialProvider.swift index ce6617a7be..ac6596129f 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/IAMCredentialProvider.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/IAMCredentialProvider.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AwsCommonRuntimeKit import AWSPluginsCore +import Foundation import SmithyIdentity public protocol IAMCredentialsProvider { func getCredentialsProvider() -> CredentialsProviding - + func getCredentialIdentityResolver() -> any AWSCredentialIdentityResolver } diff --git a/AmplifyPlugins/Core/AmplifyCredentials/ServiceConfiguration/AmplifyAWSServiceConfiguration+Platform.swift b/AmplifyPlugins/Core/AmplifyCredentials/ServiceConfiguration/AmplifyAWSServiceConfiguration+Platform.swift index 5b5988ae90..ce2b476c0d 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/ServiceConfiguration/AmplifyAWSServiceConfiguration+Platform.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/ServiceConfiguration/AmplifyAWSServiceConfiguration+Platform.swift @@ -7,15 +7,15 @@ import Foundation -extension AmplifyAWSServiceConfiguration { +public extension AmplifyAWSServiceConfiguration { - static var platformMapping: [Platform: String] = [:] + internal static var platformMapping: [Platform: String] = [:] - public static func addUserAgentPlatform(_ platform: Platform, version: String) { + static func addUserAgentPlatform(_ platform: Platform, version: String) { platformMapping[platform] = version } - public enum Platform: String { + enum Platform: String { case flutter = "amplify-flutter" } } diff --git a/AmplifyPlugins/Core/AmplifyCredentialsTests/Auth/AWSAuthServiceTests.swift b/AmplifyPlugins/Core/AmplifyCredentialsTests/Auth/AWSAuthServiceTests.swift index 85c209e12b..140a661b57 100644 --- a/AmplifyPlugins/Core/AmplifyCredentialsTests/Auth/AWSAuthServiceTests.swift +++ b/AmplifyPlugins/Core/AmplifyCredentialsTests/Auth/AWSAuthServiceTests.swift @@ -7,10 +7,10 @@ import XCTest +import AWSClientRuntime @testable import Amplify @testable import AWSPluginsCore @testable import InternalAmplifyCredentials -import AWSClientRuntime class AWSAuthServiceTests: XCTestCase { @@ -166,7 +166,8 @@ class AWSAuthServiceTests: XCTestCase { sessionToken: "somesession", accessKeyId: "accessKeyId", secretAccessKey: "secretAccessKey", - expiration: Date().addingTimeInterval(100)) + expiration: Date().addingTimeInterval(100) + ) let sdkCredentials = try credentials.toAWSSDKCredentials() XCTAssertNotNil(sdkCredentials) } @@ -180,7 +181,8 @@ class AWSAuthServiceTests: XCTestCase { sessionToken: "somesession", accessKeyId: "accessKeyId", secretAccessKey: "secretAccessKey", - expiration: Date().addingTimeInterval(-100)) + expiration: Date().addingTimeInterval(-100) + ) let sdkCredentials = try credentials.toAWSSDKCredentials() XCTAssertNotNil(sdkCredentials) } diff --git a/AmplifyPlugins/Core/AmplifyCredentialsTests/Utils/UserAgentSettingClientEngineTests.swift b/AmplifyPlugins/Core/AmplifyCredentialsTests/Utils/UserAgentSettingClientEngineTests.swift index b5ac23f362..60af5c3347 100644 --- a/AmplifyPlugins/Core/AmplifyCredentialsTests/Utils/UserAgentSettingClientEngineTests.swift +++ b/AmplifyPlugins/Core/AmplifyCredentialsTests/Utils/UserAgentSettingClientEngineTests.swift @@ -5,7 +5,7 @@ // SPDX-License-Identifier: Apache-2.0 // -@_spi(InternalAmplifyPluginExtension) +@_spi(InternalAmplifyPluginExtension) @_spi(PluginHTTPClientEngine) @_spi(InternalHttpEngineProxy) import InternalAmplifyCredentials diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreBaseBehavior.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreBaseBehavior.swift index a7a128f638..a9b2108e64 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreBaseBehavior.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreBaseBehavior.swift @@ -11,22 +11,26 @@ import AWSPluginsCore extension AWSDataStorePlugin: DataStoreBaseBehavior { // MARK: - Save - public func save(_ model: M, - where condition: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) { + public func save( + _ model: M, + where condition: QueryPredicate? = nil, + completion: @escaping DataStoreCallback + ) { save(model, modelSchema: model.schema, where: condition, completion: completion) } - public func save(_ model: M, - where condition: QueryPredicate? = nil) async throws -> M { + public func save( + _ model: M, + where condition: QueryPredicate? = nil + ) async throws -> M { try await save(model, modelSchema: model.schema, where: condition) } public func save( _ model: M, - modelSchema: ModelSchema, - where condition: QueryPredicate? = nil, - completion: @escaping DataStoreCallback + modelSchema: ModelSchema, + where condition: QueryPredicate? = nil, + completion: @escaping DataStoreCallback ) { log.verbose("Saving: \(model) with condition: \(String(describing: condition))") let prepareSaveResult = initStorageEngineAndTryStartSync().flatMap { storageEngineBehavior in @@ -57,9 +61,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func save(_ model: M, - modelSchema: ModelSchema, - where condition: QueryPredicate? = nil) async throws -> M { + public func save( + _ model: M, + modelSchema: ModelSchema, + where condition: QueryPredicate? = nil + ) async throws -> M { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in save(model, modelSchema: model.schema, where: condition) { result in continuation.resume(with: result) @@ -70,9 +76,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { // MARK: - Query @available(*, deprecated, renamed: "query(byIdentifier:completion:)") - public func query(_ modelType: M.Type, - byId id: String, - completion: DataStoreCallback) { + public func query( + _ modelType: M.Type, + byId id: String, + completion: DataStoreCallback + ) { let predicate: QueryPredicate = field("id") == id query(modelType, where: predicate, paginate: .firstResult) { switch $0 { @@ -89,8 +97,10 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } @available(*, deprecated, renamed: "query(byIdentifier:)") - public func query(_ modelType: M.Type, - byId id: String) async throws -> M? { + public func query( + _ modelType: M.Type, + byId id: String + ) async throws -> M? { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in query(modelType, byId: id) { result in continuation.resume(with: result) @@ -98,49 +108,69 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func query(_ modelType: M.Type, - byIdentifier identifier: String, - completion: DataStoreCallback) where M: ModelIdentifiable, + public func query( + _ modelType: M.Type, + byIdentifier identifier: String, + completion: DataStoreCallback + ) where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { - queryByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: DefaultModelIdentifier.makeDefault(id: identifier), - completion: completion) + queryByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: DefaultModelIdentifier.makeDefault(id: identifier), + completion: completion + ) } - public func query(_ modelType: M.Type, - byIdentifier identifier: String) async throws -> M? + public func query( + _ modelType: M.Type, + byIdentifier identifier: String + ) async throws -> M? where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { - try await queryByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: DefaultModelIdentifier.makeDefault(id: identifier)) + try await queryByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: DefaultModelIdentifier.makeDefault(id: identifier) + ) } - public func query(_ modelType: M.Type, - byIdentifier identifier: ModelIdentifier, - completion: DataStoreCallback) where M: ModelIdentifiable { - queryByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: identifier, - completion: completion) + public func query( + _ modelType: M.Type, + byIdentifier identifier: ModelIdentifier, + completion: DataStoreCallback + ) where M: ModelIdentifiable { + queryByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: identifier, + completion: completion + ) } - public func query(_ modelType: M.Type, - byIdentifier identifier: ModelIdentifier) async throws -> M? + public func query( + _ modelType: M.Type, + byIdentifier identifier: ModelIdentifier + ) async throws -> M? where M: ModelIdentifiable { - try await queryByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: identifier) - } - - private func queryByIdentifier(_ modelType: M.Type, - modelSchema: ModelSchema, - identifier: ModelIdentifierProtocol, - completion: DataStoreCallback) { - query(modelType, - modelSchema: modelSchema, - where: identifier.predicate, - paginate: .firstResult) { + try await queryByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: identifier + ) + } + + private func queryByIdentifier( + _ modelType: M.Type, + modelSchema: ModelSchema, + identifier: ModelIdentifierProtocol, + completion: DataStoreCallback + ) { + query( + modelType, + modelSchema: modelSchema, + where: identifier.predicate, + paginate: .firstResult + ) { switch $0 { case .success(let models): do { @@ -155,9 +185,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - private func queryByIdentifier(_ modelType: M.Type, - modelSchema: ModelSchema, - identifier: ModelIdentifierProtocol) async throws -> M? { + private func queryByIdentifier( + _ modelType: M.Type, + modelSchema: ModelSchema, + identifier: ModelIdentifierProtocol + ) async throws -> M? { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in queryByIdentifier(modelType, modelSchema: modelSchema, identifier: identifier) { result in continuation.resume(with: result) @@ -165,28 +197,36 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func query(_ modelType: M.Type, - where predicate: QueryPredicate? = nil, - sort sortInput: QuerySortInput? = nil, - paginate paginationInput: QueryPaginationInput? = nil, - completion: DataStoreCallback<[M]>) { - query(modelType, - modelSchema: modelType.schema, - where: predicate, - sort: sortInput?.asSortDescriptors(), - paginate: paginationInput, - completion: completion) + public func query( + _ modelType: M.Type, + where predicate: QueryPredicate? = nil, + sort sortInput: QuerySortInput? = nil, + paginate paginationInput: QueryPaginationInput? = nil, + completion: DataStoreCallback<[M]> + ) { + query( + modelType, + modelSchema: modelType.schema, + where: predicate, + sort: sortInput?.asSortDescriptors(), + paginate: paginationInput, + completion: completion + ) } - public func query(_ modelType: M.Type, - where predicate: QueryPredicate? = nil, - sort sortInput: QuerySortInput? = nil, - paginate paginationInput: QueryPaginationInput? = nil) async throws -> [M] { - try await query(modelType, - modelSchema: modelType.schema, - where: predicate, - sort: sortInput?.asSortDescriptors(), - paginate: paginationInput) + public func query( + _ modelType: M.Type, + where predicate: QueryPredicate? = nil, + sort sortInput: QuerySortInput? = nil, + paginate paginationInput: QueryPaginationInput? = nil + ) async throws -> [M] { + try await query( + modelType, + modelSchema: modelType.schema, + where: predicate, + sort: sortInput?.asSortDescriptors(), + paginate: paginationInput + ) } public func query( @@ -213,11 +253,13 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func query(_ modelType: M.Type, - modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil, - sort sortInput: [QuerySortDescriptor]? = nil, - paginate paginationInput: QueryPaginationInput? = nil) async throws -> [M] { + public func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil, + sort sortInput: [QuerySortDescriptor]? = nil, + paginate paginationInput: QueryPaginationInput? = nil + ) async throws -> [M] { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<[M], Error>) in query(modelType, modelSchema: modelSchema, where: predicate, sort: sortInput, paginate: paginationInput) { result in continuation.resume(with: result) @@ -227,18 +269,22 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { // MARK: - Delete @available(*, deprecated, renamed: "delete(withIdentifier:)") - public func delete(_ modelType: M.Type, - withId id: String, - where predicate: QueryPredicate?) async throws { + public func delete( + _ modelType: M.Type, + withId id: String, + where predicate: QueryPredicate? + ) async throws { try await delete(modelType, modelSchema: modelType.schema, withId: id, where: predicate) } @available(*, deprecated, renamed: "delete(withIdentifier:)") - public func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withId id: String, - where predicate: QueryPredicate? = nil) async throws { + public func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withId id: String, + where predicate: QueryPredicate? = nil + ) async throws { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in switch initStorageEngineAndTryStartSync() { case .success(let storageEngineBehavior): @@ -253,53 +299,71 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func delete(_ modelType: M.Type, - withIdentifier identifier: String, - where predicate: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) where M: ModelIdentifiable, + public func delete( + _ modelType: M.Type, + withIdentifier identifier: String, + where predicate: QueryPredicate? = nil, + completion: @escaping DataStoreCallback + ) where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { - deleteByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: DefaultModelIdentifier.makeDefault(id: identifier), - where: predicate, - completion: completion) + deleteByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: DefaultModelIdentifier.makeDefault(id: identifier), + where: predicate, + completion: completion + ) } - public func delete(_ modelType: M.Type, - withIdentifier identifier: String, - where predicate: QueryPredicate? = nil) async throws + public func delete( + _ modelType: M.Type, + withIdentifier identifier: String, + where predicate: QueryPredicate? = nil + ) async throws where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { - try await deleteByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: DefaultModelIdentifier.makeDefault(id: identifier), - where: predicate) - } - - public func delete(_ modelType: M.Type, - withIdentifier identifier: ModelIdentifier, - where predicate: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) where M: ModelIdentifiable { - deleteByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: identifier, - where: predicate, - completion: completion) - } - - public func delete(_ modelType: M.Type, - withIdentifier identifier: ModelIdentifier, - where predicate: QueryPredicate? = nil) async throws where M: ModelIdentifiable { - try await deleteByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: identifier, - where: predicate) - } - - private func deleteByIdentifier(_ modelType: M.Type, - modelSchema: ModelSchema, - identifier: ModelIdentifierProtocol, - where predicate: QueryPredicate?, - completion: @escaping DataStoreCallback) where M: ModelIdentifiable { + try await deleteByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: DefaultModelIdentifier.makeDefault(id: identifier), + where: predicate + ) + } + + public func delete( + _ modelType: M.Type, + withIdentifier identifier: ModelIdentifier, + where predicate: QueryPredicate? = nil, + completion: @escaping DataStoreCallback + ) where M: ModelIdentifiable { + deleteByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: identifier, + where: predicate, + completion: completion + ) + } + + public func delete( + _ modelType: M.Type, + withIdentifier identifier: ModelIdentifier, + where predicate: QueryPredicate? = nil + ) async throws where M: ModelIdentifiable { + try await deleteByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: identifier, + where: predicate + ) + } + + private func deleteByIdentifier( + _ modelType: (some Model & ModelIdentifiable).Type, + modelSchema: ModelSchema, + identifier: ModelIdentifierProtocol, + where predicate: QueryPredicate?, + completion: @escaping DataStoreCallback + ) { switch initStorageEngineAndTryStartSync() { case .success(let storageEngineBehavior): storageEngineBehavior.delete( @@ -320,10 +384,12 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } - private func deleteByIdentifier(_ modelType: M.Type, - modelSchema: ModelSchema, - identifier: ModelIdentifierProtocol, - where predicate: QueryPredicate?) async throws where M: ModelIdentifiable { + private func deleteByIdentifier( + _ modelType: (some Model & ModelIdentifiable).Type, + modelSchema: ModelSchema, + identifier: ModelIdentifierProtocol, + where predicate: QueryPredicate? + ) async throws { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in deleteByIdentifier(modelType, modelSchema: modelSchema, identifier: identifier, where: predicate) { result in continuation.resume(with: result) @@ -331,21 +397,27 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func delete(_ model: M, - where predicate: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) { + public func delete( + _ model: some Model, + where predicate: QueryPredicate? = nil, + completion: @escaping DataStoreCallback + ) { delete(model, modelSchema: model.schema, where: predicate, completion: completion) } - public func delete(_ model: M, - where predicate: QueryPredicate? = nil) async throws { + public func delete( + _ model: some Model, + where predicate: QueryPredicate? = nil + ) async throws { try await delete(model, modelSchema: model.schema, where: predicate) } - public func delete(_ model: M, - modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) { + public func delete( + _ model: some Model, + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil, + completion: @escaping DataStoreCallback + ) { switch initStorageEngineAndTryStartSync() { case .success(let storageEngineBehavior): storageEngineBehavior.delete( @@ -362,9 +434,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } - public func delete(_ model: M, - modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil) async throws { + public func delete( + _ model: some Model, + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil + ) async throws { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in delete(model, modelSchema: modelSchema, where: predicate) { result in continuation.resume(with: result) @@ -372,21 +446,27 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func delete(_ modelType: M.Type, - where predicate: QueryPredicate, - completion: @escaping DataStoreCallback) { + public func delete( + _ modelType: (some Model).Type, + where predicate: QueryPredicate, + completion: @escaping DataStoreCallback + ) { delete(modelType, modelSchema: modelType.schema, where: predicate, completion: completion) } - public func delete(_ modelType: M.Type, - where predicate: QueryPredicate) async throws { + public func delete( + _ modelType: (some Model).Type, + where predicate: QueryPredicate + ) async throws { try await delete(modelType, modelSchema: modelType.schema, where: predicate) } - public func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - where predicate: QueryPredicate, - completion: @escaping DataStoreCallback) { + public func delete( + _ modelType: (some Model).Type, + modelSchema: ModelSchema, + where predicate: QueryPredicate, + completion: @escaping DataStoreCallback + ) { switch initStorageEngineAndTryStartSync() { case .success(let storageEngineBehavior): storageEngineBehavior.delete( @@ -409,9 +489,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - where predicate: QueryPredicate) async throws { + public func delete( + _ modelType: (some Model).Type, + modelSchema: ModelSchema, + where predicate: QueryPredicate + ) async throws { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in delete(modelType, modelSchema: modelSchema, where: predicate) { result in continuation.resume(with: result) @@ -421,7 +503,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { public func start(completion: @escaping DataStoreCallback) { let result = initStorageEngineAndStartSync().map { _ in () } - self.queue.async { + queue.async { completion(result) } } @@ -437,7 +519,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { public func stop(completion: @escaping DataStoreCallback) { storageEngineInitQueue.sync { self.dataStoreStateSubject.send(.stop) - dispatchedModelSyncedEvents.forEach { _, dispatchedModelSynced in + for (_, dispatchedModelSynced) in dispatchedModelSyncedEvents { dispatchedModelSynced.set(false) } if storageEngine == nil { @@ -471,7 +553,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { storageEngineInitQueue.sync { self.dataStoreStateSubject.send(.clear) - dispatchedModelSyncedEvents.forEach { _, dispatchedModelSynced in + for (_, dispatchedModelSynced) in dispatchedModelSyncedEvents { dispatchedModelSynced.set(false) } if storageEngine == nil { @@ -499,9 +581,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { // MARK: Private - private func onDeleteCompletion(result: DataStoreResult, - modelSchema: ModelSchema, - completion: @escaping DataStoreCallback) { + private func onDeleteCompletion( + result: DataStoreResult<(some Model)?>, + modelSchema: ModelSchema, + completion: @escaping DataStoreCallback + ) { switch result { case .success(let modelOptional): if let model = modelOptional { @@ -513,8 +597,8 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - private func mutationTypeOfModel( - _ model: M, + private func mutationTypeOfModel( + _ model: some Model, modelSchema: ModelSchema, storageEngine: StorageEngineBehavior ) -> Result { @@ -523,9 +607,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { guard let engine = storageEngine as? StorageEngine else { throw DataStoreError.configuration("Unable to get storage adapter", "") } - modelExists = try engine.storageAdapter.exists(modelSchema, - withIdentifier: model.identifier(schema: modelSchema), - predicate: nil) + modelExists = try engine.storageAdapter.exists( + modelSchema, + withIdentifier: model.identifier(schema: modelSchema), + predicate: nil + ) } catch { if let dataStoreError = error as? DataStoreError { return .failure(dataStoreError) @@ -538,10 +624,12 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { return .success(modelExists ? MutationEvent.MutationType.update : .create) } - private func publishMutationEvent(from model: M, - modelSchema: ModelSchema, - mutationType: MutationEvent.MutationType) { - guard let storageEngine = storageEngine else { + private func publishMutationEvent( + from model: some Model, + modelSchema: ModelSchema, + mutationType: MutationEvent.MutationType + ) { + guard let storageEngine else { log.info( """ StorageEngine is nil; @@ -552,20 +640,26 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } let metadata = MutationSyncMetadata.keys - let metadataId = MutationSyncMetadata.identifier(modelName: modelSchema.name, - modelId: model.identifier(schema: modelSchema).stringValue) - storageEngine.query(MutationSyncMetadata.self, - predicate: metadata.id == metadataId, - sort: nil, - paginationInput: .firstResult, - eagerLoad: true) { + let metadataId = MutationSyncMetadata.identifier( + modelName: modelSchema.name, + modelId: model.identifier(schema: modelSchema).stringValue + ) + storageEngine.query( + MutationSyncMetadata.self, + predicate: metadata.id == metadataId, + sort: nil, + paginationInput: .firstResult, + eagerLoad: true + ) { do { let result = try $0.get() let syncMetadata = try result.unique() - let mutationEvent = try MutationEvent(model: model, - modelSchema: modelSchema, - mutationType: mutationType, - version: syncMetadata?.version) + let mutationEvent = try MutationEvent( + model: model, + modelSchema: modelSchema, + mutationType: mutationType, + version: syncMetadata?.version + ) self.dataStorePublisher?.send(input: mutationEvent) } catch { self.log.error(error: error) @@ -576,26 +670,34 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } /// Overrides needed by platforms using a serialized version of models (i.e. Flutter) -extension AWSDataStorePlugin { - public func query(_ modelType: M.Type, - modelSchema: ModelSchema, - byIdentifier identifier: ModelIdentifier, - completion: DataStoreCallback) where M: ModelIdentifiable { - queryByIdentifier(modelType, - modelSchema: modelSchema, - identifier: identifier, - completion: completion) - } - - public func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifier, - where predicate: QueryPredicate?, - completion: @escaping DataStoreCallback) where M: ModelIdentifiable { - deleteByIdentifier(modelType, - modelSchema: modelSchema, - identifier: identifier, - where: predicate, - completion: completion) +public extension AWSDataStorePlugin { + func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + byIdentifier identifier: ModelIdentifier, + completion: DataStoreCallback + ) where M: ModelIdentifiable { + queryByIdentifier( + modelType, + modelSchema: modelSchema, + identifier: identifier, + completion: completion + ) + } + + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifier, + where predicate: QueryPredicate?, + completion: @escaping DataStoreCallback + ) where M: ModelIdentifiable { + deleteByIdentifier( + modelType, + modelSchema: modelSchema, + identifier: identifier, + where: predicate, + completion: completion + ) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreSubscribeBehavior.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreSubscribeBehavior.swift index ca41efd230..f66d70c35b 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreSubscribeBehavior.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreSubscribeBehavior.swift @@ -21,34 +21,38 @@ extension AWSDataStorePlugin: DataStoreSubscribeBehavior { return publisher.filter { $0.modelName == modelName }.eraseToAnyPublisher() } - public func observe(_ modelType: M.Type) -> AmplifyAsyncThrowingSequence { + public func observe(_ modelType: (some Model).Type) -> AmplifyAsyncThrowingSequence { let runner = ObserveTaskRunner(publisher: publisher(for: modelType.modelName)) return runner.sequence } - public func observeQuery(for modelType: M.Type, - where predicate: QueryPredicate?, - sort sortInput: QuerySortInput?) -> AmplifyAsyncThrowingSequence> { + public func observeQuery( + for modelType: M.Type, + where predicate: QueryPredicate?, + sort sortInput: QuerySortInput? + ) -> AmplifyAsyncThrowingSequence> { switch initStorageEngineAndTryStartSync() { case .success(let storageEngineBehavior): let modelSchema = modelType.schema - guard let dataStorePublisher = dataStorePublisher else { + guard let dataStorePublisher else { return Fatal.preconditionFailure("`dataStorePublisher` is expected to exist for deployment targets >=iOS13.0") } guard let dispatchedModelSyncedEvent = dispatchedModelSyncedEvents[modelSchema.name] else { return Fatal.preconditionFailure("`dispatchedModelSyncedEvent` is expected to exist for \(modelSchema.name)") } let request = ObserveQueryRequest(options: []) - let taskRunner = ObserveQueryTaskRunner(request: request, - modelType: modelType, - modelSchema: modelType.schema, - predicate: predicate, - sortInput: sortInput?.asSortDescriptors(), - storageEngine: storageEngineBehavior, - dataStorePublisher: dataStorePublisher, - dataStoreConfiguration: configuration.pluginConfiguration, - dispatchedModelSyncedEvent: dispatchedModelSyncedEvent, - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + let taskRunner = ObserveQueryTaskRunner( + request: request, + modelType: modelType, + modelSchema: modelType.schema, + predicate: predicate, + sortInput: sortInput?.asSortDescriptors(), + storageEngine: storageEngineBehavior, + dataStorePublisher: dataStorePublisher, + dataStoreConfiguration: configuration.pluginConfiguration, + dispatchedModelSyncedEvent: dispatchedModelSyncedEvent, + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) return taskRunner.sequence case .failure(let error): return Fatal.preconditionFailure("Unable to get storage adapter \(error.localizedDescription)") diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin.swift index cdcbbc2bfb..272a6ac607 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin.swift @@ -6,8 +6,8 @@ // import Amplify -import Combine import AWSPluginsCore +import Combine import Foundation enum DataStoreState { @@ -16,7 +16,7 @@ enum DataStoreState { case clear } -final public class AWSDataStorePlugin: DataStoreCategoryPlugin { +public final class AWSDataStorePlugin: DataStoreCategoryPlugin { public var key: PluginKey = "awsDataStorePlugin" @@ -60,14 +60,17 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { /// - Parameters: /// - modelRegistration: Register DataStore models. /// - dataStoreConfiguration: Configuration object for DataStore - public init(modelRegistration: AmplifyModelRegistration, - configuration dataStoreConfiguration: DataStoreConfiguration) { + public init( + modelRegistration: AmplifyModelRegistration, + configuration dataStoreConfiguration: DataStoreConfiguration + ) { self.modelRegistration = modelRegistration self.configuration = InternalDatastoreConfiguration( isSyncEnabled: false, validAPIPluginKey: "awsAPIPlugin", validAuthPluginKey: "awsCognitoAuthPlugin", - pluginConfiguration: dataStoreConfiguration) + pluginConfiguration: dataStoreConfiguration + ) self.storageEngineBehaviorFactory = StorageEngine.init( @@ -86,14 +89,17 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { /// - Parameters: /// - modelRegistration: Register DataStore models. /// - dataStoreConfiguration: Configuration object for DataStore - public init(modelRegistration: AmplifyModelRegistration, - configuration dataStoreConfiguration: DataStoreConfiguration = .default) { + public init( + modelRegistration: AmplifyModelRegistration, + configuration dataStoreConfiguration: DataStoreConfiguration = .default + ) { self.modelRegistration = modelRegistration self.configuration = InternalDatastoreConfiguration( isSyncEnabled: false, validAPIPluginKey: "awsAPIPlugin", validAuthPluginKey: "awsCognitoAuthPlugin", - pluginConfiguration: dataStoreConfiguration) + pluginConfiguration: dataStoreConfiguration + ) self.storageEngineBehaviorFactory = StorageEngine.init( @@ -110,19 +116,22 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { #endif /// Internal initializer for testing - init(modelRegistration: AmplifyModelRegistration, - configuration dataStoreConfiguration: DataStoreConfiguration = .testDefault(), - storageEngineBehaviorFactory: StorageEngineBehaviorFactory? = nil, - dataStorePublisher: ModelSubcriptionBehavior, - operationQueue: OperationQueue = OperationQueue(), - validAPIPluginKey: String, - validAuthPluginKey: String) { + init( + modelRegistration: AmplifyModelRegistration, + configuration dataStoreConfiguration: DataStoreConfiguration = .testDefault(), + storageEngineBehaviorFactory: StorageEngineBehaviorFactory? = nil, + dataStorePublisher: ModelSubcriptionBehavior, + operationQueue: OperationQueue = OperationQueue(), + validAPIPluginKey: String, + validAuthPluginKey: String + ) { self.modelRegistration = modelRegistration self.configuration = InternalDatastoreConfiguration( isSyncEnabled: false, validAPIPluginKey: validAPIPluginKey, validAuthPluginKey: validAuthPluginKey, - pluginConfiguration: dataStoreConfiguration) + pluginConfiguration: dataStoreConfiguration + ) self.storageEngineBehaviorFactory = storageEngineBehaviorFactory ?? StorageEngine.init( @@ -161,8 +170,8 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { } do { - if self.dataStorePublisher == nil { - self.dataStorePublisher = DataStorePublisher() + if dataStorePublisher == nil { + dataStorePublisher = DataStorePublisher() } try resolveStorageEngine(dataStoreConfiguration: configuration.pluginConfiguration) try storageEngine.setUp(modelSchemas: ModelRegistry.modelSchemas) @@ -251,7 +260,7 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { } func onReceiveValue(receiveValue: StorageEngineEvent) { - guard let dataStorePublisher = self.dataStorePublisher else { + guard let dataStorePublisher else { log.error("Data store publisher not initalized") return } @@ -264,8 +273,10 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { case .modelSyncedEvent(let modelSyncedEvent): log.verbose("Emitting DataStore event: modelSyncedEvent \(modelSyncedEvent)") dispatchedModelSyncedEvents[modelSyncedEvent.modelName]?.set(true) - let modelSyncedEventPayload = HubPayload(eventName: HubPayload.EventName.DataStore.modelSynced, - data: modelSyncedEvent) + let modelSyncedEventPayload = HubPayload( + eventName: HubPayload.EventName.DataStore.modelSynced, + data: modelSyncedEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: modelSyncedEventPayload) case .syncQueriesReadyEvent: log.verbose("[Lifecycle event 4]: syncQueriesReady") @@ -284,7 +295,7 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { if let resettable = storageEngine as? Resettable { log.verbose("Resetting storageEngine") await resettable.reset() - self.log.verbose("Resetting storageEngine: finished") + log.verbose("Resetting storageEngine: finished") } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift index 564918daa2..fcfe84030c 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation -extension DataStoreConfiguration { +public extension DataStoreConfiguration { - public static let defaultSyncInterval: TimeInterval = .hours(24) - public static let defaultSyncMaxRecords: UInt = 10_000 - public static let defaultSyncPageSize: UInt = 1_000 + static let defaultSyncInterval: TimeInterval = .hours(24) + static let defaultSyncMaxRecords: UInt = 10_000 + static let defaultSyncPageSize: UInt = 1_000 #if os(watchOS) /// Creates a custom configuration. The only required property is `conflictHandler`. @@ -27,7 +27,7 @@ extension DataStoreConfiguration { /// - authModeStrategy: authorization strategy (.default | multiauth) /// - disableSubscriptions: called before establishing subscriptions. Return true to disable subscriptions. /// - Returns: an instance of `DataStoreConfiguration` with the passed parameters. - public static func custom( + static func custom( errorHandler: @escaping DataStoreErrorHandler = { error in Amplify.Logging.error(error: error) }, @@ -41,14 +41,16 @@ extension DataStoreConfiguration { authModeStrategy: AuthModeStrategyType = .default, disableSubscriptions: @escaping () -> Bool ) -> DataStoreConfiguration { - return DataStoreConfiguration(errorHandler: errorHandler, - conflictHandler: conflictHandler, - syncInterval: syncInterval, - syncMaxRecords: syncMaxRecords, - syncPageSize: syncPageSize, - syncExpressions: syncExpressions, - authModeStrategy: authModeStrategy, - disableSubscriptions: disableSubscriptions) + return DataStoreConfiguration( + errorHandler: errorHandler, + conflictHandler: conflictHandler, + syncInterval: syncInterval, + syncMaxRecords: syncMaxRecords, + syncPageSize: syncPageSize, + syncExpressions: syncExpressions, + authModeStrategy: authModeStrategy, + disableSubscriptions: disableSubscriptions + ) } #else /// Creates a custom configuration. The only required property is `conflictHandler`. @@ -61,7 +63,7 @@ extension DataStoreConfiguration { /// - syncPageSize: the page size of each sync execution /// - authModeStrategy: authorization strategy (.default | multiauth) /// - Returns: an instance of `DataStoreConfiguration` with the passed parameters. - public static func custom( + static func custom( errorHandler: @escaping DataStoreErrorHandler = { error in Amplify.Logging.error(error: error) }, @@ -74,13 +76,15 @@ extension DataStoreConfiguration { syncExpressions: [DataStoreSyncExpression] = [], authModeStrategy: AuthModeStrategyType = .default ) -> DataStoreConfiguration { - return DataStoreConfiguration(errorHandler: errorHandler, - conflictHandler: conflictHandler, - syncInterval: syncInterval, - syncMaxRecords: syncMaxRecords, - syncPageSize: syncPageSize, - syncExpressions: syncExpressions, - authModeStrategy: authModeStrategy) + return DataStoreConfiguration( + errorHandler: errorHandler, + conflictHandler: conflictHandler, + syncInterval: syncInterval, + syncMaxRecords: syncMaxRecords, + syncPageSize: syncPageSize, + syncExpressions: syncExpressions, + authModeStrategy: authModeStrategy + ) } #endif @@ -89,12 +93,12 @@ extension DataStoreConfiguration { /// which work on the watchOS simulator but not on the device. Running DataStore on watchOS with subscriptions /// enabled is only possible during special circumstances such as actively streaming audio. /// See https://github.com/aws-amplify/amplify-swift/pull/3368 for more details. - public static var subscriptionsDisabled: DataStoreConfiguration { + static var subscriptionsDisabled: DataStoreConfiguration { .custom(disableSubscriptions: { true }) } #else /// The default configuration. - public static var `default`: DataStoreConfiguration { + static var `default`: DataStoreConfiguration { .custom() } #endif diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration.swift index a1c3ec8788..b25e1b008b 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSPluginsCore +import Foundation /// Error Handler function typealias public typealias DataStoreErrorHandler = (AmplifyError) -> Void @@ -73,14 +73,16 @@ public struct DataStoreConfiguration { public let disableSubscriptions: () -> Bool #if os(watchOS) - init(errorHandler: @escaping DataStoreErrorHandler, - conflictHandler: @escaping DataStoreConflictHandler, - syncInterval: TimeInterval, - syncMaxRecords: UInt, - syncPageSize: UInt, - syncExpressions: [DataStoreSyncExpression], - authModeStrategy: AuthModeStrategyType = .default, - disableSubscriptions: @escaping () -> Bool) { + init( + errorHandler: @escaping DataStoreErrorHandler, + conflictHandler: @escaping DataStoreConflictHandler, + syncInterval: TimeInterval, + syncMaxRecords: UInt, + syncPageSize: UInt, + syncExpressions: [DataStoreSyncExpression], + authModeStrategy: AuthModeStrategyType = .default, + disableSubscriptions: @escaping () -> Bool + ) { self.errorHandler = errorHandler self.conflictHandler = conflictHandler self.syncInterval = syncInterval @@ -91,13 +93,15 @@ public struct DataStoreConfiguration { self.disableSubscriptions = disableSubscriptions } #else - init(errorHandler: @escaping DataStoreErrorHandler, - conflictHandler: @escaping DataStoreConflictHandler, - syncInterval: TimeInterval, - syncMaxRecords: UInt, - syncPageSize: UInt, - syncExpressions: [DataStoreSyncExpression], - authModeStrategy: AuthModeStrategyType = .default) { + init( + errorHandler: @escaping DataStoreErrorHandler, + conflictHandler: @escaping DataStoreConflictHandler, + syncInterval: TimeInterval, + syncMaxRecords: UInt, + syncPageSize: UInt, + syncExpressions: [DataStoreSyncExpression], + authModeStrategy: AuthModeStrategyType = .default + ) { self.errorHandler = errorHandler self.conflictHandler = conflictHandler self.syncInterval = syncInterval diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/InternalDatastoreConfiguration.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/InternalDatastoreConfiguration.swift index f70585d5a1..34e3968b45 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/InternalDatastoreConfiguration.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/InternalDatastoreConfiguration.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct InternalDatastoreConfiguration { @@ -32,7 +32,7 @@ struct InternalDatastoreConfiguration { let pluginConfiguration: DataStoreConfiguration mutating func updateIsSyncEnabled(_ isEnabled: Bool) { - self.isSyncEnabled = isEnabled + isSyncEnabled = isEnabled } mutating func updateIsEagerLoad(modelSchema: ModelSchema) { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListDecoder.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListDecoder.swift index 9241da72e2..4bc09c8fee 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListDecoder.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListDecoder.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import Combine +import Foundation public struct DataStoreListDecoder: ModelListDecoder { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListProvider.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListProvider.swift index 59aee21603..699d5dd033 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListProvider.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListProvider.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import Combine +import Foundation /// `DataStoreList` is a DataStore-aware custom `Collection` that is capable of loading /// records from the `DataStore` on-demand. This is especially useful when dealing with @@ -21,8 +21,10 @@ public class DataStoreListProvider: ModelListProvider { var loadedState: ModelListProviderState init(metadata: DataStoreListDecoder.Metadata) { - self.loadedState = .notLoaded(associatedIdentifiers: metadata.dataStoreAssociatedIdentifiers, - associatedFields: metadata.dataStoreAssociatedFields) + self.loadedState = .notLoaded( + associatedIdentifiers: metadata.dataStoreAssociatedIdentifiers, + associatedFields: metadata.dataStoreAssociatedFields + ) } init(_ elements: [Element]) { @@ -47,28 +49,32 @@ public class DataStoreListProvider: ModelListProvider { if associatedIdentifiers.count == 1, let associatedId = associatedIdentifiers.first, let associatedField = associatedFields.first { - self.log.verbose("Loading List of \(Element.schema.name) by \(associatedField) == \(associatedId) ") + log.verbose("Loading List of \(Element.schema.name) by \(associatedField) == \(associatedId) ") predicate = field(associatedField) == associatedId } else { let predicateValues = zip(associatedFields, associatedIdentifiers) var queryPredicates: [QueryPredicateOperation] = [] for (identifierName, identifierValue) in predicateValues { - queryPredicates.append(QueryPredicateOperation(field: identifierName, - operator: .equals(identifierValue))) + queryPredicates.append(QueryPredicateOperation( + field: identifierName, + operator: .equals(identifierValue) + )) } - self.log.verbose("Loading List of \(Element.schema.name) by \(associatedFields) == \(associatedIdentifiers) ") + log.verbose("Loading List of \(Element.schema.name) by \(associatedFields) == \(associatedIdentifiers) ") predicate = QueryPredicateGroup(type: .and, predicates: queryPredicates) } do { let elements = try await Amplify.DataStore.query(Element.self, where: predicate) - self.loadedState = .loaded(elements) + loadedState = .loaded(elements) return elements } catch let error as DataStoreError { self.log.error(error: error) - throw CoreError.listOperation("Failed to Query DataStore.", - "See underlying DataStoreError for more details.", - error) + throw CoreError.listOperation( + "Failed to Query DataStore.", + "See underlying DataStoreError for more details.", + error + ) } catch { throw error @@ -81,17 +87,23 @@ public class DataStoreListProvider: ModelListProvider { } public func getNextPage() async throws -> List { - throw CoreError.clientValidation("There is no next page.", - "Only call `getNextPage()` when `hasNextPage()` is true.", - nil) + throw CoreError.clientValidation( + "There is no next page.", + "Only call `getNextPage()` when `hasNextPage()` is true.", + nil + ) } public func encode(to encoder: Encoder) throws { switch loadedState { - case .notLoaded(let associatedIdentifiers, - let associatedFields): - let metadata = DataStoreListDecoder.Metadata(dataStoreAssociatedIdentifiers: associatedIdentifiers, - dataStoreAssociatedFields: associatedFields) + case .notLoaded( + let associatedIdentifiers, + let associatedFields + ): + let metadata = DataStoreListDecoder.Metadata( + dataStoreAssociatedIdentifiers: associatedIdentifiers, + dataStoreAssociatedFields: associatedFields + ) var container = encoder.singleValueContainer() try container.encode(metadata) case .loaded(let elements): diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelDecoder.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelDecoder.swift index ea4cd42ac9..92288c3984 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelDecoder.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelDecoder.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import SQLite import AWSPluginsCore +import Foundation +import SQLite public struct DataStoreModelDecoder: ModelProviderDecoder { @@ -17,8 +17,10 @@ public struct DataStoreModelDecoder: ModelProviderDecoder { let identifiers: [LazyReferenceIdentifier] let source: String - init(identifiers: [LazyReferenceIdentifier], - source: String = ModelProviderRegistry.DecoderSource.dataStore) { + init( + identifiers: [LazyReferenceIdentifier], + source: String = ModelProviderRegistry.DecoderSource.dataStore + ) { self.identifiers = identifiers self.source = source } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelProvider.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelProvider.swift index 64878140f9..d80236a773 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelProvider.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelProvider.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import Combine +import Foundation public class DataStoreModelProvider: ModelProvider { var loadedState: ModelProviderState @@ -27,20 +27,20 @@ public class DataStoreModelProvider: ModelProvider { public func load() async throws -> ModelType? { switch loadedState { case .notLoaded(let identifiers): - guard let identifiers = identifiers, !identifiers.isEmpty else { + guard let identifiers, !identifiers.isEmpty else { return nil } let identifierValue = identifiers.count == 1 ? identifiers.first?.value - : identifiers.map({ "\"\($0.value)\""}).joined(separator: ModelIdentifierFormat.Custom.separator) + : identifiers.map { "\"\($0.value)\""}.joined(separator: ModelIdentifierFormat.Custom.separator) let queryPredicate: QueryPredicate = field(ModelType.schema.primaryKey.sqlName).eq(identifierValue) let models = try await Amplify.DataStore.query(ModelType.self, where: queryPredicate) guard let model = models.first else { return nil } - self.loadedState = .loaded(model: model) + loadedState = .loaded(model: model) return model case .loaded(let model): return model diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/DataStoreSyncExpression.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/DataStoreSyncExpression.swift index f1ae361e7b..64f3782f32 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/DataStoreSyncExpression.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/DataStoreSyncExpression.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public typealias QueryPredicateResolver = () -> QueryPredicate @@ -14,8 +14,10 @@ public struct DataStoreSyncExpression { let modelSchema: ModelSchema let modelPredicate: QueryPredicateResolver - static public func syncExpression(_ modelSchema: ModelSchema, - where predicate: @escaping QueryPredicateResolver) -> DataStoreSyncExpression { + public static func syncExpression( + _ modelSchema: ModelSchema, + where predicate: @escaping QueryPredicateResolver + ) -> DataStoreSyncExpression { DataStoreSyncExpression(modelSchema: modelSchema, modelPredicate: predicate) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/ModelSyncMetadataMigration.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/ModelSyncMetadataMigration.swift index 0a0eb72e03..dc73d7039b 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/ModelSyncMetadataMigration.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/ModelSyncMetadataMigration.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Foundation import SQLite -import AWSPluginsCore class ModelSyncMetadataMigration: ModelMigration { @@ -37,19 +37,22 @@ class ModelSyncMetadataMigration: ModelMigration { func performModelMetadataSyncPredicateUpgrade() throws -> Bool { do { guard let field = ModelSyncMetadata.schema.field( - withName: ModelSyncMetadata.keys.syncPredicate.stringValue) else { + withName: ModelSyncMetadata.keys.syncPredicate.stringValue) + else { log.error("Could not find corresponding ModelField from ModelSyncMetadata for syncPredicate") return false } - let exists = try columnExists(modelSchema: ModelSyncMetadata.schema, - field: field) + let exists = try columnExists( + modelSchema: ModelSyncMetadata.schema, + field: field + ) guard !exists else { log.debug("Detected ModelSyncMetadata table has syncPredicate column. No migration needed") return false } log.debug("Detected ModelSyncMetadata table exists without syncPredicate column.") - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -58,7 +61,8 @@ class ModelSyncMetadataMigration: ModelMigration { } let addColumnStatement = AlterTableAddColumnStatement( modelSchema: ModelSyncMetadata.schema, - field: field).stringValue + field: field + ).stringValue try connection.execute(addColumnStatement) log.debug("ModelSyncMetadata table altered to add syncPredicate column.") return true @@ -68,7 +72,7 @@ class ModelSyncMetadataMigration: ModelMigration { } func columnExists(modelSchema: ModelSchema, field: ModelField) throws -> Bool { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataCopy.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataCopy.swift index 855b3cf079..32eb5a7bad 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataCopy.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataCopy.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension MutationSyncMetadataMigration { - public struct MutationSyncMetadataCopy: Model { + struct MutationSyncMetadataCopy: Model { public let id: String public var deleted: Bool public var lastChangedAt: Int64 diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigration.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigration.swift index f32c027cad..02fba91670 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigration.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigration.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSPluginsCore +import Foundation /// Migrates `MutationSyncMetadata` to the new format. /// @@ -23,7 +23,7 @@ class MutationSyncMetadataMigration: ModelMigration { } func apply() throws { - guard let delegate = delegate else { + guard let delegate else { log.debug("Missing MutationSyncMetadataMigrationDelegate delegate") throw DataStoreError.unknown("Missing MutationSyncMetadataMigrationDelegate delegate", "", nil) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLite.swift index 29aad4f815..fa2b198746 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLite.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Foundation import SQLite -import AWSPluginsCore final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMigrationDelegate { @@ -46,7 +46,7 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig // MARK: - Clear @discardableResult func emptyMutationSyncMetadataStore() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -55,7 +55,7 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig } @discardableResult func emptyModelSyncMetadataStore() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -66,7 +66,7 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig // MARK: - Migration @discardableResult func removeMutationSyncMetadataCopyStore() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -75,7 +75,7 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig } @discardableResult func createMutationSyncMetadataCopyStore() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -84,7 +84,7 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig } @discardableResult func backfillMutationSyncMetadata() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -110,7 +110,7 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig } @discardableResult func removeMutationSyncMetadataStore() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -119,13 +119,15 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig } @discardableResult func renameMutationSyncMetadataCopy() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } - return try storageAdapter.renameStore(from: MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema, - toModelSchema: MutationSyncMetadata.schema) + return try storageAdapter.renameStore( + from: MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema, + toModelSchema: MutationSyncMetadata.schema + ) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLiteValidation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLiteValidation.swift index 33115bf373..16122b8bdb 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLiteValidation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLiteValidation.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Foundation import SQLite -import AWSPluginsCore extension SQLiteMutationSyncMetadataMigrationDelegate { @@ -30,7 +30,8 @@ extension SQLiteMutationSyncMetadataMigrationDelegate { guard MutationSyncMetadata.schema.fields[idField] != nil, MutationSyncMetadata.schema.fields[deletedField] != nil, MutationSyncMetadata.schema.fields[lastChangedAtField] != nil, - MutationSyncMetadata.schema.fields[versionField] != nil else { + MutationSyncMetadata.schema.fields[versionField] != nil + else { throw DataStoreError.internalOperation("MutationSyncMetadata schema missing expected fields", "", nil) } @@ -41,7 +42,8 @@ extension SQLiteMutationSyncMetadataMigrationDelegate { guard MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema.fields[idField] != nil, MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema.fields[deletedField] != nil, MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema.fields[lastChangedAtField] != nil, - MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema.fields[versionField] != nil else { + MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema.fields[versionField] != nil + else { throw DataStoreError.internalOperation("MutationSyncMetadataCopy schema missing expected fields", "", nil) } } @@ -64,7 +66,7 @@ extension SQLiteMutationSyncMetadataMigrationDelegate { /// 1. the total number of records /// 2. the total number of records that have the `id` match `|` func selectMutationSyncMetadataRecords() throws -> (metadataCount: Int64, metadataIdMatchNewKeyCount: Int64) { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -93,7 +95,7 @@ extension SQLiteMutationSyncMetadataMigrationDelegate { // MARK: - Cannot Migrate func containsDuplicateIdsAcrossModels() throws -> Bool { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/CascadeDeleteOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/CascadeDeleteOperation.swift index 29687e390c..c90b03db15 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/CascadeDeleteOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/CascadeDeleteOperation.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore import Combine +import Foundation // swiftlint:disable type_body_length file_length /// CascadeDeleteOperation has the following logic: @@ -40,10 +40,11 @@ public class CascadeDeleteOperation: AsynchronousOperation { modelSchema: ModelSchema, withIdentifier identifier: ModelIdentifierProtocol, condition: QueryPredicate? = nil, - completion: @escaping (DataStoreResult) -> Void) { + completion: @escaping (DataStoreResult) -> Void + ) { var deleteInput = DeleteInput.withIdentifier(id: identifier) - if let condition = condition { + if let condition { deleteInput = .withIdentifierAndCondition(id: identifier, condition: condition) } self.init( @@ -53,7 +54,8 @@ public class CascadeDeleteOperation: AsynchronousOperation { modelSchema: modelSchema, deleteInput: deleteInput, completionForWithId: completion, - completionForWithFilter: nil) + completionForWithFilter: nil + ) } convenience init( @@ -62,7 +64,8 @@ public class CascadeDeleteOperation: AsynchronousOperation { modelType: M.Type, modelSchema: ModelSchema, filter: QueryPredicate, - completion: @escaping (DataStoreResult<[M]>) -> Void) { + completion: @escaping (DataStoreResult<[M]>) -> Void + ) { self.init( storageAdapter: storageAdapter, syncEngine: syncEngine, @@ -74,13 +77,14 @@ public class CascadeDeleteOperation: AsynchronousOperation { ) } - private init(storageAdapter: StorageEngineAdapter, - syncEngine: RemoteSyncEngineBehavior?, - modelType: M.Type, - modelSchema: ModelSchema, - deleteInput: DeleteInput, - completionForWithId: ((DataStoreResult) -> Void)?, - completionForWithFilter: ((DataStoreResult<[M]>) -> Void)? + private init( + storageAdapter: StorageEngineAdapter, + syncEngine: RemoteSyncEngineBehavior?, + modelType: M.Type, + modelSchema: ModelSchema, + deleteInput: DeleteInput, + completionForWithId: ((DataStoreResult) -> Void)?, + completionForWithFilter: ((DataStoreResult<[M]>) -> Void)? ) { self.storageAdapter = storageAdapter self.syncEngine = syncEngine @@ -118,36 +122,43 @@ public class CascadeDeleteOperation: AsynchronousOperation { var associatedModels: [(ModelName, Model)] = [] queriedResult = await withCheckedContinuation { continuation in - self.storageAdapter.query(self.modelType, - modelSchema: self.modelSchema, - predicate: self.deleteInput.predicate, - sort: nil, - paginationInput: nil, - eagerLoad: true) { result in + self.storageAdapter.query( + self.modelType, + modelSchema: self.modelSchema, + predicate: self.deleteInput.predicate, + sort: nil, + paginationInput: nil, + eagerLoad: true + ) { result in continuation.resume(returning: result) } } guard case .success(let queriedModels) = queriedResult else { - return collapseResults(queryResult: queriedResult, - deleteResult: deletedResult, - associatedModels: associatedModels) + return collapseResults( + queryResult: queriedResult, + deleteResult: deletedResult, + associatedModels: associatedModels + ) } guard !queriedModels.isEmpty else { - guard case .withIdentifierAndCondition(let identifier, _) = self.deleteInput else { + guard case .withIdentifierAndCondition(let identifier, _) = deleteInput else { // Query did not return any results, treat this as a successful no-op delete. deletedResult = .success([M]()) - return collapseResults(queryResult: queriedResult, - deleteResult: deletedResult, - associatedModels: associatedModels) + return collapseResults( + queryResult: queriedResult, + deleteResult: deletedResult, + associatedModels: associatedModels + ) } // Query using the computed predicate did not return any results, check if model actually exists. do { - if try self.storageAdapter.exists(self.modelSchema, withIdentifier: identifier, predicate: nil) { + if try storageAdapter.exists(modelSchema, withIdentifier: identifier, predicate: nil) { queriedResult = .failure( DataStoreError.invalidCondition( "Delete failed due to condition did not match existing model instance.", - "Subsequent deletes will continue to fail until the model instance is updated.")) + "Subsequent deletes will continue to fail until the model instance is updated." + )) } else { deletedResult = .success([M]()) } @@ -155,26 +166,33 @@ public class CascadeDeleteOperation: AsynchronousOperation { queriedResult = .failure(DataStoreError.invalidOperation(causedBy: error)) } - return collapseResults(queryResult: queriedResult, - deleteResult: deletedResult, - associatedModels: associatedModels) + return collapseResults( + queryResult: queriedResult, + deleteResult: deletedResult, + associatedModels: associatedModels + ) } let modelIds = queriedModels.map { $0.identifier(schema: self.modelSchema).stringValue } + // swiftformat:disable redundantSelf logMessage("[CascadeDelete.1] Deleting \(self.modelSchema.name) with identifiers: \(modelIds)") - - associatedModels = await self.recurseQueryAssociatedModels(modelSchema: self.modelSchema, ids: modelIds) + // swiftformat:enable redundantSelf + associatedModels = await recurseQueryAssociatedModels(modelSchema: modelSchema, ids: modelIds) deletedResult = await withCheckedContinuation { continuation in - self.storageAdapter.delete(self.modelType, - modelSchema: self.modelSchema, - filter: self.deleteInput.predicate) { result in + self.storageAdapter.delete( + self.modelType, + modelSchema: self.modelSchema, + filter: self.deleteInput.predicate + ) { result in continuation.resume(returning: result) } } - return collapseResults(queryResult: queriedResult, - deleteResult: deletedResult, - associatedModels: associatedModels) + return collapseResults( + queryResult: queriedResult, + deleteResult: deletedResult, + associatedModels: associatedModels + ) } func recurseQueryAssociatedModels(modelSchema: ModelSchema, ids: [String]) async -> [(ModelName, Model)] { @@ -195,7 +213,8 @@ public class CascadeDeleteOperation: AsynchronousOperation { let queriedModels = await queryAssociatedModels( associatedModelSchema: associatedModelSchema, associatedField: associatedField, - ids: ids) + ids: ids + ) let associatedModelIds = queriedModels.map { $0.1.identifier(schema: associatedModelSchema).stringValue @@ -204,18 +223,21 @@ public class CascadeDeleteOperation: AsynchronousOperation { logMessage("[CascadeDelete.2] Queried for \(associatedModelSchema.name), retrieved ids for deletion: \(associatedModelIds)") associatedModels.append(contentsOf: queriedModels) - associatedModels.append(contentsOf: await recurseQueryAssociatedModels( + await associatedModels.append(contentsOf: recurseQueryAssociatedModels( modelSchema: associatedModelSchema, - ids: associatedModelIds) + ids: associatedModelIds + ) ) } return associatedModels } - func queryAssociatedModels(associatedModelSchema modelSchema: ModelSchema, - associatedField: ModelField, - ids: [String]) async -> [(ModelName, Model)] { + func queryAssociatedModels( + associatedModelSchema modelSchema: ModelSchema, + associatedField: ModelField, + ids: [String] + ) async -> [(ModelName, Model)] { var queriedModels: [(ModelName, Model)] = [] let chunkedArrays = ids.chunked(into: SQLiteStorageEngineAdapter.maxNumberOfPredicates) for chunkedArray in chunkedArrays { @@ -248,21 +270,25 @@ public class CascadeDeleteOperation: AsynchronousOperation { associatedModels: [(ModelName, Model)] ) -> DataStoreResult> { - guard let queryResult = queryResult else { + guard let queryResult else { return .failure(.unknown("queryResult not set during transaction", "coding error", nil)) } switch queryResult { case .success(let models): - guard let deleteResult = deleteResult else { + guard let deleteResult else { return .failure(.unknown("deleteResult not set during transaction", "coding error", nil)) } switch deleteResult { case .success: + // swiftformat:disable redundantSelf logMessage("[CascadeDelete.3] Local cascade delete of \(self.modelSchema.name) successful!") - return .success(QueryAndDeleteResult(deletedModels: models, - associatedModels: associatedModels)) + // swiftformat:enable redundantSelf + return .success(QueryAndDeleteResult( + deletedModels: models, + associatedModels: associatedModels + )) case .failure(let error): return .failure(error) } @@ -302,7 +328,7 @@ public class CascadeDeleteOperation: AsynchronousOperation { } } - guard modelSchema.isSyncable, let syncEngine = self.syncEngine else { + guard modelSchema.isSyncable, let syncEngine else { if !modelSchema.isSystem { log.error("Unable to sync model (\(modelSchema.name)) where isSyncable is false") } @@ -336,9 +362,11 @@ public class CascadeDeleteOperation: AsynchronousOperation { // mutation? switch deleteInput { case .withIdentifier, .withIdentifierAndCondition: - syncDeletions(withModels: queryAndDeleteResult.deletedModels, - associatedModels: queryAndDeleteResult.associatedModels, - syncEngine: syncEngine) { + syncDeletions( + withModels: queryAndDeleteResult.deletedModels, + associatedModels: queryAndDeleteResult.associatedModels, + syncEngine: syncEngine + ) { switch $0 { case .success: self.completionForWithId?(.success(queryAndDeleteResult.deletedModels.first)) @@ -348,10 +376,12 @@ public class CascadeDeleteOperation: AsynchronousOperation { self.finish() } case .withFilter(let filter): - syncDeletions(withModels: queryAndDeleteResult.deletedModels, - predicate: filter, - associatedModels: queryAndDeleteResult.associatedModels, - syncEngine: syncEngine) { + syncDeletions( + withModels: queryAndDeleteResult.deletedModels, + predicate: filter, + associatedModels: queryAndDeleteResult.associatedModels, + syncEngine: syncEngine + ) { switch $0 { case .success: self.completionForWithFilter?(.success(queryAndDeleteResult.deletedModels)) @@ -382,30 +412,36 @@ public class CascadeDeleteOperation: AsynchronousOperation { // collection and provide access in reverse order. // For more details: https://developer.apple.com/documentation/swift/array/1690025-reversed @available(iOS 13.0, *) - private func syncDeletions(withModels models: [M], - predicate: QueryPredicate? = nil, - associatedModels: [(ModelName, Model)], - syncEngine: RemoteSyncEngineBehavior, - completion: @escaping DataStoreCallback) { + private func syncDeletions( + withModels models: [M], + predicate: QueryPredicate? = nil, + associatedModels: [(ModelName, Model)], + syncEngine: RemoteSyncEngineBehavior, + completion: @escaping DataStoreCallback + ) { var savedDataStoreError: DataStoreError? guard !associatedModels.isEmpty else { - syncDeletions(withModels: models, - predicate: predicate, - syncEngine: syncEngine, - dataStoreError: savedDataStoreError, - completion: completion) + syncDeletions( + withModels: models, + predicate: predicate, + syncEngine: syncEngine, + dataStoreError: savedDataStoreError, + completion: completion + ) return } - self.log.debug("[CascadeDelete.4] Begin syncing \(associatedModels.count) associated models for deletion. ") + log.debug("[CascadeDelete.4] Begin syncing \(associatedModels.count) associated models for deletion. ") var mutationEventsSubmitCompleted = 0 for (modelName, associatedModel) in associatedModels.reversed() { let mutationEvent: MutationEvent do { - mutationEvent = try MutationEvent(untypedModel: associatedModel, - modelName: modelName, - mutationType: .delete) + mutationEvent = try MutationEvent( + untypedModel: associatedModel, + modelName: modelName, + mutationType: .delete + ) } catch { let dataStoreError = DataStoreError(error: error) completion(.failure(dataStoreError)) @@ -426,33 +462,43 @@ public class CascadeDeleteOperation: AsynchronousOperation { } if mutationEventsSubmitCompleted == associatedModels.count { - self.syncDeletions(withModels: models, - predicate: predicate, - syncEngine: syncEngine, - dataStoreError: savedDataStoreError, - completion: completion) + self.syncDeletions( + withModels: models, + predicate: predicate, + syncEngine: syncEngine, + dataStoreError: savedDataStoreError, + completion: completion + ) } } } - submitToSyncEngine(mutationEvent: mutationEvent, - syncEngine: syncEngine, - completion: mutationEventCallback) + submitToSyncEngine( + mutationEvent: mutationEvent, + syncEngine: syncEngine, + completion: mutationEventCallback + ) } } @available(iOS 13.0, *) - private func syncDeletions(withModels models: [M], - predicate: QueryPredicate? = nil, - syncEngine: RemoteSyncEngineBehavior, - dataStoreError: DataStoreError?, - completion: @escaping DataStoreCallback) { + private func syncDeletions( + withModels models: [M], + predicate: QueryPredicate? = nil, + syncEngine: RemoteSyncEngineBehavior, + dataStoreError: DataStoreError?, + completion: @escaping DataStoreCallback + ) { + // swiftformat:disable redundantSelf logMessage("[CascadeDelete.4] Begin syncing \(models.count) \(self.modelSchema.name) model for deletion") + // swiftformat:enable redundantSelf var graphQLFilterJSON: String? - if let predicate = predicate { + if let predicate { do { - graphQLFilterJSON = try GraphQLFilterConverter.toJSON(predicate, - modelSchema: modelSchema) + graphQLFilterJSON = try GraphQLFilterConverter.toJSON( + predicate, + modelSchema: modelSchema + ) } catch { let dataStoreError = DataStoreError(error: error) completion(.failure(dataStoreError)) @@ -464,10 +510,12 @@ public class CascadeDeleteOperation: AsynchronousOperation { for model in models { let mutationEvent: MutationEvent do { - mutationEvent = try MutationEvent(model: model, - modelSchema: modelSchema, - mutationType: .delete, - graphQLFilterJSON: graphQLFilterJSON) + mutationEvent = try MutationEvent( + model: model, + modelSchema: modelSchema, + mutationType: .delete, + graphQLFilterJSON: graphQLFilterJSON + ) } catch { let dataStoreError = DataStoreError(error: error) completion(.failure(dataStoreError)) @@ -496,21 +544,26 @@ public class CascadeDeleteOperation: AsynchronousOperation { } } - submitToSyncEngine(mutationEvent: mutationEvent, - syncEngine: syncEngine, - completion: mutationEventCallback) + submitToSyncEngine( + mutationEvent: mutationEvent, + syncEngine: syncEngine, + completion: mutationEventCallback + ) } } - private func submitToSyncEngine(mutationEvent: MutationEvent, - syncEngine: RemoteSyncEngineBehavior, - completion: @escaping DataStoreCallback) { + private func submitToSyncEngine( + mutationEvent: MutationEvent, + syncEngine: RemoteSyncEngineBehavior, + completion: @escaping DataStoreCallback + ) { syncEngine.submit(mutationEvent, completion: completion) } private func logMessage( _ message: @escaping @autoclosure () -> String, - level log: (() -> String) -> Void = log.debug) { + level log: (() -> String) -> Void = log.debug + ) { guard isDeveloperDefinedModel else { return } log(message) } @@ -535,9 +588,13 @@ extension CascadeDeleteOperation { case .withIdentifier(let identifier): return identifier.predicate case .withIdentifierAndCondition(let identifier, let predicate): - return QueryPredicateGroup(type: .and, - predicates: [identifier.predicate, - predicate]) + return QueryPredicateGroup( + type: .and, + predicates: [ + identifier.predicate, + predicate + ] + ) case .withFilter(let predicate): return predicate } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/ModelStorageBehavior.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/ModelStorageBehavior.swift index e33537baa5..b4dca1abc4 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/ModelStorageBehavior.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/ModelStorageBehavior.swift @@ -15,49 +15,63 @@ protocol ModelStorageBehavior { /// Apply any data migration logic for the given schemas in the underlying data store. func applyModelMigrations(modelSchemas: [ModelSchema]) throws - func save(_ model: M, - modelSchema: ModelSchema, - condition: QueryPredicate?, - eagerLoad: Bool, - completion: @escaping DataStoreCallback) + func save( + _ model: M, + modelSchema: ModelSchema, + condition: QueryPredicate?, + eagerLoad: Bool, + completion: @escaping DataStoreCallback + ) - func save(_ model: M, - condition: QueryPredicate?, - eagerLoad: Bool, - completion: @escaping DataStoreCallback) + func save( + _ model: M, + condition: QueryPredicate?, + eagerLoad: Bool, + completion: @escaping DataStoreCallback + ) @available(*, deprecated, message: "Use delete(:modelSchema:withIdentifier:predicate:completion") - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withId id: Model.Identifier, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withId id: Model.Identifier, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - filter: QueryPredicate, - completion: @escaping DataStoreCallback<[M]>) + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + filter: QueryPredicate, + completion: @escaping DataStoreCallback<[M]> + ) - func query(_ modelType: M.Type, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: DataStoreCallback<[M]>) + func query( + _ modelType: M.Type, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: DataStoreCallback<[M]> + ) - func query(_ modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: DataStoreCallback<[M]>) + func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: DataStoreCallback<[M]> + ) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Model+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Model+SQLite.swift index 7ff35dccb2..1570a7030d 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Model+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Model+SQLite.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Foundation import SQLite -import AWSPluginsCore /// Extended types that conform to `Persistable` in order to provide conversion to SQLite's `Binding` /// types. This is necessary so `Model` properties' map values to a SQLite compatible types. @@ -22,12 +22,14 @@ extension Persistable { /// - Note: a `preconditionFailure` might happen in case the value cannot be converted. /// /// - Returns: the value as `Binding` - internal func asBinding() -> Binding { + func asBinding() -> Binding { let value = self let valueType = type(of: value) do { - let binding = try SQLiteModelValueConverter.convertToTarget(from: value, - fieldType: .from(type: valueType)) + let binding = try SQLiteModelValueConverter.convertToTarget( + from: value, + fieldType: .from(type: valueType) + ) guard let validBinding = binding else { return Fatal.preconditionFailure(""" Converting \(String(describing: value)) of type \(String(describing: valueType)) @@ -58,7 +60,7 @@ extension Model { /// /// - Parameter fields: an optional subset of fields /// - Returns: an array of SQLite's `Binding` compatible type - internal func sqlValues(for fields: [ModelField]? = nil, modelSchema: ModelSchema) -> [Binding?] { + func sqlValues(for fields: [ModelField]? = nil, modelSchema: ModelSchema) -> [Binding?] { let modelFields = fields ?? modelSchema.sortedFields let values: [Binding?] = modelFields.map { field in @@ -117,7 +119,7 @@ extension Model { // from the not loaded identifier's stringValue (the value, or the formatted value for CPK) switch associatedLazyModel._state { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { + guard let identifiers else { return nil } return identifiers.stringValue @@ -125,8 +127,10 @@ extension Model { return model?.identifier } } else if let associatedModelJSON = value as? [String: JSONValue] { - return associatedPrimaryKeyValue(fromJSON: associatedModelJSON, - associatedModelSchema: associatedModelSchema) + return associatedPrimaryKeyValue( + fromJSON: associatedModelJSON, + associatedModelSchema: associatedModelSchema + ) } } @@ -153,8 +157,10 @@ extension Model { /// - associatedModelJSON: model as JSON value /// - associatedModelSchema: model's schema /// - Returns: serialized value of the primary key - private func associatedPrimaryKeyValue(fromJSON associatedModelJSON: [String: JSONValue], - associatedModelSchema: ModelSchema) -> String { + private func associatedPrimaryKeyValue( + fromJSON associatedModelJSON: [String: JSONValue], + associatedModelSchema: ModelSchema + ) -> String { let associatedModelPKFields: ModelIdentifierProtocol.Fields // get the associated model primary key fields @@ -172,7 +178,7 @@ extension Model { } -extension Array where Element == ModelSchema { +extension [ModelSchema] { /// Sort the [ModelSchema] array based on the associations between them. /// @@ -200,7 +206,7 @@ extension Array where Element == ModelSchema { if !sortedKeys.contains(schema.name) { let associatedModelSchemas = schema.sortedFields .filter { $0.isForeignKey } - .map { (schema) -> ModelSchema in + .map { schema -> ModelSchema in guard let associatedSchema = ModelRegistry.modelSchema(from: schema.requiredAssociatedModelName) else { return Fatal.preconditionFailure(""" @@ -230,7 +236,7 @@ extension Array where Element == ModelSchema { } } -extension ModelIdentifierFormat.Custom { +public extension ModelIdentifierFormat.Custom { /// Name for composite identifier (multiple fields) - public static let sqlColumnName = "@@primaryKey" + static let sqlColumnName = "@@primaryKey" } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelSchema+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelSchema+SQLite.swift index ab3bf52aff..3fd7a15ae4 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelSchema+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelSchema+SQLite.swift @@ -41,10 +41,12 @@ extension ModelPrimaryKey: SQLColumn { /// Convenience method to convert a ModelPrimaryKey to an /// ModelField to be used in a SQL query var asField: ModelField { - ModelField(name: name, - type: .string, - isRequired: true, - attributes: [.primaryKey]) + ModelField( + name: name, + type: .string, + isRequired: true, + attributes: [.primaryKey] + ) } var sqlType: SQLDataType { @@ -69,7 +71,7 @@ extension ModelPrimaryKey: SQLColumn { } let columnName = ModelIdentifierFormat.Custom.sqlColumnName.quoted() - if let namespace = namespace { + if let namespace { return "\(namespace.quoted()).\(columnName)" } @@ -130,7 +132,7 @@ extension ModelField: SQLColumn { /// - Returns: a valid (i.e. escaped) SQL column name func columnName(forNamespace namespace: String? = nil) -> String { var column = sqlName.quoted() - if let namespace = namespace { + if let namespace { column = namespace.quoted() + "." + column } return column @@ -148,7 +150,7 @@ extension ModelField: SQLColumn { /// the call `field.columnAlias(forNamespace: "post")` would return `as "post.id"`. func columnAlias(forNamespace namespace: String? = nil) -> String { var column = sqlName - if let namespace = namespace { + if let namespace { column = "\(namespace).\(column)" } return column.quoted() @@ -172,14 +174,14 @@ extension ModelSchema { /// Filter the fields that represent foreign keys. var foreignKeys: [ModelField] { - sortedFields.filter { $0.isForeignKey } + sortedFields.filter(\.isForeignKey) } /// Create SQLite indexes corresponding to secondary indexes in the model schema func createIndexStatements() -> String { // Store field names used to represent associations for a fast lookup var associationsFields = Set() - for (_, field) in self.fields { + for (_, field) in fields { if field.isAssociationOwner, let association = field.association, case let .belongsTo(_, targetNames: targetNames) = association { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelValueConverter+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelValueConverter+SQLite.swift index ab1a85aed9..523802f8ce 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelValueConverter+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelValueConverter+SQLite.swift @@ -9,7 +9,7 @@ import Amplify import Foundation import SQLite -internal extension Bool { +extension Bool { var intValue: Int { return self ? Int(1) : Int(0) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/QuerySortDescriptor.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/QuerySortDescriptor.swift index 913e63545a..d3436c6925 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/QuerySortDescriptor.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/QuerySortDescriptor.swift @@ -31,22 +31,26 @@ public enum QuerySortOrder: String { case descending = "desc" } -extension Array where Element == QuerySortDescriptor { +extension [QuerySortDescriptor] { /// Generates the sorting part of the sql statement. /// /// For a sort description of ascending on `Post.createdAt` will return the string `"\"root\".\"createdAt\" asc"` /// where `root` is the namespace. func sortStatement(namespace: String) -> String { - let sqlResult = map { Array.columnFor(field: $0.fieldName, - order: $0.order.rawValue, - namespace: namespace) } + let sqlResult = map { Array.columnFor( + field: $0.fieldName, + order: $0.order.rawValue, + namespace: namespace + ) } return sqlResult.joined(separator: ", ") } - static func columnFor(field: String, - order: String, - namespace: String) -> String { + static func columnFor( + field: String, + order: String, + namespace: String + ) -> String { return namespace.quoted() + "." + field.quoted() + " " + order } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Condition.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Condition.swift index 2a774992d3..0b83db01c2 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Condition.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Condition.swift @@ -18,9 +18,11 @@ typealias SQLPredicate = (String, [Binding?]) /// - modelSchema: the model schema of the `Model` /// - predicate: the query predicate /// - Returns: a tuple containing the SQL string and the associated values -private func translateQueryPredicate(from modelSchema: ModelSchema, - predicate: QueryPredicate, - namespace: Substring? = nil) -> SQLPredicate { +private func translateQueryPredicate( + from modelSchema: ModelSchema, + predicate: QueryPredicate, + namespace: Substring? = nil +) -> SQLPredicate { var sql: [String] = [] var bindings: [Binding?] = [] let indentPrefix = " " @@ -66,11 +68,11 @@ private func translateQueryPredicate(from modelSchema: ModelSchema, func resolveColumn(_ operation: QueryPredicateOperation) -> String { let modelField = modelSchema.field(withName: operation.field) - if let namespace = namespace, let modelField = modelField { + if let namespace, let modelField { return modelField.columnName(forNamespace: String(namespace)) - } else if let modelField = modelField { + } else if let modelField { return modelField.columnName() - } else if let namespace = namespace { + } else if let namespace { return String(namespace).quoted() + "." + operation.field.quoted() } return operation.field.quoted() @@ -150,9 +152,11 @@ struct ConditionStatement: SQLStatement { init(modelSchema: ModelSchema, predicate: QueryPredicate, namespace: Substring? = nil) { self.modelSchema = modelSchema - let (sql, variables) = translateQueryPredicate(from: modelSchema, - predicate: predicate, - namespace: namespace) + let (sql, variables) = translateQueryPredicate( + from: modelSchema, + predicate: predicate, + namespace: namespace + ) self.stringValue = sql self.variables = variables } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Delete.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Delete.swift index 26290d6968..162824d773 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Delete.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Delete.swift @@ -20,31 +20,39 @@ struct DeleteStatement: SQLStatement { self.modelSchema = modelSchema var conditionStatement: ConditionStatement? - if let predicate = predicate { - let statement = ConditionStatement(modelSchema: modelSchema, - predicate: predicate, - namespace: namespace[...]) + if let predicate { + let statement = ConditionStatement( + modelSchema: modelSchema, + predicate: predicate, + namespace: namespace[...] + ) conditionStatement = statement } self.conditionStatement = conditionStatement } - init(_: M.Type, - modelSchema: ModelSchema, - withId id: String, - predicate: QueryPredicate? = nil) { + init( + _: M.Type, + modelSchema: ModelSchema, + withId id: String, + predicate: QueryPredicate? = nil + ) { let identifier = DefaultModelIdentifier.makeDefault(id: id) - self.init(modelSchema: modelSchema, - withIdentifier: identifier, - predicate: predicate) + self.init( + modelSchema: modelSchema, + withIdentifier: identifier, + predicate: predicate + ) } - init(modelSchema: ModelSchema, - withIdentifier id: ModelIdentifierProtocol, - predicate: QueryPredicate? = nil) { + init( + modelSchema: ModelSchema, + withIdentifier id: ModelIdentifierProtocol, + predicate: QueryPredicate? = nil + ) { var queryPredicate: QueryPredicate = field(modelSchema.primaryKey.sqlName) .eq(id.stringValue) - if let predicate = predicate { + if let predicate { queryPredicate = field(modelSchema.primaryKey.sqlName) .eq(id.stringValue).and(predicate) } @@ -60,7 +68,7 @@ struct DeleteStatement: SQLStatement { delete from "\(modelSchema.name)" as \(namespace) """ - if let conditionStatement = conditionStatement { + if let conditionStatement { return """ \(sql) where 1 = 1 diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Select.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Select.swift index 9a0b9e909a..10740385bb 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Select.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Select.swift @@ -19,11 +19,13 @@ struct SelectStatementMetadata { let columnMapping: ColumnMapping let bindings: [Binding?] - static func metadata(from modelSchema: ModelSchema, - predicate: QueryPredicate? = nil, - sort: [QuerySortDescriptor]? = nil, - paginationInput: QueryPaginationInput? = nil, - eagerLoad: Bool = true) -> SelectStatementMetadata { + static func metadata( + from modelSchema: ModelSchema, + predicate: QueryPredicate? = nil, + sort: [QuerySortDescriptor]? = nil, + paginationInput: QueryPaginationInput? = nil, + eagerLoad: Bool = true + ) -> SelectStatementMetadata { let rootNamespace = "root" let fields = modelSchema.columns let tableName = modelSchema.name @@ -46,10 +48,12 @@ struct SelectStatementMetadata { """.trimmingCharacters(in: .whitespacesAndNewlines) var bindings: [Binding?] = [] - if let predicate = predicate { - let conditionStatement = ConditionStatement(modelSchema: modelSchema, - predicate: predicate, - namespace: rootNamespace[...]) + if let predicate { + let conditionStatement = ConditionStatement( + modelSchema: modelSchema, + predicate: predicate, + namespace: rootNamespace[...] + ) bindings.append(contentsOf: conditionStatement.variables) sql = """ \(sql) @@ -58,23 +62,25 @@ struct SelectStatementMetadata { """ } - if let sort = sort, !sort.isEmpty { + if let sort, !sort.isEmpty { sql = """ \(sql) order by \(sort.sortStatement(namespace: rootNamespace)) """ } - if let paginationInput = paginationInput { + if let paginationInput { sql = """ \(sql) \(paginationInput.sqlStatement) """ } - return SelectStatementMetadata(statement: sql, - columnMapping: columnMapping, - bindings: bindings) + return SelectStatementMetadata( + statement: sql, + columnMapping: columnMapping, + bindings: bindings + ) } struct JoinStatement { @@ -92,9 +98,11 @@ struct SelectStatementMetadata { var joinStatements: [String] = [] var columnMapping: ColumnMapping = [:] guard eagerLoad == true else { - return JoinStatement(columns: columns, - statements: joinStatements, - columnMapping: columnMapping) + return JoinStatement( + columns: columns, + statements: joinStatements, + columnMapping: columnMapping + ) } func visitAssociations(node: ModelSchema, namespace: String = "root") { @@ -131,9 +139,11 @@ struct SelectStatementMetadata { } visitAssociations(node: schema) - return JoinStatement(columns: columns, - statements: joinStatements, - columnMapping: columnMapping) + return JoinStatement( + columns: columns, + statements: joinStatements, + columnMapping: columnMapping + ) } } @@ -145,17 +155,21 @@ struct SelectStatement: SQLStatement { let modelSchema: ModelSchema let metadata: SelectStatementMetadata - init(from modelSchema: ModelSchema, - predicate: QueryPredicate? = nil, - sort: [QuerySortDescriptor]? = nil, - paginationInput: QueryPaginationInput? = nil, - eagerLoad: Bool = true) { + init( + from modelSchema: ModelSchema, + predicate: QueryPredicate? = nil, + sort: [QuerySortDescriptor]? = nil, + paginationInput: QueryPaginationInput? = nil, + eagerLoad: Bool = true + ) { self.modelSchema = modelSchema - self.metadata = .metadata(from: modelSchema, - predicate: predicate, - sort: sort, - paginationInput: paginationInput, - eagerLoad: eagerLoad) + self.metadata = .metadata( + from: modelSchema, + predicate: predicate, + sort: sort, + paginationInput: paginationInput, + eagerLoad: eagerLoad + ) } var stringValue: String { @@ -175,7 +189,7 @@ struct SelectStatement: SQLStatement { /// - Parameter columns the list of column names /// - Parameter perLine max numbers of columns per line /// - Returns: a list of columns that can be used in `select` SQL statements -internal func joinedAsSelectedColumns(_ columns: [String], perLine: Int = 3) -> String { +func joinedAsSelectedColumns(_ columns: [String], perLine: Int = 3) -> String { return columns.enumerated().reduce("") { partial, entry in let spacer = entry.offset == 0 || entry.offset % perLine == 0 ? "\n " : " " let isFirstOrLast = entry.offset == 0 || entry.offset >= columns.count diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Update.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Update.swift index 70df1854ec..f409583581 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Update.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Update.swift @@ -22,9 +22,11 @@ struct UpdateStatement: SQLStatement { self.modelSchema = modelSchema var conditionStatement: ConditionStatement? - if let condition = condition { - let statement = ConditionStatement(modelSchema: modelSchema, - predicate: condition) + if let condition { + let statement = ConditionStatement( + modelSchema: modelSchema, + predicate: condition + ) conditionStatement = statement } @@ -45,7 +47,7 @@ struct UpdateStatement: SQLStatement { where \(modelSchema.primaryKey.columnName()) = ? """ - if let conditionStatement = conditionStatement { + if let conditionStatement { sql = """ \(sql) \(conditionStatement.stringValue) @@ -58,7 +60,7 @@ struct UpdateStatement: SQLStatement { var variables: [Binding?] { var bindings = model.sqlValues(for: updateColumns, modelSchema: modelSchema) bindings.append(model.identifier(schema: modelSchema).stringValue) - if let conditionStatement = conditionStatement { + if let conditionStatement { bindings.append(contentsOf: conditionStatement.variables) } return bindings diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+AnyModel.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+AnyModel.swift index 332e1b8ba6..8e25d4542c 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+AnyModel.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+AnyModel.swift @@ -6,26 +6,30 @@ // import Amplify -import SQLite import Foundation +import SQLite extension Statement { - func convertToUntypedModel(using modelSchema: ModelSchema, - statement: SelectStatement, - eagerLoad: Bool) throws -> [Model] { + func convertToUntypedModel( + using modelSchema: ModelSchema, + statement: SelectStatement, + eagerLoad: Bool + ) throws -> [Model] { var models = [Model]() for row in self { - let modelValues = try convert(row: row, - withSchema: modelSchema, - using: statement, - eagerLoad: eagerLoad) + let modelValues = try convert( + row: row, + withSchema: modelSchema, + using: statement, + eagerLoad: eagerLoad + ) let untypedModel = try modelValues.map { try convertToAnyModel(using: modelSchema, modelDictionary: $0) } - if let untypedModel = untypedModel { + if let untypedModel { models.append(untypedModel) } } @@ -33,8 +37,10 @@ extension Statement { return models } - private func convertToAnyModel(using modelSchema: ModelSchema, - modelDictionary: ModelValues) throws -> Model { + private func convertToAnyModel( + using modelSchema: ModelSchema, + modelDictionary: ModelValues + ) throws -> Model { let data = try JSONSerialization.data(withJSONObject: modelDictionary) guard let jsonString = String(data: data, encoding: .utf8) else { let error = DataStoreError.decodingError( diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+Model.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+Model.swift index 4345db1a74..58ce7b8234 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+Model.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+Model.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Foundation import SQLite -import AWSPluginsCore typealias ModelValues = [String: Any?] @@ -39,10 +39,12 @@ protocol StatementModelConvertible { /// - modelSchema - the schema for `Model` /// - statement - the query executed that generated this result /// - Returns: an array of `Model` of the specified type - func convert(to modelType: M.Type, - withSchema modelSchema: ModelSchema, - using statement: SelectStatement, - eagerLoad: Bool) throws -> [M] + func convert( + to modelType: M.Type, + withSchema modelSchema: ModelSchema, + using statement: SelectStatement, + eagerLoad: Bool + ) throws -> [M] } @@ -53,23 +55,29 @@ extension Statement: StatementModelConvertible { Amplify.Logging.logger(forCategory: .dataStore) } - func convert(to modelType: M.Type, - withSchema modelSchema: ModelSchema, - using statement: SelectStatement, - eagerLoad: Bool = true) throws -> [M] { - let elements: [ModelValues] = try self.convertToModelValues(to: modelType, - withSchema: modelSchema, - using: statement, - eagerLoad: eagerLoad) + func convert( + to modelType: M.Type, + withSchema modelSchema: ModelSchema, + using statement: SelectStatement, + eagerLoad: Bool = true + ) throws -> [M] { + let elements: [ModelValues] = try convertToModelValues( + to: modelType, + withSchema: modelSchema, + using: statement, + eagerLoad: eagerLoad + ) let values: ModelValues = ["elements": elements] let result: StatementResult = try StatementResult.from(dictionary: values) return result.elements } - func convertToModelValues(to modelType: M.Type, - withSchema modelSchema: ModelSchema, - using statement: SelectStatement, - eagerLoad: Bool = true) throws -> [ModelValues] { + func convertToModelValues( + to modelType: (some Model).Type, + withSchema modelSchema: ModelSchema, + using statement: SelectStatement, + eagerLoad: Bool = true + ) throws -> [ModelValues] { var elements: [ModelValues] = [] // parse each row of the result @@ -150,7 +158,8 @@ extension Statement: StatementModelConvertible { withSchema: modelSchema, using: statement, eagerLoad: eagerLoad, - path: path + [field.name]) + path: path + [field.name] + ) default: let value = getValue(from: element, by: path + [field.name]) @@ -159,41 +168,45 @@ extension Statement: StatementModelConvertible { } private func getModelSchema(for modelName: ModelName, with statement: SelectStatement) -> ModelSchema? { - return statement.metadata.columnMapping.values.first { $0.0.name == modelName }.map { $0.0 } + return statement.metadata.columnMapping.values.first { $0.0.name == modelName }.map(\.0) } private func associatedValues(from foreignKeyPath: [String], element: Element) -> [String] { return [getValue(from: element, by: foreignKeyPath)] - .compactMap({ $0 }) - .map({ String(describing: $0) }) - .flatMap({ $0.split(separator: ModelIdentifierFormat.Custom.separator.first!) }) - .map({ String($0).trimmingCharacters(in: .init(charactersIn: "\"")) }) + .compactMap { $0 } + .map { String(describing: $0) } + .flatMap { $0.split(separator: ModelIdentifierFormat.Custom.separator.first!) } + .map { String($0).trimmingCharacters(in: .init(charactersIn: "\"")) } } private func convertCollection(field: ModelField, schema: ModelSchema, from element: Element, path: [String]) -> Any? { if field.isArray && field.hasAssociation, case let .some(.hasMany(associatedFieldName: associatedFieldName, associatedFieldNames: associatedFieldNames)) = field.association { // Construct the lazy list based on the field reference name and `@@primarykey` or primary key field of the parent - if associatedFieldNames.count <= 1, let associatedFieldName = associatedFieldName { + if associatedFieldNames.count <= 1, let associatedFieldName { let primaryKeyName = schema.primaryKey.isCompositeKey ? ModelIdentifierFormat.Custom.sqlColumnName - : schema.primaryKey.fields.first.flatMap { $0.name } + : schema.primaryKey.fields.first.flatMap{ $0.name } let primaryKeyValue = primaryKeyName.flatMap { getValue(from: element, by: path + [$0]) } return primaryKeyValue.map { - DataStoreListDecoder.lazyInit(associatedIds: [String(describing: $0)], - associatedWith: [associatedFieldName]) + DataStoreListDecoder.lazyInit( + associatedIds: [String(describing: $0)], + associatedWith: [associatedFieldName] + ) } } else { // If `targetNames` is > 1, then this is a uni-directional has-many, thus no reference field on the child // Construct the lazy list based on the primary key values and the corresponding target names - let primaryKeyNames = schema.primaryKey.fields.map { $0.name } + let primaryKeyNames = schema.primaryKey.fields.map(\.name) let primaryKeyValues = primaryKeyNames .map { getValue(from: element, by: path + [$0]) } .compactMap { $0 } .map { String(describing: $0) } - return DataStoreListDecoder.lazyInit(associatedIds: primaryKeyValues, - associatedWith: associatedFieldNames) + return DataStoreListDecoder.lazyInit( + associatedIds: primaryKeyValues, + associatedWith: associatedFieldNames + ) } } @@ -231,7 +244,7 @@ extension Statement: StatementModelConvertible { } } -private extension Dictionary where Key == String, Value == Any? { +private extension [String: Any?] { /// Utility to create a `NSMutableDictionary` from a Swift `Dictionary`. func mutableCopy() -> NSMutableDictionary { @@ -325,8 +338,8 @@ extension String { } } -extension Array where Element == String { +extension [String] { var fieldPath: String { - self.filter { !$0.isEmpty }.joined(separator: ".") + filter { !$0.isEmpty }.joined(separator: ".") } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+SQLite.swift index d01c94bacb..ab088b52c4 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+SQLite.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Foundation import SQLite -import AWSPluginsCore // swiftlint:disable type_body_length file_length /// [SQLite](https://sqlite.org) `StorageEngineAdapter` implementation. This class provides @@ -27,9 +27,11 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { // our system and find an optimal value. static var maxNumberOfPredicates: Int = 950 - convenience init(version: String, - databaseName: String = "database", - userDefaults: UserDefaults = UserDefaults.standard) throws { + convenience init( + version: String, + databaseName: String = "database", + userDefaults: UserDefaults = UserDefaults.standard + ) throws { var dbFilePath = SQLiteStorageEngineAdapter.getDbFilePath(databaseName: databaseName) _ = try SQLiteStorageEngineAdapter.clearIfNewVersion(version: version, dbFilePath: dbFilePath) @@ -46,17 +48,21 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { throw DataStoreError.invalidDatabase(path: path, error) } - try self.init(connection: connection, - dbFilePath: dbFilePath, - userDefaults: userDefaults, - version: version) + try self.init( + connection: connection, + dbFilePath: dbFilePath, + userDefaults: userDefaults, + version: version + ) } - internal init(connection: Connection, - dbFilePath: URL? = nil, - userDefaults: UserDefaults = UserDefaults.standard, - version: String = "version") throws { + init( + connection: Connection, + dbFilePath: URL? = nil, + userDefaults: UserDefaults = UserDefaults.standard, + version: String = "version" + ) throws { self.connection = connection self.dbFilePath = dbFilePath try SQLiteStorageEngineAdapter.initializeDatabase(connection: connection) @@ -89,7 +95,7 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } func setUp(modelSchemas: [ModelSchema]) throws { - guard let connection = connection else { + guard let connection else { throw DataStoreError.invalidOperation(causedBy: nil) } @@ -117,13 +123,16 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { func applyModelMigrations(modelSchemas: [ModelSchema]) throws { let delegate = SQLiteMutationSyncMetadataMigrationDelegate( storageAdapter: self, - modelSchemas: modelSchemas) + modelSchemas: modelSchemas + ) let mutationSyncMetadataMigration = MutationSyncMetadataMigration(delegate: delegate) let modelSyncMetadataMigration = ModelSyncMetadataMigration(storageAdapter: self) - let modelMigrations = ModelMigrations(modelMigrations: [mutationSyncMetadataMigration, - modelSyncMetadataMigration]) + let modelMigrations = ModelMigrations(modelMigrations: [ + mutationSyncMetadataMigration, + modelSyncMetadataMigration + ]) do { try modelMigrations.apply() } catch { @@ -132,33 +141,43 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } // MARK: - Save - func save(_ model: M, - condition: QueryPredicate? = nil, - eagerLoad: Bool = true, - completion: @escaping DataStoreCallback) { - save(model, - modelSchema: model.schema, - condition: condition, - eagerLoad: eagerLoad, - completion: completion) + func save( + _ model: M, + condition: QueryPredicate? = nil, + eagerLoad: Bool = true, + completion: @escaping DataStoreCallback + ) { + save( + model, + modelSchema: model.schema, + condition: condition, + eagerLoad: eagerLoad, + completion: completion + ) } - func save(_ model: M, - modelSchema: ModelSchema, - condition: QueryPredicate? = nil, - eagerLoad: Bool = true, - completion: DataStoreCallback) { - completion(save(model, - modelSchema: modelSchema, - condition: condition, - eagerLoad: eagerLoad)) + func save( + _ model: M, + modelSchema: ModelSchema, + condition: QueryPredicate? = nil, + eagerLoad: Bool = true, + completion: DataStoreCallback + ) { + completion(save( + model, + modelSchema: modelSchema, + condition: condition, + eagerLoad: eagerLoad + )) } - func save(_ model: M, - modelSchema: ModelSchema, - condition: QueryPredicate? = nil, - eagerLoad: Bool = true) -> DataStoreResult { - guard let connection = connection else { + func save( + _ model: M, + modelSchema: ModelSchema, + condition: QueryPredicate? = nil, + eagerLoad: Bool = true + ) -> DataStoreResult { + guard let connection else { return .failure(DataStoreError.nilSQLiteConnection()) } do { @@ -167,10 +186,11 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { let modelExists = try exists(modelSchema, withIdentifier: modelIdentifier) if !modelExists { - if let condition = condition, !condition.isAll { + if let condition, !condition.isAll { let dataStoreError = DataStoreError.invalidCondition( "Cannot apply a condition on model which does not exist.", - "Save the model instance without a condition first.") + "Save the model instance without a condition first." + ) return .failure(causedBy: dataStoreError) } @@ -179,35 +199,45 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } if modelExists { - if let condition = condition, !condition.isAll { - let modelExistsWithCondition = try exists(modelSchema, - withIdentifier: modelIdentifier, - predicate: condition) + if let condition, !condition.isAll { + let modelExistsWithCondition = try exists( + modelSchema, + withIdentifier: modelIdentifier, + predicate: condition + ) if !modelExistsWithCondition { let dataStoreError = DataStoreError.invalidCondition( - "Save failed due to condition did not match existing model instance.", - "The save will continue to fail until the model instance is updated.") + "Save failed due to condition did not match existing model instance.", + "The save will continue to fail until the model instance is updated." + ) return .failure(causedBy: dataStoreError) } } - let statement = UpdateStatement(model: model, - modelSchema: modelSchema, - condition: condition) + let statement = UpdateStatement( + model: model, + modelSchema: modelSchema, + condition: condition + ) _ = try connection.prepare(statement.stringValue).run(statement.variables) } // load the recent saved instance and pass it back to the callback - let queryResult = query(modelType, modelSchema: modelSchema, - predicate: model.identifier(schema: modelSchema).predicate, - eagerLoad: eagerLoad) + let queryResult = query( + modelType, + modelSchema: modelSchema, + predicate: model.identifier(schema: modelSchema).predicate, + eagerLoad: eagerLoad + ) switch queryResult { case .success(let result): if let saved = result.first { return .success(saved) } else { - return .failure(.nonUniqueResult(model: modelType.modelName, - count: result.count)) + return .failure(.nonUniqueResult( + model: modelType.modelName, + count: result.count + )) } case .failure(let error): return .failure(error) @@ -218,11 +248,13 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } // MARK: - Delete - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - filter: QueryPredicate, - completion: (DataStoreResult<[M]>) -> Void) { - guard let connection = connection else { + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + filter: QueryPredicate, + completion: (DataStoreResult<[M]>) -> Void + ) { + guard let connection else { completion(.failure(DataStoreError.nilSQLiteConnection())) return } @@ -235,15 +267,19 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withId id: Model.Identifier, - condition: QueryPredicate? = nil, - completion: (DataStoreResult) -> Void) { - delete(untypedModelType: modelType, - modelSchema: modelSchema, - withId: id, - condition: condition) { result in + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withId id: Model.Identifier, + condition: QueryPredicate? = nil, + completion: (DataStoreResult) -> Void + ) { + delete( + untypedModelType: modelType, + modelSchema: modelSchema, + withId: id, + condition: condition + ) { result in switch result { case .success: completion(.success(nil)) @@ -253,15 +289,19 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) where M: Model { - delete(untypedModelType: modelType, - modelSchema: modelSchema, - withIdentifier: identifier, - condition: condition) { result in + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) where M: Model { + delete( + untypedModelType: modelType, + modelSchema: modelSchema, + withIdentifier: identifier, + condition: condition + ) { result in switch result { case .success: completion(.success(nil)) @@ -271,31 +311,39 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } } - func delete(untypedModelType modelType: Model.Type, - modelSchema: ModelSchema, - withId id: Model.Identifier, - condition: QueryPredicate? = nil, - completion: DataStoreCallback) { - delete(untypedModelType: modelType, - modelSchema: modelSchema, - withIdentifier: DefaultModelIdentifier.makeDefault(id: id), - condition: condition, - completion: completion) + func delete( + untypedModelType modelType: Model.Type, + modelSchema: ModelSchema, + withId id: Model.Identifier, + condition: QueryPredicate? = nil, + completion: DataStoreCallback + ) { + delete( + untypedModelType: modelType, + modelSchema: modelSchema, + withIdentifier: DefaultModelIdentifier.makeDefault(id: id), + condition: condition, + completion: completion + ) } - func delete(untypedModelType modelType: Model.Type, - modelSchema: ModelSchema, - withIdentifier id: ModelIdentifierProtocol, - condition: QueryPredicate? = nil, - completion: DataStoreCallback) { - guard let connection = connection else { + func delete( + untypedModelType modelType: Model.Type, + modelSchema: ModelSchema, + withIdentifier id: ModelIdentifierProtocol, + condition: QueryPredicate? = nil, + completion: DataStoreCallback + ) { + guard let connection else { completion(.failure(DataStoreError.nilSQLiteConnection())) return } do { - let statement = DeleteStatement(modelSchema: modelSchema, - withIdentifier: id, - predicate: condition) + let statement = DeleteStatement( + modelSchema: modelSchema, + withIdentifier: id, + predicate: condition + ) _ = try connection.prepare(statement.stringValue).run(statement.variables) completion(.emptyResult) } catch { @@ -304,56 +352,70 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } // MARK: - query - func query(_ modelType: M.Type, - predicate: QueryPredicate? = nil, - sort: [QuerySortDescriptor]? = nil, - paginationInput: QueryPaginationInput? = nil, - eagerLoad: Bool = true, - completion: DataStoreCallback<[M]>) { - query(modelType, - modelSchema: modelType.schema, - predicate: predicate, - sort: sort, - paginationInput: paginationInput, - eagerLoad: eagerLoad, - completion: completion) + func query( + _ modelType: M.Type, + predicate: QueryPredicate? = nil, + sort: [QuerySortDescriptor]? = nil, + paginationInput: QueryPaginationInput? = nil, + eagerLoad: Bool = true, + completion: DataStoreCallback<[M]> + ) { + query( + modelType, + modelSchema: modelType.schema, + predicate: predicate, + sort: sort, + paginationInput: paginationInput, + eagerLoad: eagerLoad, + completion: completion + ) } - func query(_ modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate? = nil, - sort: [QuerySortDescriptor]? = nil, - paginationInput: QueryPaginationInput? = nil, - eagerLoad: Bool = true, - completion: DataStoreCallback<[M]>) { - completion(query(modelType, - modelSchema: modelSchema, - predicate: predicate, - sort: sort, - paginationInput: paginationInput, - eagerLoad: eagerLoad)) + func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate? = nil, + sort: [QuerySortDescriptor]? = nil, + paginationInput: QueryPaginationInput? = nil, + eagerLoad: Bool = true, + completion: DataStoreCallback<[M]> + ) { + completion(query( + modelType, + modelSchema: modelSchema, + predicate: predicate, + sort: sort, + paginationInput: paginationInput, + eagerLoad: eagerLoad + )) } - private func query(_ modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate? = nil, - sort: [QuerySortDescriptor]? = nil, - paginationInput: QueryPaginationInput? = nil, - eagerLoad: Bool = true) -> DataStoreResult<[M]> { - guard let connection = connection else { + private func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate? = nil, + sort: [QuerySortDescriptor]? = nil, + paginationInput: QueryPaginationInput? = nil, + eagerLoad: Bool = true + ) -> DataStoreResult<[M]> { + guard let connection else { return .failure(DataStoreError.nilSQLiteConnection()) } do { - let statement = SelectStatement(from: modelSchema, - predicate: predicate, - sort: sort, - paginationInput: paginationInput, - eagerLoad: eagerLoad) + let statement = SelectStatement( + from: modelSchema, + predicate: predicate, + sort: sort, + paginationInput: paginationInput, + eagerLoad: eagerLoad + ) let rows = try connection.prepare(statement.stringValue).run(statement.variables) - let result: [M] = try rows.convert(to: modelType, - withSchema: modelSchema, - using: statement, - eagerLoad: eagerLoad) + let result: [M] = try rows.convert( + to: modelType, + withSchema: modelSchema, + using: statement, + eagerLoad: eagerLoad + ) return .success(result) } catch { return .failure(causedBy: error) @@ -361,24 +423,30 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } // MARK: - Exists - func exists(_ modelSchema: ModelSchema, - withId id: String, - predicate: QueryPredicate? = nil) throws -> Bool { - try exists(modelSchema, - withIdentifier: DefaultModelIdentifier.makeDefault(id: id), - predicate: predicate) + func exists( + _ modelSchema: ModelSchema, + withId id: String, + predicate: QueryPredicate? = nil + ) throws -> Bool { + try exists( + modelSchema, + withIdentifier: DefaultModelIdentifier.makeDefault(id: id), + predicate: predicate + ) } - func exists(_ modelSchema: ModelSchema, - withIdentifier id: ModelIdentifierProtocol, - predicate: QueryPredicate? = nil) throws -> Bool { - guard let connection = connection else { + func exists( + _ modelSchema: ModelSchema, + withIdentifier id: ModelIdentifierProtocol, + predicate: QueryPredicate? = nil + ) throws -> Bool { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } let primaryKey = modelSchema.primaryKey.sqlName.quoted() var sql = "select count(\(primaryKey)) from \"\(modelSchema.name)\" where \(primaryKey) = ?" var variables: [Binding?] = [id.stringValue] - if let predicate = predicate { + if let predicate { let conditionStatement = ConditionStatement(modelSchema: modelSchema, predicate: predicate) sql = """ \(sql) @@ -405,7 +473,7 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } func queryMutationSync(for models: [Model], modelName: String) throws -> [MutationSync] { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } @@ -422,15 +490,19 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { // group models by id for fast access when creating the tuple let modelById = Dictionary(grouping: models, by: { - return MutationSyncMetadata.identifier(modelName: modelName, - modelId: $0.identifier(schema: modelSchema).stringValue) + return MutationSyncMetadata.identifier( + modelName: modelName, + modelId: $0.identifier(schema: modelSchema).stringValue + ) }).mapValues { $0.first! } let ids = [String](modelById.keys) let rows = try connection.prepare(sql).bind(ids) - let syncMetadataList = try rows.convert(to: MutationSyncMetadata.self, - withSchema: MutationSyncMetadata.schema, - using: statement) + let syncMetadataList = try rows.convert( + to: MutationSyncMetadata.self, + withSchema: MutationSyncMetadata.schema, + using: statement + ) let mutationSyncList = try syncMetadataList.map { syncMetadata -> MutationSync in guard let model = modelById[syncMetadata.id] else { throw DataStoreError.invalidOperation(causedBy: nil) @@ -446,9 +518,11 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { return try results.unique() } - func queryMutationSyncMetadata(for modelIds: [String], - modelName: String) throws -> [MutationSyncMetadata] { - guard let connection = connection else { + func queryMutationSyncMetadata( + for modelIds: [String], + modelName: String + ) throws -> [MutationSyncMetadata] { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } let modelType = MutationSyncMetadata.self @@ -459,37 +533,47 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { for chunkedModelIds in chunkedModelIdsArr { var queryPredicates: [QueryPredicateOperation] = [] for id in chunkedModelIds { - let mutationSyncMetadataId = MutationSyncMetadata.identifier(modelName: modelName, - modelId: id) - queryPredicates.append(QueryPredicateOperation(field: fields.id.stringValue, - operator: .equals(mutationSyncMetadataId))) + let mutationSyncMetadataId = MutationSyncMetadata.identifier( + modelName: modelName, + modelId: id + ) + queryPredicates.append(QueryPredicateOperation( + field: fields.id.stringValue, + operator: .equals(mutationSyncMetadataId) + )) } let groupedQueryPredicates = QueryPredicateGroup(type: .or, predicates: queryPredicates) let statement = SelectStatement(from: modelSchema, predicate: groupedQueryPredicates) let rows = try connection.prepare(statement.stringValue).run(statement.variables) - let result = try rows.convert(to: modelType, - withSchema: modelSchema, - using: statement) + let result = try rows.convert( + to: modelType, + withSchema: modelSchema, + using: statement + ) results.append(contentsOf: result) } return results } func queryModelSyncMetadata(for modelSchema: ModelSchema) throws -> ModelSyncMetadata? { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } - let statement = SelectStatement(from: ModelSyncMetadata.schema, - predicate: field("id").eq(modelSchema.name)) + let statement = SelectStatement( + from: ModelSyncMetadata.schema, + predicate: field("id").eq(modelSchema.name) + ) let rows = try connection.prepare(statement.stringValue).run(statement.variables) - let result = try rows.convert(to: ModelSyncMetadata.self, - withSchema: ModelSyncMetadata.schema, - using: statement) + let result = try rows.convert( + to: ModelSyncMetadata.self, + withSchema: ModelSyncMetadata.schema, + using: statement + ) return try result.unique() } func transaction(_ transactionBlock: BasicThrowableClosure) throws { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } try connection.transaction { @@ -498,7 +582,7 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } func clear(completion: @escaping DataStoreCallback) { - guard let dbFilePath = dbFilePath else { + guard let dbFilePath else { log.error("Attempt to clear DB, but file path was empty") completion(.failure(causedBy: DataStoreError.invalidDatabase(path: "Database path not set", nil))) return @@ -523,10 +607,12 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { return false } - static func clearIfNewVersion(version: String, - dbFilePath: URL, - userDefaults: UserDefaults = UserDefaults.standard, - fileManager: FileManager = FileManager.default) throws -> Bool { + static func clearIfNewVersion( + version: String, + dbFilePath: URL, + userDefaults: UserDefaults = UserDefaults.standard, + fileManager: FileManager = FileManager.default + ) throws -> Bool { guard let previousVersion = userDefaults.string(forKey: dbVersionKey) else { return false @@ -569,11 +655,14 @@ private func getDocumentPath() -> URL? { extension DataStoreError { static func nilSQLiteConnection() -> DataStoreError { - .internalOperation("SQLite connection is `nil`", + .internalOperation( + "SQLite connection is `nil`", """ This is expected if DataStore.clear is called while syncing as the SQLite connection is closed. Call DataStore.start to restart the sync process. - """, nil) + """, + nil + ) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+UntypedModel.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+UntypedModel.swift index 212840733f..7acc4e2ae8 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+UntypedModel.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+UntypedModel.swift @@ -10,21 +10,22 @@ import SQLite extension SQLiteStorageEngineAdapter { - func save(untypedModel: Model, - eagerLoad: Bool = true, - completion: DataStoreCallback) { - guard let connection = connection else { + func save( + untypedModel: Model, + eagerLoad: Bool = true, + completion: DataStoreCallback + ) { + guard let connection else { completion(.failure(.nilSQLiteConnection())) return } do { - let modelName: ModelName - if let jsonModel = untypedModel as? JSONValueHolder, + let modelName: ModelName = if let jsonModel = untypedModel as? JSONValueHolder, let modelNameFromJson = jsonModel.jsonValue(for: "__typename") as? String { - modelName = modelNameFromJson + modelNameFromJson } else { - modelName = untypedModel.modelName + untypedModel.modelName } guard let modelSchema = ModelRegistry.modelSchema(from: modelName) else { @@ -32,8 +33,10 @@ extension SQLiteStorageEngineAdapter { throw error } - let shouldUpdate = try exists(modelSchema, - withIdentifier: untypedModel.identifier(schema: modelSchema)) + let shouldUpdate = try exists( + modelSchema, + withIdentifier: untypedModel.identifier(schema: modelSchema) + ) if shouldUpdate { let statement = UpdateStatement(model: untypedModel, modelSchema: modelSchema) @@ -43,16 +46,20 @@ extension SQLiteStorageEngineAdapter { _ = try connection.prepare(statement.stringValue).run(statement.variables) } - query(modelSchema: modelSchema, - predicate: untypedModel.identifier(schema: modelSchema).predicate, - eagerLoad: eagerLoad) { + query( + modelSchema: modelSchema, + predicate: untypedModel.identifier(schema: modelSchema).predicate, + eagerLoad: eagerLoad + ) { switch $0 { case .success(let result): if let saved = result.first { completion(.success(saved)) } else { - completion(.failure(.nonUniqueResult(model: modelSchema.name, - count: result.count))) + completion(.failure(.nonUniqueResult( + model: modelSchema.name, + count: result.count + ))) } case .failure(let error): completion(.failure(error)) @@ -64,22 +71,28 @@ extension SQLiteStorageEngineAdapter { } } - func query(modelSchema: ModelSchema, - predicate: QueryPredicate? = nil, - eagerLoad: Bool = true, - completion: DataStoreCallback<[Model]>) { - guard let connection = connection else { + func query( + modelSchema: ModelSchema, + predicate: QueryPredicate? = nil, + eagerLoad: Bool = true, + completion: DataStoreCallback<[Model]> + ) { + guard let connection else { completion(.failure(.nilSQLiteConnection())) return } do { - let statement = SelectStatement(from: modelSchema, - predicate: predicate, - eagerLoad: eagerLoad) + let statement = SelectStatement( + from: modelSchema, + predicate: predicate, + eagerLoad: eagerLoad + ) let rows = try connection.prepare(statement.stringValue).run(statement.variables) - let result: [Model] = try rows.convertToUntypedModel(using: modelSchema, - statement: statement, - eagerLoad: eagerLoad) + let result: [Model] = try rows.convertToUntypedModel( + using: modelSchema, + statement: statement, + eagerLoad: eagerLoad + ) completion(.success(result)) } catch { completion(.failure(causedBy: error)) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineMigrationAdapter+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineMigrationAdapter+SQLite.swift index 42370a1be2..a1ecd849ea 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineMigrationAdapter+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineMigrationAdapter+SQLite.swift @@ -12,7 +12,7 @@ import SQLite extension SQLiteStorageEngineAdapter { @discardableResult func createStore(for modelSchema: ModelSchema) throws -> String { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } let createTableStatement = CreateTableStatement(modelSchema: modelSchema).stringValue @@ -23,7 +23,7 @@ extension SQLiteStorageEngineAdapter { } @discardableResult func removeStore(for modelSchema: ModelSchema) throws -> String { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } let dropStatement = DropTableStatement(modelSchema: modelSchema).stringValue @@ -32,7 +32,7 @@ extension SQLiteStorageEngineAdapter { } @discardableResult func emptyStore(for modelSchema: ModelSchema) throws -> String { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } let deleteStatement = DeleteStatement(modelSchema: modelSchema).stringValue @@ -41,7 +41,7 @@ extension SQLiteStorageEngineAdapter { } @discardableResult func renameStore(from: ModelSchema, toModelSchema: ModelSchema) throws -> String { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } let alterTableStatement = AlterTableStatement(from: from, toModelSchema: toModelSchema).stringValue diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine+SyncRequirement.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine+SyncRequirement.swift index b6a8aac20c..3f137c0d0d 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine+SyncRequirement.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine+SyncRequirement.swift @@ -6,16 +6,16 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore extension StorageEngine { func startSync() -> Result { let (result, syncEngine) = initalizeSyncEngine() - if let syncEngine = syncEngine, !syncEngine.isSyncing() { + if let syncEngine, !syncEngine.isSyncing() { guard let api = tryGetAPIPlugin() else { log.info("Unable to find suitable API plugin for syncEngine. syncEngine will not be started") return .failure(.configuration( @@ -59,16 +59,16 @@ extension StorageEngine { } private func initalizeSyncEngine() -> (SyncEngineInitResult, RemoteSyncEngineBehavior?) { - if let syncEngine = syncEngine { + if let syncEngine { return (.alreadyInitialized, syncEngine) } else { if isSyncEnabled, syncEngine == nil { - self.syncEngine = try? RemoteSyncEngine( + syncEngine = try? RemoteSyncEngine( storageAdapter: storageAdapter, dataStoreConfiguration: dataStoreConfiguration ) - self.syncEngineSink = syncEngine?.publisher.sink( + syncEngineSink = syncEngine?.publisher.sink( receiveCompletion: onReceiveCompletion(receiveCompletion:), receiveValue: onReceive(receiveValue:) ) @@ -107,9 +107,11 @@ extension StorageEngine { guard schema.isSyncable else { return false } - return requiresAuthPlugin(apiPlugin, - authRules: schema.authRules, - authModeStrategy: authModeStrategy) + return requiresAuthPlugin( + apiPlugin, + authRules: schema.authRules, + authModeStrategy: authModeStrategy + ) } return modelsRequireAuthPlugin @@ -175,7 +177,7 @@ extension StorageEngine { } } -internal extension AuthRules { +extension AuthRules { /// Convenience method to check whether we need Auth plugin /// - Returns: true If **any** of the rules uses a provider that requires the Auth plugin, `nil` otherwise var requireAuthPlugin: Bool? { @@ -191,9 +193,9 @@ internal extension AuthRules { } } -internal extension AuthRule { +extension AuthRule { var requiresAuthPlugin: Bool? { - guard let provider = self.provider else { + guard let provider else { return nil } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine.swift index 53c213e4fb..9ba91c2bec 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine.swift @@ -6,17 +6,19 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore typealias StorageEngineBehaviorFactory = - (Bool, - DataStoreConfiguration, - String, - String, - String, - UserDefaults) throws -> StorageEngineBehavior + ( + Bool, + DataStoreConfiguration, + String, + String, + String, + UserDefaults + ) throws -> StorageEngineBehavior // swiftlint:disable type_body_length final class StorageEngine: StorageEngineBehavior { @@ -72,12 +74,13 @@ final class StorageEngine: StorageEngineBehavior { // Internal initializer used for testing, to allow lazy initialization of the SyncEngine. Note that the provided // storageAdapter must have already been set up with system models - init(storageAdapter: StorageEngineAdapter, - dataStoreConfiguration: DataStoreConfiguration, - syncEngine: RemoteSyncEngineBehavior?, - validAPIPluginKey: String, - validAuthPluginKey: String, - isSyncEnabled: Bool = false + init( + storageAdapter: StorageEngineAdapter, + dataStoreConfiguration: DataStoreConfiguration, + syncEngine: RemoteSyncEngineBehavior?, + validAPIPluginKey: String, + validAuthPluginKey: String, + isSyncEnabled: Bool = false ) { self.storageAdapter = storageAdapter self.dataStoreConfiguration = dataStoreConfiguration @@ -91,12 +94,14 @@ final class StorageEngine: StorageEngineBehavior { self.operationQueue = operationQueue } - convenience init(isSyncEnabled: Bool, - dataStoreConfiguration: DataStoreConfiguration, - validAPIPluginKey: String = "awsAPIPlugin", - validAuthPluginKey: String = "awsCognitoAuthPlugin", - modelRegistryVersion: String, - userDefault: UserDefaults = UserDefaults.standard) throws { + convenience init( + isSyncEnabled: Bool, + dataStoreConfiguration: DataStoreConfiguration, + validAPIPluginKey: String = "awsAPIPlugin", + validAuthPluginKey: String = "awsCognitoAuthPlugin", + modelRegistryVersion: String, + userDefault: UserDefaults = UserDefaults.standard + ) throws { let key = kCFBundleNameKey as String let databaseName = Bundle.main.object(forInfoDictionaryKey: key) as? String ?? "app" @@ -179,19 +184,23 @@ final class StorageEngine: StorageEngineBehavior { try storageAdapter.applyModelMigrations(modelSchemas: modelSchemas) } - public func save(_ model: M, - modelSchema: ModelSchema, - condition: QueryPredicate? = nil, - eagerLoad: Bool = true, - completion: @escaping DataStoreCallback) { + public func save( + _ model: M, + modelSchema: ModelSchema, + condition: QueryPredicate? = nil, + eagerLoad: Bool = true, + completion: @escaping DataStoreCallback + ) { // TODO: Refactor this into a proper request/result where the result includes metadata like the derived // mutation type let modelExists: Bool do { - modelExists = try storageAdapter.exists(modelSchema, - withIdentifier: model.identifier(schema: modelSchema), - predicate: nil) + modelExists = try storageAdapter.exists( + modelSchema, + withIdentifier: model.identifier(schema: modelSchema), + predicate: nil + ) } catch { let dataStoreError = DataStoreError.invalidOperation(causedBy: error) completion(.failure(dataStoreError)) @@ -201,20 +210,23 @@ final class StorageEngine: StorageEngineBehavior { let mutationType = modelExists ? MutationEvent.MutationType.update : .create // If it is `create`, and there is a condition, and that condition is not `.all`, fail the request - if mutationType == .create, let condition = condition, !condition.isAll { + if mutationType == .create, let condition, !condition.isAll { let dataStoreError = DataStoreError.invalidCondition( "Cannot apply a condition on model which does not exist.", - "Save the model instance without a condition first.") + "Save the model instance without a condition first." + ) completion(.failure(causedBy: dataStoreError)) return } do { try storageAdapter.transaction { - let result = self.storageAdapter.save(model, - modelSchema: modelSchema, - condition: condition, - eagerLoad: eagerLoad) + let result = self.storageAdapter.save( + model, + modelSchema: modelSchema, + condition: condition, + eagerLoad: eagerLoad + ) guard modelSchema.isSyncable else { completion(result) return @@ -231,105 +243,134 @@ final class StorageEngine: StorageEngineBehavior { throw DataStoreError.internalOperation( message, "`DataStore.save()` was interrupted. `DataStore.stop()` may have been called.", - nil) + nil + ) } self.log.verbose("\(#function) syncing mutation for \(savedModel)") - self.syncMutation(of: savedModel, - modelSchema: modelSchema, - mutationType: mutationType, - predicate: condition, - syncEngine: syncEngine, - completion: completion) + self.syncMutation( + of: savedModel, + modelSchema: modelSchema, + mutationType: mutationType, + predicate: condition, + syncEngine: syncEngine, + completion: completion + ) } } catch { completion(.failure(causedBy: error)) } } - func save(_ model: M, - condition: QueryPredicate? = nil, - eagerLoad: Bool = true, - completion: @escaping DataStoreCallback) { - save(model, - modelSchema: model.schema, - condition: condition, - eagerLoad: eagerLoad, - completion: completion) + func save( + _ model: M, + condition: QueryPredicate? = nil, + eagerLoad: Bool = true, + completion: @escaping DataStoreCallback + ) { + save( + model, + modelSchema: model.schema, + condition: condition, + eagerLoad: eagerLoad, + completion: completion + ) } @available(*, deprecated, message: "Use delete(:modelSchema:withIdentifier:predicate:completion") - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withId id: Model.Identifier, - condition: QueryPredicate? = nil, - completion: @escaping (DataStoreResult) -> Void) { - let cascadeDeleteOperation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: modelType, modelSchema: modelSchema, - withIdentifier: DefaultModelIdentifier.makeDefault(id: id), - condition: condition) { completion($0) } + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withId id: Model.Identifier, + condition: QueryPredicate? = nil, + completion: @escaping (DataStoreResult) -> Void + ) { + let cascadeDeleteOperation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: modelType, + modelSchema: modelSchema, + withIdentifier: DefaultModelIdentifier.makeDefault(id: id), + condition: condition + ) { completion($0) } operationQueue.addOperation(cascadeDeleteOperation) } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) { - let cascadeDeleteOperation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: modelType, modelSchema: modelSchema, - withIdentifier: identifier, - condition: condition) { completion($0) } + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) { + let cascadeDeleteOperation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: modelType, + modelSchema: modelSchema, + withIdentifier: identifier, + condition: condition + ) { completion($0) } operationQueue.addOperation(cascadeDeleteOperation) } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - filter: QueryPredicate, - completion: @escaping DataStoreCallback<[M]>) { - let cascadeDeleteOperation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: modelType, - modelSchema: modelSchema, - filter: filter) { completion($0) } + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + filter: QueryPredicate, + completion: @escaping DataStoreCallback<[M]> + ) { + let cascadeDeleteOperation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: modelType, + modelSchema: modelSchema, + filter: filter + ) { completion($0) } operationQueue.addOperation(cascadeDeleteOperation) } - func query(_ modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool = true, - completion: (DataStoreResult<[M]>) -> Void) { - return storageAdapter.query(modelType, - modelSchema: modelSchema, - predicate: predicate, - sort: sort, - paginationInput: paginationInput, - eagerLoad: eagerLoad, - completion: completion) + func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool = true, + completion: (DataStoreResult<[M]>) -> Void + ) { + return storageAdapter.query( + modelType, + modelSchema: modelSchema, + predicate: predicate, + sort: sort, + paginationInput: paginationInput, + eagerLoad: eagerLoad, + completion: completion + ) } - func query(_ modelType: M.Type, - predicate: QueryPredicate? = nil, - sort: [QuerySortDescriptor]? = nil, - paginationInput: QueryPaginationInput? = nil, - eagerLoad: Bool = true, - completion: DataStoreCallback<[M]>) { - query(modelType, - modelSchema: modelType.schema, - predicate: predicate, - sort: sort, - paginationInput: paginationInput, - eagerLoad: eagerLoad, - completion: completion) + func query( + _ modelType: M.Type, + predicate: QueryPredicate? = nil, + sort: [QuerySortDescriptor]? = nil, + paginationInput: QueryPaginationInput? = nil, + eagerLoad: Bool = true, + completion: DataStoreCallback<[M]> + ) { + query( + modelType, + modelSchema: modelType.schema, + predicate: predicate, + sort: sort, + paginationInput: paginationInput, + eagerLoad: eagerLoad, + completion: completion + ) } func clear(completion: @escaping DataStoreCallback) { - if let syncEngine = syncEngine { + if let syncEngine { syncEngine.stop(completion: { _ in self.syncEngine = nil self.storageAdapter.clear(completion: completion) @@ -340,7 +381,7 @@ final class StorageEngine: StorageEngineBehavior { } func stopSync(completion: @escaping DataStoreCallback) { - if let syncEngine = syncEngine { + if let syncEngine { syncEngine.stop { _ in self.syncEngine = nil completion(.successfulVoid) @@ -351,24 +392,30 @@ final class StorageEngine: StorageEngineBehavior { } @available(iOS 13.0, *) - private func syncMutation(of savedModel: M, - modelSchema: ModelSchema, - mutationType: MutationEvent.MutationType, - predicate: QueryPredicate? = nil, - syncEngine: RemoteSyncEngineBehavior, - completion: @escaping DataStoreCallback) { + private func syncMutation( + of savedModel: M, + modelSchema: ModelSchema, + mutationType: MutationEvent.MutationType, + predicate: QueryPredicate? = nil, + syncEngine: RemoteSyncEngineBehavior, + completion: @escaping DataStoreCallback + ) { let mutationEvent: MutationEvent do { var graphQLFilterJSON: String? - if let predicate = predicate { - graphQLFilterJSON = try GraphQLFilterConverter.toJSON(predicate, - modelSchema: modelSchema) + if let predicate { + graphQLFilterJSON = try GraphQLFilterConverter.toJSON( + predicate, + modelSchema: modelSchema + ) } - mutationEvent = try MutationEvent(model: savedModel, - modelSchema: modelSchema, - mutationType: mutationType, - graphQLFilterJSON: graphQLFilterJSON) + mutationEvent = try MutationEvent( + model: savedModel, + modelSchema: modelSchema, + mutationType: mutationType, + graphQLFilterJSON: graphQLFilterJSON + ) } catch { let dataStoreError = DataStoreError(error: error) @@ -386,14 +433,18 @@ final class StorageEngine: StorageEngineBehavior { } } - submitToSyncEngine(mutationEvent: mutationEvent, - syncEngine: syncEngine, - completion: mutationEventCallback) + submitToSyncEngine( + mutationEvent: mutationEvent, + syncEngine: syncEngine, + completion: mutationEventCallback + ) } - private func submitToSyncEngine(mutationEvent: MutationEvent, - syncEngine: RemoteSyncEngineBehavior, - completion: @escaping DataStoreCallback) { + private func submitToSyncEngine( + mutationEvent: MutationEvent, + syncEngine: RemoteSyncEngineBehavior, + completion: @escaping DataStoreCallback + ) { Task { syncEngine.submit(mutationEvent, completion: completion) } @@ -407,7 +458,7 @@ extension StorageEngine: Resettable { if let resettable = syncEngine as? Resettable { log.verbose("Resetting syncEngine") await resettable.reset() - self.log.verbose("Resetting syncEngine: finished") + log.verbose("Resetting syncEngine: finished") } } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineAdapter.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineAdapter.swift index 191df26ebc..448020b80f 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineAdapter.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineAdapter.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSPluginsCore +import Foundation protocol StorageEngineAdapter: AnyObject, ModelStorageBehavior, ModelStorageErrorBehavior, StorageEngineMigrationAdapter { @@ -16,32 +16,42 @@ protocol StorageEngineAdapter: AnyObject, ModelStorageBehavior, ModelStorageErro // MARK: - Async APIs func save(untypedModel: Model, eagerLoad: Bool, completion: @escaping DataStoreCallback) - func delete(untypedModelType modelType: Model.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, - completion: DataStoreCallback) - - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - filter: QueryPredicate, - completion: @escaping DataStoreCallback<[M]>) - - func query(modelSchema: ModelSchema, - predicate: QueryPredicate?, - eagerLoad: Bool, - completion: DataStoreCallback<[Model]>) + func delete( + untypedModelType modelType: Model.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: DataStoreCallback + ) + + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + filter: QueryPredicate, + completion: @escaping DataStoreCallback<[M]> + ) + + func query( + modelSchema: ModelSchema, + predicate: QueryPredicate?, + eagerLoad: Bool, + completion: DataStoreCallback<[Model]> + ) // MARK: - Synchronous APIs - func save(_ model: M, - modelSchema: ModelSchema, - condition: QueryPredicate?, - eagerLoad: Bool) -> DataStoreResult + func save( + _ model: M, + modelSchema: ModelSchema, + condition: QueryPredicate?, + eagerLoad: Bool + ) -> DataStoreResult - func exists(_ modelSchema: ModelSchema, - withIdentifier id: ModelIdentifierProtocol, - predicate: QueryPredicate?) throws -> Bool + func exists( + _ modelSchema: ModelSchema, + withIdentifier id: ModelIdentifierProtocol, + predicate: QueryPredicate? + ) throws -> Bool func queryMutationSync(for models: [Model], modelName: String) throws -> [MutationSync] @@ -71,20 +81,26 @@ protocol StorageEngineMigrationAdapter { extension StorageEngineAdapter { - func delete(_ modelType: M.Type, - filter predicate: QueryPredicate, - completion: @escaping DataStoreCallback<[M]>) { + func delete( + _ modelType: M.Type, + filter predicate: QueryPredicate, + completion: @escaping DataStoreCallback<[M]> + ) { delete(modelType, modelSchema: modelType.schema, filter: predicate, completion: completion) } - func delete(untypedModelType modelType: Model.Type, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate? = nil, - completion: DataStoreCallback) { - delete(untypedModelType: modelType, - modelSchema: modelType.schema, - withIdentifier: identifier, - condition: condition, - completion: completion) + func delete( + untypedModelType modelType: Model.Type, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate? = nil, + completion: DataStoreCallback + ) { + delete( + untypedModelType: modelType, + modelSchema: modelType.schema, + withIdentifier: identifier, + condition: condition, + completion: completion + ) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineBehavior.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineBehavior.swift index 43c8878703..9e02fe9fbb 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineBehavior.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineBehavior.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import Combine +import Foundation enum StorageEngineEvent { case started diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStoreObserveQueryOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStoreObserveQueryOperation.swift index 6e6781716a..1c1d0ed003 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStoreObserveQueryOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStoreObserveQueryOperation.swift @@ -45,8 +45,10 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr var request: ObserveQueryRequest var context = InternalTaskAsyncThrowingSequenceContext>() - private let serialQueue = DispatchQueue(label: "com.amazonaws.AWSDataStoreObseverQueryOperation.serialQueue", - target: DispatchQueue.global()) + private let serialQueue = DispatchQueue( + label: "com.amazonaws.AWSDataStoreObseverQueryOperation.serialQueue", + target: DispatchQueue.global() + ) private let itemsChangedPeriodicPublishTimeInSeconds: DispatchQueue.SchedulerTimeType.Stride = 2 let modelType: M.Type @@ -74,17 +76,19 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr var dataStoreStatePublisher: AnyPublisher var dataStoreStateSink: AnyCancellable? - init(request: ObserveQueryRequest = .init(options: []), - context: InternalTaskAsyncThrowingSequenceContext> = InternalTaskAsyncThrowingSequenceContext>(), - modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate?, - sortInput: [QuerySortDescriptor]?, - storageEngine: StorageEngineBehavior, - dataStorePublisher: ModelSubcriptionBehavior, - dataStoreConfiguration: DataStoreConfiguration, - dispatchedModelSyncedEvent: AtomicValue, - dataStoreStatePublisher: AnyPublisher) { + init( + request: ObserveQueryRequest = .init(options: []), + context: InternalTaskAsyncThrowingSequenceContext> = InternalTaskAsyncThrowingSequenceContext>(), + modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate?, + sortInput: [QuerySortDescriptor]?, + storageEngine: StorageEngineBehavior, + dataStorePublisher: ModelSubcriptionBehavior, + dataStoreConfiguration: DataStoreConfiguration, + dispatchedModelSyncedEvent: AtomicValue, + dataStoreStatePublisher: AnyPublisher + ) { self.request = request self.context = context @@ -113,9 +117,9 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr func subscribeToDataStoreState() { serialQueue.async { [weak self] in - guard let self = self else { return } + guard let self else { return } - self.dataStoreStateSink = self.dataStoreStatePublisher.sink { completion in + dataStoreStateSink = dataStoreStatePublisher.sink { completion in switch completion { case .finished: self.finish() @@ -136,15 +140,15 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr public func cancel() { serialQueue.sync { - if let itemsChangedSink = itemsChangedSink { + if let itemsChangedSink { itemsChangedSink.cancel() } - if let batchItemsChangedSink = batchItemsChangedSink { + if let batchItemsChangedSink { batchItemsChangedSink.cancel() } - if let modelSyncedEventSink = modelSyncedEventSink { + if let modelSyncedEventSink { modelSyncedEventSink.cancel() } } @@ -178,7 +182,7 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr self.observeQueryStarted = true } - if let storageEngine = storageEngine { + if let storageEngine { self.storageEngine = storageEngine } self.log.verbose("Start ObserveQuery") @@ -208,7 +212,8 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr fail(error) return } - }) + } + ) } // MARK: Observe item changes @@ -221,36 +226,40 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr /// accessed under the serial queue. func subscribeToItemChanges() { serialQueue.async { [weak self] in - guard let self = self else { return } + guard let self else { return } - self.batchItemsChangedSink = self.dataStorePublisher.publisher + batchItemsChangedSink = dataStorePublisher.publisher .filter { _ in !self.dispatchedModelSyncedEvent.get() } - .filter(self.filterByModelName(mutationEvent:)) - .filter(self.filterByPredicateMatch(mutationEvent:)) - .handleEvents(receiveOutput: self.onItemChangeDuringSync(mutationEvent:) ) + .filter(filterByModelName(mutationEvent:)) + .filter(filterByPredicateMatch(mutationEvent:)) + .handleEvents(receiveOutput: onItemChangeDuringSync(mutationEvent:) ) .collect( .byTimeOrCount( // on queue - self.serialQueue, + serialQueue, // collect over this timeframe - self.itemsChangedPeriodicPublishTimeInSeconds, + itemsChangedPeriodicPublishTimeInSeconds, // If the `storageEngine` does sync from remote, the initial batch should // collect snapshots based on time / snapshots received. // If it doesn't, it should publish each snapshot without waiting. - self.storageEngine.syncsFromRemote - ? self.itemsChangedMaxSize + storageEngine.syncsFromRemote + ? itemsChangedMaxSize : 1 ) ) - .sink(receiveCompletion: self.onReceiveCompletion(completed:), - receiveValue: self.onItemsChangeDuringSync(mutationEvents:)) + .sink( + receiveCompletion: onReceiveCompletion(completed:), + receiveValue: onItemsChangeDuringSync(mutationEvents:) + ) - self.itemsChangedSink = self.dataStorePublisher.publisher + itemsChangedSink = dataStorePublisher.publisher .filter { _ in self.dispatchedModelSyncedEvent.get() } - .filter(self.filterByModelName(mutationEvent:)) - .receive(on: self.serialQueue) - .sink(receiveCompletion: self.onReceiveCompletion(completed:), - receiveValue: self.onItemChangeAfterSync(mutationEvent:)) + .filter(filterByModelName(mutationEvent:)) + .receive(on: serialQueue) + .sink( + receiveCompletion: onReceiveCompletion(completed:), + receiveValue: onItemChangeAfterSync(mutationEvent:) + ) } } @@ -273,7 +282,7 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr func filterByPredicateMatch(mutationEvent: MutationEvent) -> Bool { // Filter in the model when there is no predicate to check against. - guard let predicate = self.predicate else { + guard let predicate else { return true } do { @@ -288,24 +297,24 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr func onItemChangeDuringSync(mutationEvent: MutationEvent) { serialQueue.async { [weak self] in - guard let self = self, self.observeQueryStarted else { + guard let self, observeQueryStarted else { return } - self.apply(itemsChanged: [mutationEvent]) + apply(itemsChanged: [mutationEvent]) } } func onItemsChangeDuringSync(mutationEvents: [MutationEvent]) { serialQueue.async { [weak self] in - guard let self = self, - self.observeQueryStarted, + guard let self, + observeQueryStarted, !mutationEvents.isEmpty, !self.dispatchedModelSyncedEvent.get() else { return } - self.startSnapshotStopWatch() - self.sendSnapshot() + startSnapshotStopWatch() + sendSnapshot() } } @@ -393,12 +402,12 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr private func onReceiveCompletion(completed: Subscribers.Completion) { serialQueue.async { [weak self] in - guard let self = self else { return } + guard let self else { return } switch completed { case .finished: - self.finish() + finish() case .failure(let error): - self.fail(error) + fail(error) } } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/ObserveTaskRunner.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/ObserveTaskRunner.swift index 755a105f91..1cbba21d8d 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/ObserveTaskRunner.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/ObserveTaskRunner.swift @@ -37,7 +37,7 @@ class ObserveTaskRunner: InternalTaskRunner, InternalTaskAsyncThrowingSequence, guard !running else { return } running = true - self.sink = publisher.sink { completion in + sink = publisher.sink { completion in switch completion { case .finished: self.finish() diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/Model+Sort.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/Model+Sort.swift index b9eed6bbd9..054d807eb6 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/Model+Sort.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/Model+Sort.swift @@ -84,9 +84,11 @@ extension ModelSchema { /// - sortBy: The field and direction used to compare the two models /// - Returns: The resulting comparison between the two models based on `sortBy` // swiftlint:disable:next cyclomatic_complexity - func comparator(model1: Model, - model2: Model, - sortBy: QuerySortDescriptor) -> Bool? { + func comparator( + model1: Model, + model2: Model, + sortBy: QuerySortDescriptor + ) -> Bool? { let fieldName = sortBy.fieldName let sortOrder = sortBy.order guard let modelField = field(withName: fieldName) else { @@ -99,19 +101,25 @@ extension ModelSchema { guard let value1Optional = value1 as? String?, let value2Optional = value2 as? String? else { return false } - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) case .int, .timestamp: if let value1Optional = value1 as? Int?, let value2Optional = value2 as? Int? { - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) } if let value1Optional = value1 as? Int64?, let value2Optional = value2 as? Int64? { - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) } @@ -120,44 +128,56 @@ extension ModelSchema { guard let value1Optional = value1 as? Double?, let value2Optional = value2 as? Double? else { return false } - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) case .date: guard let value1Optional = value1 as? Temporal.Date?, let value2Optional = value2 as? Temporal.Date? else { return false } - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) case .dateTime: guard let value1Optional = value1 as? Temporal.DateTime?, let value2Optional = value2 as? Temporal.DateTime? else { return false } - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) case .time: guard let value1Optional = value1 as? Temporal.Time?, let value2Optional = value2 as? Temporal.Time? else { return false } - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) case .bool: guard let value1Optional = value1 as? Bool?, let value2Optional = value2 as? Bool? else { return false } - return ModelValueCompare(value1Optional: value1Optional?.intValue, - value2Optional: value2Optional?.intValue) + return ModelValueCompare( + value1Optional: value1Optional?.intValue, + value2Optional: value2Optional?.intValue + ) .sortComparator(sortOrder: sortOrder) case .enum: + // swiftformat:disable typeSugar // swiftlint:disable syntactic_sugar guard case .some(Optional.some(let value1Optional)) = value1, - case .some(Optional.some(let value2Optional)) = value2 else { + case .some(Optional.some(let value2Optional)) = value2 + else { if value1 == nil && value2 != nil { return sortOrder == .ascending } else if value1 != nil && value2 == nil { @@ -166,10 +186,13 @@ extension ModelSchema { return false } // swiftlint:enable syntactic_sugar + // swiftformat:enable typeSugar let enumValue1Optional = (value1Optional as? EnumPersistable)?.rawValue let enumValue2Optional = (value2Optional as? EnumPersistable)?.rawValue - return ModelValueCompare(value1Optional: enumValue1Optional, - value2Optional: enumValue2Optional) + return ModelValueCompare( + value1Optional: enumValue1Optional, + value2Optional: enumValue2Optional + ) .sortComparator(sortOrder: sortOrder) case .embedded, .embeddedCollection, .model, .collection: // Behavior is undetermined diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/SortedList.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/SortedList.swift index daffa031a9..e0b2c960dc 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/SortedList.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/SortedList.swift @@ -61,7 +61,7 @@ class SortedList { func add(model: ModelType, sortInputs: [QuerySortDescriptor]) { let index = sortedModels.binarySearch { existingModel in var sortOrder: Bool? - var sortIndex: Int = 0 + var sortIndex = 0 while sortOrder == nil && sortIndex < sortInputs.endIndex { let sortInput = sortInputs[sortIndex] // `existingModel` is passed as left argument so the binarySearch's `predicate` criteria is met, ie. diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/ModelSyncedEvent.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/ModelSyncedEvent.swift index 15920e60d8..cbe94edc95 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/ModelSyncedEvent.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/ModelSyncedEvent.swift @@ -22,12 +22,14 @@ public struct ModelSyncedEvent { /// Number of existing model instances deleted from the local store public let deleted: Int - public init(modelName: String, - isFullSync: Bool, - isDeltaSync: Bool, - added: Int, - updated: Int, - deleted: Int) { + public init( + modelName: String, + isFullSync: Bool, + isDeltaSync: Bool, + added: Int, + updated: Int, + deleted: Int + ) { self.modelName = modelName self.isFullSync = isFullSync self.isDeltaSync = isDeltaSync diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/OutboxMutationEvent.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/OutboxMutationEvent.swift index 3fdf36b4d7..fa38a2b84c 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/OutboxMutationEvent.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/OutboxMutationEvent.swift @@ -17,18 +17,24 @@ public struct OutboxMutationEvent { self.modelName = modelName self.element = element } - public static func fromModelWithMetadata(modelName: String, - model: Model, - mutationSync: MutationSync) -> OutboxMutationEvent { - let element = OutboxMutationEventElement(model: model, - version: mutationSync.syncMetadata.version, - lastChangedAt: mutationSync.syncMetadata.lastChangedAt, - deleted: mutationSync.syncMetadata.deleted) + public static func fromModelWithMetadata( + modelName: String, + model: Model, + mutationSync: MutationSync + ) -> OutboxMutationEvent { + let element = OutboxMutationEventElement( + model: model, + version: mutationSync.syncMetadata.version, + lastChangedAt: mutationSync.syncMetadata.lastChangedAt, + deleted: mutationSync.syncMetadata.deleted + ) return OutboxMutationEvent(modelName: modelName, element: element) } - public static func fromModelWithoutMetadata(modelName: String, - model: Model) -> OutboxMutationEvent { + public static func fromModelWithoutMetadata( + modelName: String, + model: Model + ) -> OutboxMutationEvent { let element = OutboxMutationEventElement(model: model) return OutboxMutationEvent(modelName: modelName, element: element) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOperation.swift index b37a860eae..cbff57e91a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOperation.swift @@ -38,7 +38,7 @@ final class InitialSyncOperation: AsynchronousOperation { } private var syncPredicateString: String? { - guard let syncPredicate = syncPredicate, + guard let syncPredicate, let data = try? syncPredicateEncoder.encode(syncPredicate) else { return nil } @@ -61,12 +61,14 @@ final class InitialSyncOperation: AsynchronousOperation { return initialSyncOperationTopic.eraseToAnyPublisher() } - init(modelSchema: ModelSchema, - api: APICategoryGraphQLBehavior?, - reconciliationQueue: IncomingEventReconciliationQueue?, - storageAdapter: StorageEngineAdapter?, - dataStoreConfiguration: DataStoreConfiguration, - authModeStrategy: AuthModeStrategy) { + init( + modelSchema: ModelSchema, + api: APICategoryGraphQLBehavior?, + reconciliationQueue: IncomingEventReconciliationQueue?, + storageAdapter: StorageEngineAdapter?, + dataStoreConfiguration: DataStoreConfiguration, + authModeStrategy: AuthModeStrategy + ) { self.modelSchema = modelSchema self.api = api self.reconciliationQueue = reconciliationQueue @@ -87,7 +89,7 @@ final class InitialSyncOperation: AsynchronousOperation { log.info("Beginning sync for \(modelSchema.name)") let lastSyncMetadata = getLastSyncMetadata() let lastSyncTime = getLastSyncTime(lastSyncMetadata) - self.queryTask = Task { + queryTask = Task { await query(lastSyncTime: lastSyncTime) } } @@ -98,7 +100,7 @@ final class InitialSyncOperation: AsynchronousOperation { return nil } - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.error(error: DataStoreError.nilStorageAdapter()) return nil } @@ -119,7 +121,7 @@ final class InitialSyncOperation: AsynchronousOperation { func getLastSyncTime(_ lastSyncMetadata: ModelSyncMetadata?) -> Int64? { let syncType: SyncType let lastSyncTime: Int64? - if syncPredicateChanged(self.syncPredicateString, lastSyncMetadata?.syncPredicate) { + if syncPredicateChanged(syncPredicateString, lastSyncMetadata?.syncPredicate) { log.info("SyncPredicate for \(modelSchema.name) changed, performing full sync.") lastSyncTime = nil syncType = .fullSync @@ -143,7 +145,7 @@ final class InitialSyncOperation: AsynchronousOperation { } private func getLastSyncTime(lastSync: Int64?) -> Int64? { - guard let lastSync = lastSync else { + guard let lastSync else { return nil } let lastSyncDate = Date(timeIntervalSince1970: TimeInterval.milliseconds(Double(lastSync))) @@ -163,7 +165,7 @@ final class InitialSyncOperation: AsynchronousOperation { return } - guard let api = api else { + guard let api else { finish(result: .failure(DataStoreError.nilAPIHandle())) return } @@ -172,7 +174,7 @@ final class InitialSyncOperation: AsynchronousOperation { let authTypes = await authModeStrategy.authTypesFor(schema: modelSchema, operation: .read) let queryRequestsStream = AsyncStream { continuation in for authType in authTypes { - continuation.yield({ [weak self] in + continuation.yield { [weak self] in guard let self, let api = self.api else { throw APIError.operationError( "The initial synchronization process can no longer be accessed or referred to", @@ -181,14 +183,14 @@ final class InitialSyncOperation: AsynchronousOperation { } return try await api.query(request: GraphQLRequest.syncQuery( - modelSchema: self.modelSchema, - where: self.syncPredicate, + modelSchema: modelSchema, + where: syncPredicate, limit: limit, nextToken: nextToken, lastSync: lastSyncTime, authType: authType.awsAuthType )) - }) + } } continuation.finish() } @@ -196,11 +198,11 @@ final class InitialSyncOperation: AsynchronousOperation { case .success(let graphQLResult): await handleQueryResults(lastSyncTime: lastSyncTime, graphQLResult: graphQLResult) case .failure(let apiError): - if self.isAuthSignedOutError(apiError: apiError) { - self.log.error("Sync for \(self.modelSchema.name) failed due to signed out error \(apiError.errorDescription)") + if isAuthSignedOutError(apiError: apiError) { + log.error("Sync for \(modelSchema.name) failed due to signed out error \(apiError.errorDescription)") } - self.dataStoreConfiguration.errorHandler(DataStoreError.api(apiError)) - self.finish(result: .failure(.api(apiError))) + dataStoreConfiguration.errorHandler(DataStoreError.api(apiError)) + finish(result: .failure(.api(apiError))) } } @@ -215,7 +217,7 @@ final class InitialSyncOperation: AsynchronousOperation { return } - guard let reconciliationQueue = reconciliationQueue else { + guard let reconciliationQueue else { finish(result: .failure(DataStoreError.nilReconciliationQueue())) return } @@ -244,7 +246,7 @@ final class InitialSyncOperation: AsynchronousOperation { } if let nextToken = syncQueryResult.nextToken, recordsReceived < syncMaxRecords { - await self.query(lastSyncTime: lastSyncTime, nextToken: nextToken) + await query(lastSyncTime: lastSyncTime, nextToken: nextToken) } else { updateModelSyncMetadata(lastSyncTime: syncQueryResult.startedAt) } @@ -256,14 +258,16 @@ final class InitialSyncOperation: AsynchronousOperation { return } - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { finish(result: .failure(DataStoreError.nilStorageAdapter())) return } - let syncMetadata = ModelSyncMetadata(id: modelSchema.name, - lastSync: lastSyncTime, - syncPredicate: syncPredicateString) + let syncMetadata = ModelSyncMetadata( + id: modelSchema.name, + lastSync: lastSyncTime, + syncPredicate: syncPredicateString + ) storageAdapter.save(syncMetadata, condition: nil, eagerLoad: true) { result in switch result { case .failure(let dataStoreError): @@ -297,7 +301,7 @@ final class InitialSyncOperation: AsynchronousOperation { } override func cancel() { - self.queryTask?.cancel() + queryTask?.cancel() } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOrchestrator.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOrchestrator.swift index 806b19a240..2e54102e8e 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOrchestrator.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOrchestrator.swift @@ -17,11 +17,13 @@ protocol InitialSyncOrchestrator { // For testing typealias InitialSyncOrchestratorFactory = - (DataStoreConfiguration, - AuthModeStrategy, - APICategoryGraphQLBehavior?, - IncomingEventReconciliationQueue?, - StorageEngineAdapter?) -> InitialSyncOrchestrator + ( + DataStoreConfiguration, + AuthModeStrategy, + APICategoryGraphQLBehavior?, + IncomingEventReconciliationQueue?, + StorageEngineAdapter? + ) -> InitialSyncOrchestrator final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { typealias SyncOperationResult = Result @@ -42,19 +44,23 @@ final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { // Future optimization: can perform sync on each root in parallel, since we know they won't have any // interdependencies let syncOperationQueue: OperationQueue - private let concurrencyQueue = DispatchQueue(label: "com.amazonaws.InitialSyncOrchestrator.concurrencyQueue", - target: DispatchQueue.global()) + private let concurrencyQueue = DispatchQueue( + label: "com.amazonaws.InitialSyncOrchestrator.concurrencyQueue", + target: DispatchQueue.global() + ) private let initialSyncOrchestratorTopic: PassthroughSubject var publisher: AnyPublisher { return initialSyncOrchestratorTopic.eraseToAnyPublisher() } - init(dataStoreConfiguration: DataStoreConfiguration, - authModeStrategy: AuthModeStrategy, - api: APICategoryGraphQLBehavior?, - reconciliationQueue: IncomingEventReconciliationQueue?, - storageAdapter: StorageEngineAdapter?) { + init( + dataStoreConfiguration: DataStoreConfiguration, + authModeStrategy: AuthModeStrategy, + api: APICategoryGraphQLBehavior?, + reconciliationQueue: IncomingEventReconciliationQueue?, + storageAdapter: StorageEngineAdapter? + ) { self.initialSyncOperationSinks = [:] self.dataStoreConfiguration = dataStoreConfiguration self.authModeStrategy = authModeStrategy @@ -81,10 +87,10 @@ final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { self.log.info("Beginning initial sync") - let syncableModelSchemas = ModelRegistry.modelSchemas.filter { $0.isSyncable } + let syncableModelSchemas = ModelRegistry.modelSchemas.filter(\.isSyncable) self.enqueueSyncableModels(syncableModelSchemas) - let modelNames = syncableModelSchemas.map { $0.name } + let modelNames = syncableModelSchemas.map(\.name) self.dispatchSyncQueriesStarted(for: modelNames) if !syncableModelSchemas.hasAssociations() { self.syncOperationQueue.maxConcurrentOperationCount = syncableModelSchemas.count @@ -102,19 +108,25 @@ final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { /// Enqueues sync operations for models and downstream dependencies private func enqueueSyncOperation(for modelSchema: ModelSchema) { - let initialSyncForModel = InitialSyncOperation(modelSchema: modelSchema, - api: api, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter, - dataStoreConfiguration: dataStoreConfiguration, - authModeStrategy: authModeStrategy) + let initialSyncForModel = InitialSyncOperation( + modelSchema: modelSchema, + api: api, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter, + dataStoreConfiguration: dataStoreConfiguration, + authModeStrategy: authModeStrategy + ) initialSyncOperationSinks[modelSchema.name] = initialSyncForModel .publisher .receive(on: concurrencyQueue) - .sink(receiveCompletion: { result in self.onReceiveCompletion(modelSchema: modelSchema, - result: result) }, - receiveValue: onReceiveValue(_:)) + .sink( + receiveCompletion: { result in self.onReceiveCompletion( + modelSchema: modelSchema, + result: result + ) }, + receiveValue: onReceiveValue(_:) + ) syncOperationQueue.addOperation(initialSyncForModel) } @@ -128,8 +140,9 @@ final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { let syncError = DataStoreError.sync( "An error occurred syncing \(modelSchema.name)", "", - dataStoreError) - self.syncErrors.append(syncError) + dataStoreError + ) + syncErrors.append(syncError) } initialSyncOperationSinks.removeValue(forKey: modelSchema.name) @@ -170,8 +183,10 @@ final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { private func dispatchSyncQueriesStarted(for modelNames: [String]) { let syncQueriesStartedEvent = SyncQueriesStartedEvent(models: modelNames) - let syncQueriesStartedEventPayload = HubPayload(eventName: HubPayload.EventName.DataStore.syncQueriesStarted, - data: syncQueriesStartedEvent) + let syncQueriesStartedEventPayload = HubPayload( + eventName: HubPayload.EventName.DataStore.syncQueriesStarted, + data: syncQueriesStartedEvent + ) log.verbose("[Lifecycle event 2]: syncQueriesStarted") Amplify.Hub.dispatch(to: .dataStore, payload: syncQueriesStartedEventPayload) } @@ -251,8 +266,10 @@ extension AWSInitialSyncOrchestrator { if case let .api(amplifyError, _) = datastoreError, let apiError = amplifyError as? APIError { if case .operationError(let errorDescription, _, _) = apiError, - errorDescription.range(of: "Unauthorized", - options: .caseInsensitive) != nil { + errorDescription.range( + of: "Unauthorized", + options: .caseInsensitive + ) != nil { return true } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ModelSyncedEventEmitter.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ModelSyncedEventEmitter.swift index 8e59168d0d..2fbe12e66e 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ModelSyncedEventEmitter.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ModelSyncedEventEmitter.swift @@ -25,8 +25,10 @@ enum IncomingModelSyncedEmitterEvent { /// - Check if it `ModelSyncedEvent` should be emitted, if so, emit it. /// - Then send the mutation event which was used in the check above. final class ModelSyncedEventEmitter { - private let queue = DispatchQueue(label: "com.amazonaws.ModelSyncedEventEmitterQueue", - target: DispatchQueue.global()) + private let queue = DispatchQueue( + label: "com.amazonaws.ModelSyncedEventEmitterQueue", + target: DispatchQueue.global() + ) private var syncOrchestratorSink: AnyCancellable? private var reconciliationQueueSink: AnyCancellable? @@ -50,9 +52,11 @@ final class ModelSyncedEventEmitter { /// Used within ModelSyncedEventEmitter instances, not thread-safe, is accessed serially under DispatchQueue. var dispatchedModelSyncedEvent: Bool - init(modelSchema: ModelSchema, - initialSyncOrchestrator: InitialSyncOrchestrator?, - reconciliationQueue: IncomingEventReconciliationQueue?) { + init( + modelSchema: ModelSchema, + initialSyncOrchestrator: InitialSyncOrchestrator?, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { self.modelSchema = modelSchema self.recordsReceived = 0 self.reconciledReceived = 0 @@ -66,19 +70,23 @@ final class ModelSyncedEventEmitter { .publisher .receive(on: queue) .filter { [weak self] in self?.filterSyncOperationEvent($0) == true } - .sink(receiveCompletion: { _ in }, - receiveValue: { [weak self] value in + .sink( + receiveCompletion: { _ in }, + receiveValue: { [weak self] value in self?.onReceiveSyncOperationEvent(value: value) - }) + } + ) self.reconciliationQueueSink = reconciliationQueue? .publisher .receive(on: queue) .filter { [weak self] in self?.filterReconciliationQueueEvent($0) == true } - .sink(receiveCompletion: { _ in }, - receiveValue: { [weak self] value in + .sink( + receiveCompletion: { _ in }, + receiveValue: { [weak self] value in self?.onReceiveReconciliationEvent(value: value) - }) + } + ) } /// Filtering `InitialSyncOperationEvent`s that come from `InitialSyncOperation` of the same ModelType diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ReadyEventEmitter.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ReadyEventEmitter.swift index 66f73bf9ba..3a06731e85 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ReadyEventEmitter.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ReadyEventEmitter.swift @@ -28,7 +28,7 @@ final class ReadyEventEmitter { let syncEngineStartedPublisher = ReadyEventEmitter.makeRemoteSyncEngineStartedPublisher( remoteSyncEnginePublisher: remoteSyncEnginePublisher ) - readySink = Publishers + self.readySink = Publishers .Merge(queriesReadyPublisher, syncEngineStartedPublisher) .sink(receiveCompletion: { completion in switch completion { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/SyncEventEmitter.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/SyncEventEmitter.swift index 789849aa1e..9b9e51d207 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/SyncEventEmitter.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/SyncEventEmitter.swift @@ -21,8 +21,10 @@ enum IncomingSyncEventEmitterEvent { /// emit the `syncQueriesReady` and sends back the reconciliation events (`.mutationEventApplied`, /// `.mutationEventDropped`) to its subscribers. final class SyncEventEmitter { - private let queue = DispatchQueue(label: "com.amazonaws.SyncEventEmitter", - target: DispatchQueue.global()) + private let queue = DispatchQueue( + label: "com.amazonaws.SyncEventEmitter", + target: DispatchQueue.global() + ) var modelSyncedEventEmitters: [String: ModelSyncedEventEmitter] var initialSyncCompleted: AnyCancellable? @@ -39,20 +41,24 @@ final class SyncEventEmitter { syncableModels == modelSyncedReceived } - init(initialSyncOrchestrator: InitialSyncOrchestrator?, - reconciliationQueue: IncomingEventReconciliationQueue?) { + init( + initialSyncOrchestrator: InitialSyncOrchestrator?, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { self.modelSyncedEventEmitters = [String: ModelSyncedEventEmitter]() self.syncEventEmitterTopic = PassthroughSubject() self.modelSyncedReceived = 0 - let syncableModelSchemas = ModelRegistry.modelSchemas.filter { $0.isSyncable } + let syncableModelSchemas = ModelRegistry.modelSchemas.filter(\.isSyncable) self.syncableModels = syncableModelSchemas.count var publishers = [AnyPublisher]() for syncableModelSchema in syncableModelSchemas { - let modelSyncedEventEmitter = ModelSyncedEventEmitter(modelSchema: syncableModelSchema, - initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + let modelSyncedEventEmitter = ModelSyncedEventEmitter( + modelSchema: syncableModelSchema, + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) modelSyncedEventEmitters[syncableModelSchema.name] = modelSyncedEventEmitter publishers.append(modelSyncedEventEmitter.publisher) } @@ -60,10 +66,12 @@ final class SyncEventEmitter { self.initialSyncCompleted = Publishers .MergeMany(publishers) .receive(on: queue) - .sink(receiveCompletion: { _ in }, - receiveValue: { [weak self] value in + .sink( + receiveCompletion: { _ in }, + receiveValue: { [weak self] value in self?.onReceiveModelSyncedEmitterEvent(value: value) - }) + } + ) } private func onReceiveModelSyncedEmitterEvent(value: IncomingModelSyncedEmitterEvent) { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventIngester.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventIngester.swift index 3a419c8d78..e96e905131 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventIngester.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventIngester.swift @@ -22,37 +22,48 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { return } - self.resolveConflictsThenSave(mutationEvent: mutationEvent, - storageAdapter: storageAdapter, - completion: completion) + self.resolveConflictsThenSave( + mutationEvent: mutationEvent, + storageAdapter: storageAdapter, + completion: completion + ) } } /// Resolves conflicts for the offered mutationEvent, and either accepts the event, returning a disposition, or /// rejects the event with an error - func resolveConflictsThenSave(mutationEvent: MutationEvent, - storageAdapter: StorageEngineAdapter, - completion: @escaping (Result) -> Void) { + func resolveConflictsThenSave( + mutationEvent: MutationEvent, + storageAdapter: StorageEngineAdapter, + completion: @escaping (Result) -> Void + ) { MutationEvent.pendingMutationEvents( forMutationEvent: mutationEvent, - storageAdapter: storageAdapter) { result in + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let dataStoreError): completion(.failure(dataStoreError)) case .success(let localMutationEvents): - let mutationDisposition = self.disposition(for: mutationEvent, - given: localMutationEvents) - self.resolve(candidate: mutationEvent, - localEvents: localMutationEvents, - per: mutationDisposition, - storageAdapter: storageAdapter, - completionPromise: completion) + let mutationDisposition = self.disposition( + for: mutationEvent, + given: localMutationEvents + ) + self.resolve( + candidate: mutationEvent, + localEvents: localMutationEvents, + per: mutationDisposition, + storageAdapter: storageAdapter, + completionPromise: completion + ) } } } - func disposition(for candidate: MutationEvent, - given localEvents: [MutationEvent]) -> MutationDisposition { + func disposition( + for candidate: MutationEvent, + given localEvents: [MutationEvent] + ) -> MutationDisposition { guard !localEvents.isEmpty, let existingEvent = localEvents.first else { log.verbose("\(#function) no local events, saving candidate") @@ -65,15 +76,19 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { guard let candidateMutationType = GraphQLMutationType(rawValue: candidate.mutationType) else { let dataStoreError = - DataStoreError.unknown("Couldn't get mutation type for \(candidate.mutationType)", - AmplifyErrorMessages.shouldNotHappenReportBugToAWS()) + DataStoreError.unknown( + "Couldn't get mutation type for \(candidate.mutationType)", + AmplifyErrorMessages.shouldNotHappenReportBugToAWS() + ) return .dropCandidateWithError(dataStoreError) } guard let existingMutationType = GraphQLMutationType(rawValue: existingEvent.mutationType) else { let dataStoreError = - DataStoreError.unknown("Couldn't get mutation type for \(existingEvent.mutationType)", - AmplifyErrorMessages.shouldNotHappenReportBugToAWS()) + DataStoreError.unknown( + "Couldn't get mutation type for \(existingEvent.mutationType)", + AmplifyErrorMessages.shouldNotHappenReportBugToAWS() + ) return .dropCandidateWithError(dataStoreError) } @@ -98,7 +113,7 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { model. Candidate model is below: \(candidate) """ - ) + ) return .dropCandidateWithError(dataStoreError) case (.delete, .update): @@ -110,17 +125,19 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { model. Candidate model is below: \(candidate) """ - ) + ) return .dropCandidateWithError(dataStoreError) } } - func resolve(candidate: MutationEvent, - localEvents: [MutationEvent], - per disposition: MutationDisposition, - storageAdapter: StorageEngineAdapter, - completionPromise: @escaping Future.Promise) { + func resolve( + candidate: MutationEvent, + localEvents: [MutationEvent], + per disposition: MutationDisposition, + storageAdapter: StorageEngineAdapter, + completionPromise: @escaping Future.Promise + ) { log.verbose("\(#function) disposition \(disposition)") switch disposition { @@ -133,10 +150,12 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { for localEvent in localEvents { group.addTask { try await withCheckedThrowingContinuation { continuation in - storageAdapter.delete(untypedModelType: MutationEvent.self, - modelSchema: MutationEvent.schema, - withIdentifier: localEvent.identifier(schema: MutationEvent.schema), - condition: nil) { result in + storageAdapter.delete( + untypedModelType: MutationEvent.self, + modelSchema: MutationEvent.schema, + withIdentifier: localEvent.identifier(schema: MutationEvent.schema), + condition: nil + ) { result in continuation.resume(with: result) } } @@ -150,15 +169,19 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { } } case .saveCandidate: - save(mutationEvent: candidate, - storageAdapter: storageAdapter, - completionPromise: completionPromise) + save( + mutationEvent: candidate, + storageAdapter: storageAdapter, + completionPromise: completionPromise + ) case .replaceLocalWithCandidate: guard !localEvents.isEmpty, let eventToUpdate = localEvents.first else { // Should be caught upstream, but being defensive - save(mutationEvent: candidate, - storageAdapter: storageAdapter, - completionPromise: completionPromise) + save( + mutationEvent: candidate, + storageAdapter: storageAdapter, + completionPromise: completionPromise + ) return } @@ -166,30 +189,35 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { // TODO: Handle errors from delete localEvents .suffix(from: 1) - .forEach { storageAdapter.delete(MutationEvent.self, - modelSchema: MutationEvent.schema, - withIdentifier: $0.identifier(schema: MutationEvent.schema), - condition: nil) { _ in } } + .forEach { storageAdapter.delete( + MutationEvent.self, + modelSchema: MutationEvent.schema, + withIdentifier: $0.identifier(schema: MutationEvent.schema), + condition: nil + ) { _ in } } } let resolvedEvent = getResolvedEvent(for: eventToUpdate, applying: candidate) - save(mutationEvent: resolvedEvent, - storageAdapter: storageAdapter, - completionPromise: completionPromise) + save( + mutationEvent: resolvedEvent, + storageAdapter: storageAdapter, + completionPromise: completionPromise + ) } } - private func getResolvedEvent(for originalEvent: MutationEvent, - applying candidate: MutationEvent) -> MutationEvent { + private func getResolvedEvent( + for originalEvent: MutationEvent, + applying candidate: MutationEvent + ) -> MutationEvent { var resolvedEvent = originalEvent resolvedEvent.json = candidate.json - let updatedMutationType: String - if candidate.mutationType == GraphQLMutationType.delete.rawValue { - updatedMutationType = candidate.mutationType + let updatedMutationType: String = if candidate.mutationType == GraphQLMutationType.delete.rawValue { + candidate.mutationType } else { - updatedMutationType = originalEvent.mutationType + originalEvent.mutationType } resolvedEvent.mutationType = updatedMutationType @@ -204,7 +232,7 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { completionPromise: @escaping Future.Promise ) { log.verbose("\(#function) mutationEvent: \(mutationEvent)") - let nextEventPromise = self.nextEventPromise.getAndSet(nil) + let nextEventPromise = nextEventPromise.getAndSet(nil) var eventToPersist = mutationEvent if nextEventPromise != nil { eventToPersist.inProcess = true diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventSource.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventSource.swift index cdd83055a6..2e17e407e7 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventSource.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventSource.swift @@ -9,7 +9,7 @@ import Amplify import Combine extension AWSMutationDatabaseAdapter: MutationEventSource { - + /// DataStore implements a FIFO queue of MutationEvents by using the local database /// and querying for the earliest MutationEvent by its `createdAt` field. /// @@ -30,7 +30,7 @@ extension AWSMutationDatabaseAdapter: MutationEventSource { func getNextMutationEvent(completion: @escaping DataStoreCallback) { log.verbose(#function) - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { completion(.failure(DataStoreError.nilStorageAdapter())) return } @@ -40,7 +40,8 @@ extension AWSMutationDatabaseAdapter: MutationEventSource { predicate: nil, sort: [sort], paginationInput: nil, - eagerLoad: true) { result in + eagerLoad: true + ) { result in switch result { case .failure(let dataStoreError): completion(.failure(dataStoreError)) @@ -53,18 +54,22 @@ extension AWSMutationDatabaseAdapter: MutationEventSource { log.verbose("The head of the MutationEvent queue was already inProcess (most likely interrupted process): \(mutationEvent)") completion(.success(mutationEvent)) } else { - self.markInProcess(mutationEvent: mutationEvent, - storageAdapter: storageAdapter, - completion: completion) + self.markInProcess( + mutationEvent: mutationEvent, + storageAdapter: storageAdapter, + completion: completion + ) } } } } - func markInProcess(mutationEvent: MutationEvent, - storageAdapter: StorageEngineAdapter, - completion: @escaping DataStoreCallback) { + func markInProcess( + mutationEvent: MutationEvent, + storageAdapter: StorageEngineAdapter, + completion: @escaping DataStoreCallback + ) { var inProcessEvent = mutationEvent inProcessEvent.inProcess = true storageAdapter.save(inProcessEvent, condition: nil, eagerLoad: true, completion: completion) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/AWSMutationEventPublisher.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/AWSMutationEventPublisher.swift index 77fc9d16c7..d6cf0eca9a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/AWSMutationEventPublisher.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/AWSMutationEventPublisher.swift @@ -53,7 +53,7 @@ final class AWSMutationEventPublisher: Publisher { func requestNextEvent() { log.verbose(#function) let promise: DataStoreCallback = { [weak self] result in - guard let self = self, let subscriber = self.subscription?.subscriber else { + guard let self, let subscriber = subscription?.subscriber else { return } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventClearState.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventClearState.swift index 52b3f301fa..8dd1c6fc6a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventClearState.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventClearState.swift @@ -19,18 +19,22 @@ final class MutationEventClearState { let fields = MutationEvent.keys let predicate = fields.inProcess == true let sort = QuerySortDescriptor(fieldName: fields.createdAt.stringValue, order: .ascending) - storageAdapter.query(MutationEvent.self, - predicate: predicate, - sort: [sort], - paginationInput: nil, - eagerLoad: true) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate, + sort: [sort], + paginationInput: nil, + eagerLoad: true + ) { result in switch result { case .failure(let dataStoreError): log.error("Failed on clearStateOutgoingMutations: \(dataStoreError)") case .success(let mutationEvents): if !mutationEvents.isEmpty { - updateMutationsState(mutationEvents: mutationEvents, - completion: completion) + updateMutationsState( + mutationEvents: mutationEvents, + completion: completion + ) } else { completion() } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventSubscription.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventSubscription.swift index bd86169200..ae6d7e1460 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventSubscription.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventSubscription.swift @@ -14,8 +14,10 @@ final class MutationEventSubscription: Subscription { let subscriber: MutationEventSubscriber private weak var publisher: AWSMutationEventPublisher? - init(subscriber: S, - publisher: AWSMutationEventPublisher) where S: Subscriber, + init( + subscriber: S, + publisher: AWSMutationEventPublisher + ) where S: Subscriber, S.Failure == DataStoreError, S.Input == MutationEvent { self.subscriber = MutationEventSubscriber(subscriber: subscriber) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/MutationRetryNotifier.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/MutationRetryNotifier.swift index 6aa55c2671..92261021b8 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/MutationRetryNotifier.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/MutationRetryNotifier.swift @@ -6,9 +6,9 @@ // import Amplify -import Foundation import AWSPluginsCore import Combine +import Foundation final class MutationRetryNotifier { private var lock: NSLock @@ -17,9 +17,11 @@ final class MutationRetryNotifier { var retryMutationCallback: () -> Void private var reachabilitySubscription: Subscription? - init(advice: RequestRetryAdvice, - networkReachabilityPublisher: AnyPublisher?, - retryMutationCallback: @escaping BasicClosure) { + init( + advice: RequestRetryAdvice, + networkReachabilityPublisher: AnyPublisher?, + retryMutationCallback: @escaping BasicClosure + ) { self.lock = NSLock() self.retryMutationCallback = retryMutationCallback diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue+Resolver.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue+Resolver.swift index 2c066d214d..6490b2a85a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue+Resolver.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue+Resolver.swift @@ -10,7 +10,7 @@ import Combine extension OutgoingMutationQueue { - struct Resolver { + enum Resolver { static func resolve(currentState: State, action: Action) -> State { switch (currentState, action) { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift index e2840f7e47..5aa9085fae 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift @@ -6,16 +6,18 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore /// Submits outgoing mutation events to the provisioned API protocol OutgoingMutationQueueBehavior: AnyObject { func stopSyncingToCloud(_ completion: @escaping BasicClosure) - func startSyncingToCloud(api: APICategoryGraphQLBehavior, - mutationEventPublisher: MutationEventPublisher, - reconciliationQueue: IncomingEventReconciliationQueue?) + func startSyncingToCloud( + api: APICategoryGraphQLBehavior, + mutationEventPublisher: MutationEventPublisher, + reconciliationQueue: IncomingEventReconciliationQueue? + ) var publisher: AnyPublisher { get } } @@ -42,10 +44,12 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { return outgoingMutationQueueSubject.eraseToAnyPublisher() } - init(_ stateMachine: StateMachine? = nil, - storageAdapter: StorageEngineAdapter, - dataStoreConfiguration: DataStoreConfiguration, - authModeStrategy: AuthModeStrategy) { + init( + _ stateMachine: StateMachine? = nil, + storageAdapter: StorageEngineAdapter, + dataStoreConfiguration: DataStoreConfiguration, + authModeStrategy: AuthModeStrategy + ) { self.storageAdapter = storageAdapter self.dataStoreConfiguration = dataStoreConfiguration self.authModeStrategy = authModeStrategy @@ -59,8 +63,10 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { self.operationQueue = operationQueue self.stateMachine = stateMachine ?? - StateMachine(initialState: .notInitialized, - resolver: OutgoingMutationQueue.Resolver.resolve(currentState:action:)) + StateMachine( + initialState: .notInitialized, + resolver: OutgoingMutationQueue.Resolver.resolve(currentState:action:) + ) self.outgoingMutationQueueSubject = PassthroughSubject() @@ -69,8 +75,8 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { .sink { [weak self] newState in guard let self else { return } - self.log.verbose("New state: \(newState)") - self.mutationDispatchQueue.async { + log.verbose("New state: \(newState)") + mutationDispatchQueue.async { self.respond(to: newState) } } @@ -81,9 +87,11 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { // MARK: - Public API - func startSyncingToCloud(api: APICategoryGraphQLBehavior, - mutationEventPublisher: MutationEventPublisher, - reconciliationQueue: IncomingEventReconciliationQueue?) { + func startSyncingToCloud( + api: APICategoryGraphQLBehavior, + mutationEventPublisher: MutationEventPublisher, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { log.verbose(#function) stateMachine.notify(action: .receivedStart(api, mutationEventPublisher, reconciliationQueue)) } @@ -127,21 +135,23 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { /// Responder method for `starting`. Starts the operation queue and subscribes to /// the publisher. After subscribing to the publisher, return actions: /// - receivedSubscription - private func doStart(api: APICategoryGraphQLBehavior, - mutationEventPublisher: MutationEventPublisher, - reconciliationQueue: IncomingEventReconciliationQueue?) { + private func doStart( + api: APICategoryGraphQLBehavior, + mutationEventPublisher: MutationEventPublisher, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { log.verbose(#function) self.api = api self.reconciliationQueue = reconciliationQueue queryMutationEventsFromStorage { [weak self] in - guard let self = self else { return } - guard case .starting = self.stateMachine.state else { - self.log.debug("Unexpected state transition while performing `doStart()` during `.starting` state. Current state: \(self.stateMachine.state).") + guard let self else { return } + guard case .starting = stateMachine.state else { + log.debug("Unexpected state transition while performing `doStart()` during `.starting` state. Current state: \(stateMachine.state).") return } - self.operationQueue.isSuspended = false + operationQueue.isSuspended = false // State machine notification to ".receivedSubscription" will be handled in `receive(subscription:)` mutationEventPublisher.publisher.subscribe(self) } @@ -153,7 +163,7 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { private func doStop(completion: @escaping BasicClosure) { log.verbose(#function) doStopWithoutNotifyingStateMachine() - self.stateMachine.notify(action: .doneStopping) + stateMachine.notify(action: .doneStopping) completion() } @@ -173,7 +183,7 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { /// - errored private func requestEvent() { log.verbose(#function) - guard let subscription = subscription else { + guard let subscription else { let dataStoreError = DataStoreError.unknown( "No subscription when requesting event", """ @@ -190,7 +200,7 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { /// Invoked when the subscription receives an event, not as part of the state machine transition private func enqueue(_ mutationEvent: MutationEvent) { log.verbose(#function) - guard let api = api else { + guard let api else { let dataStoreError = DataStoreError.configuration( "API is unexpectedly nil", """ @@ -221,33 +231,43 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { } } - private func processSyncMutationToCloudResult(_ result: GraphQLOperation>.OperationResult, - mutationEvent: MutationEvent, - api: APICategoryGraphQLBehavior) { + private func processSyncMutationToCloudResult( + _ result: GraphQLOperation>.OperationResult, + mutationEvent: MutationEvent, + api: APICategoryGraphQLBehavior + ) { if case let .success(graphQLResponse) = result { if case let .success(graphQLResult) = graphQLResponse { - processSuccessEvent(mutationEvent, - mutationSync: graphQLResult) + processSuccessEvent( + mutationEvent, + mutationSync: graphQLResult + ) } else if case let .failure(graphQLResponseError) = graphQLResponse { - processMutationErrorFromCloud(mutationEvent: mutationEvent, - api: api, - apiError: nil, - graphQLResponseError: graphQLResponseError) + processMutationErrorFromCloud( + mutationEvent: mutationEvent, + api: api, + apiError: nil, + graphQLResponseError: graphQLResponseError + ) } } else if case let .failure(apiError) = result { - processMutationErrorFromCloud(mutationEvent: mutationEvent, - api: api, - apiError: apiError, - graphQLResponseError: nil) + processMutationErrorFromCloud( + mutationEvent: mutationEvent, + api: api, + apiError: apiError, + graphQLResponseError: nil + ) } } /// Process the successful response from API by updating the mutation events in /// mutation event table having `nil` version - private func processSuccessEvent(_ mutationEvent: MutationEvent, - mutationSync: MutationSync?) { - if let mutationSync = mutationSync { - guard let reconciliationQueue = reconciliationQueue else { + private func processSuccessEvent( + _ mutationEvent: MutationEvent, + mutationSync: MutationSync? + ) { + if let mutationSync { + guard let reconciliationQueue else { let dataStoreError = DataStoreError.configuration( "reconciliationQueue is unexpectedly nil", """ @@ -271,11 +291,13 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { } } - private func processMutationErrorFromCloud(mutationEvent: MutationEvent, - api: APICategoryGraphQLBehavior, - apiError: APIError?, - graphQLResponseError: GraphQLResponseError>?) { - if let apiError = apiError, apiError.isOperationCancelledError { + private func processMutationErrorFromCloud( + mutationEvent: MutationEvent, + api: APICategoryGraphQLBehavior, + apiError: APIError?, + graphQLResponseError: GraphQLResponseError>? + ) { + if let apiError, apiError.isOperationCancelledError { log.verbose("SyncMutationToCloudOperation was cancelled, aborting processing") return } @@ -289,21 +311,23 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { apiError: apiError, reconciliationQueue: reconciliationQueue ) { [weak self] result in - guard let self = self else { + guard let self else { return } - self.log.verbose("[ProcessMutationErrorFromCloudOperation] result: \(result)") + log.verbose("[ProcessMutationErrorFromCloudOperation] result: \(result)") if case let .success(mutationEventOptional) = result, let outgoingMutationEvent = mutationEventOptional { - self.outgoingMutationQueueSubject.send(outgoingMutationEvent) + outgoingMutationQueueSubject.send(outgoingMutationEvent) } - self.completeProcessingEvent(mutationEvent) + completeProcessingEvent(mutationEvent) } operationQueue.addOperation(processMutationErrorFromCloudOperation) } - private func completeProcessingEvent(_ mutationEvent: MutationEvent, - mutationSync: MutationSync? = nil) { + private func completeProcessingEvent( + _ mutationEvent: MutationEvent, + mutationSync: MutationSync? = nil + ) { // TODO: We shouldn't be inspecting state, we should be using granular enough states to // ensure we don't encounter forbidden transitions. if case .stopped = stateMachine.state { @@ -319,13 +343,15 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { } catch { self.log.verbose("mutationEvent failed to delete: error: \(error)") } - if let mutationSync = mutationSync { - self.dispatchOutboxMutationProcessedEvent(mutationEvent: mutationEvent, - mutationSync: mutationSync) + if let mutationSync { + self.dispatchOutboxMutationProcessedEvent( + mutationEvent: mutationEvent, + mutationSync: mutationSync + ) } self.queryMutationEventsFromStorage { [weak self] in guard let self else { return } - self.stateMachine.notify(action: .processedEvent) + stateMachine.notify(action: .processedEvent) } } } @@ -334,16 +360,18 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { let fields = MutationEvent.keys let predicate = fields.inProcess == false || fields.inProcess == nil - storageAdapter.query(MutationEvent.self, - predicate: predicate, - sort: nil, - paginationInput: nil, - eagerLoad: true) { [weak self] result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate, + sort: nil, + paginationInput: nil, + eagerLoad: true + ) { [weak self] result in guard let self else { return } switch result { case .success(let events): - self.dispatchOutboxStatusEvent(isEmpty: events.isEmpty) + dispatchOutboxStatusEvent(isEmpty: events.isEmpty) case .failure(let error): log.error("Error querying mutation events: \(error)") } @@ -351,16 +379,22 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { } } - private func dispatchOutboxMutationProcessedEvent(mutationEvent: MutationEvent, - mutationSync: MutationSync) { + private func dispatchOutboxMutationProcessedEvent( + mutationEvent: MutationEvent, + mutationSync: MutationSync + ) { do { let localModel = try mutationEvent.decodeModel() let outboxMutationProcessedEvent = OutboxMutationEvent - .fromModelWithMetadata(modelName: mutationEvent.modelName, - model: localModel, - mutationSync: mutationSync) - let payload = HubPayload(eventName: HubPayload.EventName.DataStore.outboxMutationProcessed, - data: outboxMutationProcessedEvent) + .fromModelWithMetadata( + modelName: mutationEvent.modelName, + model: localModel, + mutationSync: mutationSync + ) + let payload = HubPayload( + eventName: HubPayload.EventName.DataStore.outboxMutationProcessed, + data: outboxMutationProcessedEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: payload) } catch { log.error("\(#function) Couldn't decode local model as \(mutationEvent.modelName) \(error)") @@ -373,10 +407,14 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { do { let localModel = try mutationEvent.decodeModel() let outboxMutationEnqueuedEvent = OutboxMutationEvent - .fromModelWithoutMetadata(modelName: mutationEvent.modelName, - model: localModel) - let payload = HubPayload(eventName: HubPayload.EventName.DataStore.outboxMutationEnqueued, - data: outboxMutationEnqueuedEvent) + .fromModelWithoutMetadata( + modelName: mutationEvent.modelName, + model: localModel + ) + let payload = HubPayload( + eventName: HubPayload.EventName.DataStore.outboxMutationEnqueued, + data: outboxMutationEnqueuedEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: payload) } catch { log.error("\(#function) Couldn't decode local model as \(mutationEvent.modelName) \(error)") @@ -387,8 +425,10 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { private func dispatchOutboxStatusEvent(isEmpty: Bool) { let outboxStatusEvent = OutboxStatusEvent(isEmpty: isEmpty) - let outboxStatusEventPayload = HubPayload(eventName: HubPayload.EventName.DataStore.outboxStatus, - data: outboxStatusEvent) + let outboxStatusEventPayload = HubPayload( + eventName: HubPayload.EventName.DataStore.outboxStatus, + data: outboxStatusEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: outboxStatusEventPayload) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/ProcessMutationErrorFromCloudOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/ProcessMutationErrorFromCloudOperation.swift index c334745fb7..b3f2b89049 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/ProcessMutationErrorFromCloudOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/ProcessMutationErrorFromCloudOperation.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore // swiftlint:disable type_body_length file_length /// Checks the GraphQL error response for specific error scenarios related to data synchronziation to the local store. @@ -30,14 +30,16 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { private weak var api: APICategoryGraphQLBehavior? private weak var reconciliationQueue: IncomingEventReconciliationQueue? - init(dataStoreConfiguration: DataStoreConfiguration, - mutationEvent: MutationEvent, - api: APICategoryGraphQLBehavior, - storageAdapter: StorageEngineAdapter, - graphQLResponseError: GraphQLResponseError>? = nil, - apiError: APIError? = nil, - reconciliationQueue: IncomingEventReconciliationQueue? = nil, - completion: @escaping (Result) -> Void) { + init( + dataStoreConfiguration: DataStoreConfiguration, + mutationEvent: MutationEvent, + api: APICategoryGraphQLBehavior, + storageAdapter: StorageEngineAdapter, + graphQLResponseError: GraphQLResponseError>? = nil, + apiError: APIError? = nil, + reconciliationQueue: IncomingEventReconciliationQueue? = nil, + completion: @escaping (Result) -> Void + ) { self.dataStoreConfiguration = dataStoreConfiguration self.mutationEvent = mutationEvent self.api = api @@ -58,7 +60,7 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { return } - if let apiError = apiError { + if let apiError { if isAuthSignedOutError(apiError: apiError) { log.verbose("User is signed out, passing error back to the error handler, and removing mutation event.") } else if let underlyingError = apiError.underlyingError { @@ -71,10 +73,12 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { return } - guard let graphQLResponseError = graphQLResponseError else { + guard let graphQLResponseError else { dataStoreConfiguration.errorHandler( - DataStoreError.api(APIError.unknown("This is unexpected. Missing APIError and GraphQLError.", ""), - mutationEvent)) + DataStoreError.api( + APIError.unknown("This is unexpected. Missing APIError and GraphQLError.", ""), + mutationEvent + )) finish(result: .success(nil)) return } @@ -102,8 +106,10 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { let errorType = AppSyncErrorType(errorTypeValue) switch errorType { case .conditionalCheck: - let payload = HubPayload(eventName: HubPayload.EventName.DataStore.conditionalSaveFailed, - data: mutationEvent) + let payload = HubPayload( + eventName: HubPayload.EventName.DataStore.conditionalSaveFailed, + data: mutationEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: payload) dataStoreConfiguration.errorHandler(DataStoreError.api(graphQLResponseError, mutationEvent)) finish(result: .success(nil)) @@ -175,8 +181,10 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { switch mutationType { case .create: - let error = DataStoreError.unknown("Should never get conflict unhandled for create mutation", - "This indicates something unexpected was returned from the service") + let error = DataStoreError.unknown( + "Should never get conflict unhandled for create mutation", + "This indicates something unexpected was returned from the service" + ) finish(result: .failure(error)) return case .delete: @@ -188,15 +196,17 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { private func getRemoteModel(_ extensions: [String: JSONValue]) -> Result, Error> { guard case let .object(data) = extensions["data"] else { - let error = DataStoreError.unknown("Missing remote model from the response from AppSync.", - "This indicates something unexpected was returned from the service") + let error = DataStoreError.unknown( + "Missing remote model from the response from AppSync.", + "This indicates something unexpected was returned from the service" + ) return .failure(error) } do { let serializedJSON = try JSONEncoder().encode(data) let decoder = JSONDecoder() decoder.dateDecodingStrategy = ModelDateFormatting.decodingStrategy - return .success(try decoder.decode(MutationSync.self, from: serializedJSON)) + return try .success(decoder.decode(MutationSync.self, from: serializedJSON)) } catch { return .failure(error) } @@ -219,9 +229,11 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { case .applyRemote: self.saveCreateOrUpdateMutation(remoteModel: remoteModel) case .retryLocal: - let request = GraphQLRequest.deleteMutation(of: localModel, - modelSchema: localModel.schema, - version: latestVersion) + let request = GraphQLRequest.deleteMutation( + of: localModel, + modelSchema: localModel.schema, + version: latestVersion + ) self.sendMutation(describedBy: request) case .retry(let model): guard let modelSchema = ModelRegistry.modelSchema(from: self.mutationEvent.modelName) else { @@ -230,9 +242,11 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { initialized. """) } - let request = GraphQLRequest.updateMutation(of: model, - modelSchema: modelSchema, - version: latestVersion) + let request = GraphQLRequest.updateMutation( + of: model, + modelSchema: modelSchema, + version: latestVersion + ) self.sendMutation(describedBy: request) } } @@ -262,9 +276,11 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { initialized. """) } - let request = GraphQLRequest.updateMutation(of: localModel, - modelSchema: modelSchema, - version: latestVersion) + let request = GraphQLRequest.updateMutation( + of: localModel, + modelSchema: modelSchema, + version: latestVersion + ) self.sendMutation(describedBy: request) case .retry(let model): guard let modelSchema = ModelRegistry.modelSchema(from: self.mutationEvent.modelName) else { @@ -273,9 +289,11 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { initialized. """) } - let request = GraphQLRequest.updateMutation(of: model, - modelSchema: modelSchema, - version: latestVersion) + let request = GraphQLRequest.updateMutation( + of: model, + modelSchema: modelSchema, + version: latestVersion + ) self.sendMutation(describedBy: request) } } @@ -288,7 +306,7 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { return } - guard let api = self.api else { + guard let api else { log.error("\(#function): API unexpectedly nil") let apiError = APIError.unknown("API unexpectedly nil", "") finish(result: .failure(apiError)) @@ -299,13 +317,13 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { Task { [weak self] in do { let result = try await api.mutate(request: apiRequest) - guard let self = self, !self.isCancelled else { + guard let self, !self.isCancelled else { self?.finish(result: .failure(APIError.operationError("Mutation operation cancelled", ""))) return } - self.log.verbose("sendMutationToCloud received asyncEvent: \(result)") - self.validate(cloudResult: result, request: apiRequest) + log.verbose("sendMutationToCloud received asyncEvent: \(result)") + validate(cloudResult: result, request: apiRequest) } catch { self?.finish(result: .failure(APIError.operationError("Failed to do mutation", "", error))) } @@ -319,7 +337,7 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { switch cloudResult { case .success(let mutationSyncResult): - guard let reconciliationQueue = reconciliationQueue else { + guard let reconciliationQueue else { let dataStoreError = DataStoreError.configuration( "reconciliationQueue is unexpectedly nil", """ @@ -359,10 +377,12 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { let identifier = remoteModel.model.identifier(schema: modelSchema) - storageAdapter.delete(untypedModelType: modelType, - modelSchema: modelSchema, - withIdentifier: identifier, - condition: nil) { response in + storageAdapter.delete( + untypedModelType: modelType, + modelSchema: modelSchema, + withIdentifier: identifier, + condition: nil + ) { response in switch response { case .failure(let dataStoreError): let error = DataStoreError.unknown("Delete failed \(dataStoreError)", "") @@ -397,8 +417,10 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { } } - private func saveMetadata(storageAdapter: StorageEngineAdapter, - inProcessModel: MutationSync) { + private func saveMetadata( + storageAdapter: StorageEngineAdapter, + inProcessModel: MutationSync + ) { log.verbose(#function) storageAdapter.save(inProcessModel.syncMetadata, condition: nil, eagerLoad: true) { result in switch result { @@ -430,17 +452,21 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { mutationType = .update } - guard let mutationEvent = try? MutationEvent(untypedModel: savedModel.model.instance, - mutationType: mutationType, - version: version) + guard let mutationEvent = try? MutationEvent( + untypedModel: savedModel.model.instance, + mutationType: mutationType, + version: version + ) else { let error = DataStoreError.unknown("Could not create MutationEvent", "") finish(result: .failure(error)) return } - let payload = HubPayload(eventName: HubPayload.EventName.DataStore.syncReceived, - data: mutationEvent) + let payload = HubPayload( + eventName: HubPayload.EventName.DataStore.syncReceived, + data: mutationEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: payload) finish(result: .success(mutationEvent)) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/SyncMutationToCloudOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/SyncMutationToCloudOperation.swift index 40f9c04f06..a24b8d47d7 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/SyncMutationToCloudOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/SyncMutationToCloudOperation.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore /// Publishes a mutation event to the specified Cloud API. Upon receipt of the API response, validates to ensure it is /// not a retriable error. If it is, attempts a retry until either success or terminal failure. Upon success or @@ -29,14 +29,16 @@ class SyncMutationToCloudOperation: AsynchronousOperation { private var currentAttemptNumber: Int private var authTypesIterator: AWSAuthorizationTypeIterator? - init(mutationEvent: MutationEvent, - getLatestSyncMetadata: @escaping () -> MutationSyncMetadata?, - api: APICategoryGraphQLBehavior, - authModeStrategy: AuthModeStrategy, - networkReachabilityPublisher: AnyPublisher? = nil, - currentAttemptNumber: Int = 1, - requestRetryablePolicy: RequestRetryablePolicy? = RequestRetryablePolicy(), - completion: @escaping GraphQLOperation>.ResultListener) async { + init( + mutationEvent: MutationEvent, + getLatestSyncMetadata: @escaping () -> MutationSyncMetadata?, + api: APICategoryGraphQLBehavior, + authModeStrategy: AuthModeStrategy, + networkReachabilityPublisher: AnyPublisher? = nil, + currentAttemptNumber: Int = 1, + requestRetryablePolicy: RequestRetryablePolicy? = RequestRetryablePolicy(), + completion: @escaping GraphQLOperation>.ResultListener + ) async { self.mutationEvent = mutationEvent self.getLatestSyncMetadata = getLatestSyncMetadata self.api = api @@ -48,8 +50,10 @@ class SyncMutationToCloudOperation: AsynchronousOperation { if let modelSchema = ModelRegistry.modelSchema(from: mutationEvent.modelName), let mutationType = GraphQLMutationType(rawValue: mutationEvent.mutationType) { - self.authTypesIterator = await authModeStrategy.authTypesFor(schema: modelSchema, - operation: mutationType.toModelOperation()) + self.authTypesIterator = await authModeStrategy.authTypesFor( + schema: modelSchema, + operation: mutationType.toModelOperation() + ) } super.init() @@ -151,10 +155,12 @@ class SyncMutationToCloudOperation: AsynchronousOperation { initialized. """) } - request = GraphQLRequest.deleteMutation(of: model, - modelSchema: modelSchema, - where: graphQLFilter, - version: version) + request = GraphQLRequest.deleteMutation( + of: model, + modelSchema: modelSchema, + where: graphQLFilter, + version: version + ) case .update: let model = try mutationEvent.decodeModel() guard let modelSchema = ModelRegistry.modelSchema(from: mutationEvent.modelName) else { @@ -163,10 +169,12 @@ class SyncMutationToCloudOperation: AsynchronousOperation { initialized. """) } - request = GraphQLRequest.updateMutation(of: model, - modelSchema: modelSchema, - where: graphQLFilter, - version: version) + request = GraphQLRequest.updateMutation( + of: model, + modelSchema: modelSchema, + where: graphQLFilter, + version: version + ) case .create: let model = try mutationEvent.decodeModel() guard let modelSchema = ModelRegistry.modelSchema(from: mutationEvent.modelName) else { @@ -175,9 +183,11 @@ class SyncMutationToCloudOperation: AsynchronousOperation { initialized. """) } - request = GraphQLRequest.createMutation(of: model, - modelSchema: modelSchema, - version: version) + request = GraphQLRequest.createMutation( + of: model, + modelSchema: modelSchema, + version: version + ) } } catch { let apiError = APIError.unknown("Couldn't decode model", "", error) @@ -185,8 +195,10 @@ class SyncMutationToCloudOperation: AsynchronousOperation { return nil } - let awsPluginOptions = AWSAPIPluginDataStoreOptions(authType: authType, - modelName: mutationEvent.modelName) + let awsPluginOptions = AWSAPIPluginDataStoreOptions( + authType: authType, + modelName: mutationEvent.modelName + ) request.options = GraphQLRequest.Options(pluginOptions: awsPluginOptions) return request } @@ -196,7 +208,7 @@ class SyncMutationToCloudOperation: AsynchronousOperation { /// completion handler /// - Parameter apiRequest: The GraphQLRequest used to create the mutation operation private func sendMutation(describedBy apiRequest: GraphQLRequest>) { - guard let api = api else { + guard let api else { log.error("\(#function): API unexpectedly nil") let apiError = APIError.unknown("API unexpectedly nil", "") finish(result: .failure(apiError)) @@ -224,7 +236,7 @@ class SyncMutationToCloudOperation: AsynchronousOperation { toCloudResult result: GraphQLResponse>, withAPIRequest apiRequest: GraphQLRequest> ) { - guard !self.isCancelled else { + guard !isCancelled else { Amplify.log.debug("SyncMutationToCloudOperation cancelled, aborting") return } @@ -286,9 +298,11 @@ class SyncMutationToCloudOperation: AsynchronousOperation { case .networkError(_, _, let error): // currently expecting APIOperationResponse to be an URLError let urlError = error as? URLError - advice = requestRetryablePolicy.retryRequestAdvice(urlError: urlError, - httpURLResponse: nil, - attemptNumber: currentAttemptNumber) + advice = requestRetryablePolicy.retryRequestAdvice( + urlError: urlError, + httpURLResponse: nil, + attemptNumber: currentAttemptNumber + ) // we can't unify the following two cases (case 1 and case 2) as they have different associated values. // should retry with a different authType if server returned "Unauthorized Error" @@ -302,18 +316,22 @@ class SyncMutationToCloudOperation: AsynchronousOperation { switch authError { case .sessionExpired, .signedOut: // use `userAuthenticationRequired` to ensure advice to retry is true. - advice = requestRetryablePolicy.retryRequestAdvice(urlError: URLError(.userAuthenticationRequired), - httpURLResponse: nil, - attemptNumber: currentAttemptNumber) + advice = requestRetryablePolicy.retryRequestAdvice( + urlError: URLError(.userAuthenticationRequired), + httpURLResponse: nil, + attemptNumber: currentAttemptNumber + ) default: // should retry with a different authType if request failed locally with any other AuthError advice = shouldRetryWithDifferentAuthType() } } case .httpStatusError(_, let httpURLResponse): - advice = requestRetryablePolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: httpURLResponse, - attemptNumber: currentAttemptNumber) + advice = requestRetryablePolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: httpURLResponse, + attemptNumber: currentAttemptNumber + ) default: break } @@ -325,8 +343,10 @@ class SyncMutationToCloudOperation: AsynchronousOperation { return RequestRetryAdvice(shouldRetry: shouldRetry, retryInterval: .milliseconds(0)) } - private func scheduleRetry(advice: RequestRetryAdvice, - withAuthType authType: AWSAuthorizationType? = nil) { + private func scheduleRetry( + advice: RequestRetryAdvice, + withAuthType authType: AWSAuthorizationType? = nil + ) { log.verbose("\(#function) scheduling retry for mutation \(advice)") mutationRetryNotifier = MutationRetryNotifier( advice: advice, diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+AuthModeStrategyDelegate.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+AuthModeStrategyDelegate.swift index db2ae3b9e4..bbb2826218 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+AuthModeStrategyDelegate.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+AuthModeStrategyDelegate.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore extension RemoteSyncEngine: AuthModeStrategyDelegate { @@ -29,10 +29,10 @@ extension RemoteSyncEngine: AuthModeStrategyDelegate { return isLoggedInWithOIDC } - guard let auth = auth else { + guard let auth else { return false } - return (try? await auth.getCurrentUser()) != nil + return await (try? auth.getCurrentUser()) != nil } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+IncomingEventReconciliationQueueEvent.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+IncomingEventReconciliationQueueEvent.swift index 7e3c4d23c7..ecc3b75f85 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+IncomingEventReconciliationQueueEvent.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+IncomingEventReconciliationQueueEvent.swift @@ -41,15 +41,17 @@ extension RemoteSyncEngine { stateMachine.notify(action: .initializedSubscriptions) case .started: log.verbose("[InitializeSubscription.6] RemoteSyncEngine IncomingEventReconciliationQueueEvent.started") - guard let api = self.api else { + guard let api else { let error = DataStoreError.internalOperation("api is unexpectedly `nil`", "", nil) stateMachine.notify(action: .errored(error)) return } remoteSyncTopicPublisher.send(.subscriptionsActivated) - stateMachine.notify(action: .activatedCloudSubscriptions(api, - mutationEventPublisher, - reconciliationQueue)) + stateMachine.notify(action: .activatedCloudSubscriptions( + api, + mutationEventPublisher, + reconciliationQueue + )) case .paused: remoteSyncTopicPublisher.send(.subscriptionsPaused) case .idle, .mutationEventDropped, .mutationEventApplied: diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Resolver.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Resolver.swift index 957051b8e6..ab6d7946b7 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Resolver.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Resolver.swift @@ -9,7 +9,7 @@ import Amplify import Combine extension RemoteSyncEngine { - struct Resolver { + enum Resolver { // swiftlint:disable cyclomatic_complexity static func resolve(currentState: State, action: Action) -> State { switch (currentState, action) { @@ -35,9 +35,11 @@ extension RemoteSyncEngine { case (.performingInitialSync, .errored(let error)): return .cleaningUp(error) - case (.activatingCloudSubscriptions, .activatedCloudSubscriptions(let api, - let mutationEventPublisher, - let reconciliationQueue)): + case (.activatingCloudSubscriptions, .activatedCloudSubscriptions( + let api, + let mutationEventPublisher, + let reconciliationQueue + )): return .activatingMutationQueue(api, mutationEventPublisher, reconciliationQueue) case (.activatingCloudSubscriptions, .errored(let error)): return .cleaningUp(error) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Retryable.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Retryable.swift index 8d4aa5a61a..92c8f328b1 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Retryable.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Retryable.swift @@ -44,9 +44,11 @@ extension RemoteSyncEngine { urlErrorOptional = urlError } - let advice = requestRetryablePolicy.retryRequestAdvice(urlError: urlErrorOptional, - httpURLResponse: nil, - attemptNumber: currentAttemptNumber) + let advice = requestRetryablePolicy.retryRequestAdvice( + urlError: urlErrorOptional, + httpURLResponse: nil, + attemptNumber: currentAttemptNumber + ) return advice } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine.swift index fd30c9ecae..34ea053a7c 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore // swiftlint:disable type_body_length file_length class RemoteSyncEngine: RemoteSyncEngineBehavior { @@ -66,14 +66,16 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { /// Initializes the CloudSyncEngine with the specified storageAdapter as the provider for persistence of /// MutationEvents, sync metadata, and conflict resolution metadata. Immediately initializes the incoming mutation /// queue so it can begin accepting incoming mutations from DataStore. - convenience init(storageAdapter: StorageEngineAdapter, - dataStoreConfiguration: DataStoreConfiguration, - outgoingMutationQueue: OutgoingMutationQueueBehavior? = nil, - initialSyncOrchestratorFactory: InitialSyncOrchestratorFactory? = nil, - reconciliationQueueFactory: IncomingEventReconciliationQueueFactory? = nil, - stateMachine: StateMachine? = nil, - networkReachabilityPublisher: AnyPublisher? = nil, - requestRetryablePolicy: RequestRetryablePolicy? = nil) throws { + convenience init( + storageAdapter: StorageEngineAdapter, + dataStoreConfiguration: DataStoreConfiguration, + outgoingMutationQueue: OutgoingMutationQueueBehavior? = nil, + initialSyncOrchestratorFactory: InitialSyncOrchestratorFactory? = nil, + reconciliationQueueFactory: IncomingEventReconciliationQueueFactory? = nil, + stateMachine: StateMachine? = nil, + networkReachabilityPublisher: AnyPublisher? = nil, + requestRetryablePolicy: RequestRetryablePolicy? = nil + ) throws { let mutationDatabaseAdapter = try AWSMutationDatabaseAdapter(storageAdapter: storageAdapter) let awsMutationEventPublisher = AWSMutationEventPublisher(eventSource: mutationDatabaseAdapter) @@ -82,9 +84,11 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { let resolvedAuthStrategy: AuthModeStrategy = dataStoreConfiguration.authModeStrategyType.resolveStrategy() let outgoingMutationQueue = outgoingMutationQueue ?? - OutgoingMutationQueue(storageAdapter: storageAdapter, - dataStoreConfiguration: dataStoreConfiguration, - authModeStrategy: resolvedAuthStrategy) + OutgoingMutationQueue( + storageAdapter: storageAdapter, + dataStoreConfiguration: dataStoreConfiguration, + authModeStrategy: resolvedAuthStrategy + ) // swiftlint:disable line_length let reconciliationQueueFactory = reconciliationQueueFactory ?? AWSIncomingEventReconciliationQueue.init(modelSchemas:api:storageAdapter:syncExpressions:auth:authModeStrategy:modelReconciliationQueueFactory:disableSubscriptions:) @@ -93,35 +97,41 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { AWSInitialSyncOrchestrator.init(dataStoreConfiguration:authModeStrategy:api:reconciliationQueue:storageAdapter:) let resolver = RemoteSyncEngine.Resolver.resolve(currentState:action:) - let stateMachine = stateMachine ?? StateMachine(initialState: .notStarted, - resolver: resolver) + let stateMachine = stateMachine ?? StateMachine( + initialState: .notStarted, + resolver: resolver + ) let requestRetryablePolicy = requestRetryablePolicy ?? RequestRetryablePolicy() - self.init(storageAdapter: storageAdapter, - dataStoreConfiguration: dataStoreConfiguration, - authModeStrategy: resolvedAuthStrategy, - outgoingMutationQueue: outgoingMutationQueue, - mutationEventIngester: mutationDatabaseAdapter, - mutationEventPublisher: awsMutationEventPublisher, - initialSyncOrchestratorFactory: initialSyncOrchestratorFactory, - reconciliationQueueFactory: reconciliationQueueFactory, - stateMachine: stateMachine, - networkReachabilityPublisher: networkReachabilityPublisher, - requestRetryablePolicy: requestRetryablePolicy) + self.init( + storageAdapter: storageAdapter, + dataStoreConfiguration: dataStoreConfiguration, + authModeStrategy: resolvedAuthStrategy, + outgoingMutationQueue: outgoingMutationQueue, + mutationEventIngester: mutationDatabaseAdapter, + mutationEventPublisher: awsMutationEventPublisher, + initialSyncOrchestratorFactory: initialSyncOrchestratorFactory, + reconciliationQueueFactory: reconciliationQueueFactory, + stateMachine: stateMachine, + networkReachabilityPublisher: networkReachabilityPublisher, + requestRetryablePolicy: requestRetryablePolicy + ) } - init(storageAdapter: StorageEngineAdapter, - dataStoreConfiguration: DataStoreConfiguration, - authModeStrategy: AuthModeStrategy, - outgoingMutationQueue: OutgoingMutationQueueBehavior, - mutationEventIngester: MutationEventIngester, - mutationEventPublisher: MutationEventPublisher, - initialSyncOrchestratorFactory: @escaping InitialSyncOrchestratorFactory, - reconciliationQueueFactory: @escaping IncomingEventReconciliationQueueFactory, - stateMachine: StateMachine, - networkReachabilityPublisher: AnyPublisher?, - requestRetryablePolicy: RequestRetryablePolicy) { + init( + storageAdapter: StorageEngineAdapter, + dataStoreConfiguration: DataStoreConfiguration, + authModeStrategy: AuthModeStrategy, + outgoingMutationQueue: OutgoingMutationQueueBehavior, + mutationEventIngester: MutationEventIngester, + mutationEventPublisher: MutationEventPublisher, + initialSyncOrchestratorFactory: @escaping InitialSyncOrchestratorFactory, + reconciliationQueueFactory: @escaping IncomingEventReconciliationQueueFactory, + stateMachine: StateMachine, + networkReachabilityPublisher: AnyPublisher?, + requestRetryablePolicy: RequestRetryablePolicy + ) { self.storageAdapter = storageAdapter self.dataStoreConfiguration = dataStoreConfiguration self.authModeStrategy = authModeStrategy @@ -140,11 +150,11 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { self.stateMachineSink = self.stateMachine .$state .sink { [weak self] newState in - guard let self = self else { + guard let self else { return } - self.log.verbose("New state: \(newState)") - self.taskQueue.async { + log.verbose("New state: \(newState)") + taskQueue.async { await self.respond(to: newState) } } @@ -173,9 +183,11 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { case .activatingCloudSubscriptions: activateCloudSubscriptions() case .activatingMutationQueue(let api, let mutationEventPublisher, let reconciliationQueue): - startMutationQueue(api: api, - mutationEventPublisher: mutationEventPublisher, - reconciliationQueue: reconciliationQueue) + startMutationQueue( + api: api, + mutationEventPublisher: mutationEventPublisher, + reconciliationQueue: reconciliationQueue + ) case .notifyingSyncStarted: notifySyncStarted() @@ -280,18 +292,22 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { } } - private func initializeSubscriptions(api: APICategoryGraphQLBehavior, - storageAdapter: StorageEngineAdapter) async { + private func initializeSubscriptions( + api: APICategoryGraphQLBehavior, + storageAdapter: StorageEngineAdapter + ) async { log.debug("[InitializeSubscription] \(#function)") let syncableModelSchemas = ModelRegistry.modelSchemas.filter { $0.isSyncable } - reconciliationQueue = await reconciliationQueueFactory(syncableModelSchemas, - api, - storageAdapter, - dataStoreConfiguration.syncExpressions, - auth, - authModeStrategy, - nil, - dataStoreConfiguration.disableSubscriptions) + reconciliationQueue = await reconciliationQueueFactory( + syncableModelSchemas, + api, + storageAdapter, + dataStoreConfiguration.syncExpressions, + auth, + authModeStrategy, + nil, + dataStoreConfiguration.disableSubscriptions + ) reconciliationQueueSink = reconciliationQueue? .publisher .sink( @@ -303,17 +319,21 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { private func performInitialSync() { log.debug("[InitializeSubscription.6] \(#function)") - let initialSyncOrchestrator = initialSyncOrchestratorFactory(dataStoreConfiguration, - authModeStrategy, - api, - reconciliationQueue, - storageAdapter) + let initialSyncOrchestrator = initialSyncOrchestratorFactory( + dataStoreConfiguration, + authModeStrategy, + api, + reconciliationQueue, + storageAdapter + ) // Hold a reference so we can `reset` while initial sync is in process self.initialSyncOrchestrator = initialSyncOrchestrator - syncEventEmitter = SyncEventEmitter(initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + syncEventEmitter = SyncEventEmitter( + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) syncEventEmitterSink = syncEventEmitter? .publisher @@ -330,23 +350,23 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { ) initialSyncOrchestrator.sync { [weak self] result in - guard let self = self else { + guard let self else { return } if case .failure(let dataStoreError) = result { - self.log.error(dataStoreError.errorDescription) - self.log.error(dataStoreError.recoverySuggestion) + log.error(dataStoreError.errorDescription) + log.error(dataStoreError.recoverySuggestion) if let underlyingError = dataStoreError.underlyingError { - self.log.error("\(underlyingError)") + log.error("\(underlyingError)") } - self.stateMachine.notify(action: .errored(dataStoreError)) + stateMachine.notify(action: .errored(dataStoreError)) } else { - self.log.info("Successfully finished sync") + log.info("Successfully finished sync") - self.remoteSyncTopicPublisher.send(.performedInitialSync) - self.stateMachine.notify(action: .performedInitialSync) + remoteSyncTopicPublisher.send(.performedInitialSync) + stateMachine.notify(action: .performedInitialSync) } self.initialSyncOrchestrator = nil } @@ -354,7 +374,7 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { private func activateCloudSubscriptions() { log.debug(#function) - guard let reconciliationQueue = reconciliationQueue else { + guard let reconciliationQueue else { let error = DataStoreError.internalOperation("reconciliationQueue is unexpectedly `nil`", "", nil) stateMachine.notify(action: .errored(error)) return @@ -363,13 +383,17 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { reconciliationQueue.start() } - private func startMutationQueue(api: APICategoryGraphQLBehavior, - mutationEventPublisher: MutationEventPublisher, - reconciliationQueue: IncomingEventReconciliationQueue?) { + private func startMutationQueue( + api: APICategoryGraphQLBehavior, + mutationEventPublisher: MutationEventPublisher, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { log.debug(#function) - outgoingMutationQueue.startSyncingToCloud(api: api, - mutationEventPublisher: mutationEventPublisher, - reconciliationQueue: reconciliationQueue) + outgoingMutationQueue.startSyncingToCloud( + api: api, + mutationEventPublisher: mutationEventPublisher, + reconciliationQueue: reconciliationQueue + ) remoteSyncTopicPublisher.send(.mutationQueueStarted) stateMachine.notify(action: .activatedMutationQueue) @@ -396,8 +420,10 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { private func notifySyncStarted() { resetCurrentAttemptNumber() log.verbose("[Lifecycle event 5]: syncStarted") - Amplify.Hub.dispatch(to: .dataStore, - payload: HubPayload(eventName: HubPayload.EventName.DataStore.syncStarted)) + Amplify.Hub.dispatch( + to: .dataStore, + payload: HubPayload(eventName: HubPayload.EventName.DataStore.syncStarted) + ) remoteSyncTopicPublisher.send(.syncStarted) stateMachine.notify(action: .notifiedSyncStarted) @@ -405,8 +431,10 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { private func onReceiveNetworkStatus(networkStatus: ReachabilityUpdate) { let networkStatusEvent = NetworkStatusEvent(active: networkStatus.isOnline) - let networkStatusEventPayload = HubPayload(eventName: HubPayload.EventName.DataStore.networkStatus, - data: networkStatusEvent) + let networkStatusEventPayload = HubPayload( + eventName: HubPayload.EventName.DataStore.networkStatus, + data: networkStatusEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: networkStatusEventPayload) } @@ -444,7 +472,7 @@ extension RemoteSyncEngine: Resettable { if let resettable = child.value as? Resettable { log.verbose("Resetting \(label)") await resettable.reset() - self.log.verbose("Resetting \(label): finished") + log.verbose("Resetting \(label): finished") } } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryable.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryable.swift index f215daeda0..b0c8529d9e 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryable.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryable.swift @@ -10,8 +10,10 @@ import Foundation struct RequestRetryAdvice { let shouldRetry: Bool let retryInterval: DispatchTimeInterval - init(shouldRetry: Bool, - retryInterval: DispatchTimeInterval = .seconds(60)) { + init( + shouldRetry: Bool, + retryInterval: DispatchTimeInterval = .seconds(60) + ) { self.shouldRetry = shouldRetry self.retryInterval = retryInterval } @@ -19,7 +21,9 @@ struct RequestRetryAdvice { } protocol RequestRetryable { - func retryRequestAdvice(urlError: URLError?, - httpURLResponse: HTTPURLResponse?, - attemptNumber: Int) -> RequestRetryAdvice + func retryRequestAdvice( + urlError: URLError?, + httpURLResponse: HTTPURLResponse?, + attemptNumber: Int + ) -> RequestRetryAdvice } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryablePolicy.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryablePolicy.swift index 220834d187..13cffd6ee8 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryablePolicy.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryablePolicy.swift @@ -14,24 +14,28 @@ class RequestRetryablePolicy: RequestRetryable { private static let maxExponentForExponentialBackoff = 31 - public func retryRequestAdvice(urlError: URLError?, - httpURLResponse: HTTPURLResponse?, - attemptNumber: Int) -> RequestRetryAdvice { + public func retryRequestAdvice( + urlError: URLError?, + httpURLResponse: HTTPURLResponse?, + attemptNumber: Int + ) -> RequestRetryAdvice { var attemptNumber = attemptNumber if attemptNumber <= 0 { assertionFailure("attemptNumber should be > 0") attemptNumber = 1 } - if let urlError = urlError { + if let urlError { return determineRetryRequestAdvice(basedOn: urlError, attemptNumber: attemptNumber) } else { return determineRetryRequestAdvice(basedOn: httpURLResponse, attemptNumber: attemptNumber) } } - private func determineRetryRequestAdvice(basedOn urlError: URLError, - attemptNumber: Int) -> RequestRetryAdvice { + private func determineRetryRequestAdvice( + basedOn urlError: URLError, + attemptNumber: Int + ) -> RequestRetryAdvice { switch urlError.code { case .notConnectedToInternet, .dnsLookupFailed, @@ -51,10 +55,12 @@ class RequestRetryablePolicy: RequestRetryable { return RequestRetryAdvice(shouldRetry: false) } - private func determineRetryRequestAdvice(basedOn httpURLResponse: HTTPURLResponse?, - attemptNumber: Int) -> RequestRetryAdvice { + private func determineRetryRequestAdvice( + basedOn httpURLResponse: HTTPURLResponse?, + attemptNumber: Int + ) -> RequestRetryAdvice { /// If there was no error and no response, then we should not retry. - guard let httpURLResponse = httpURLResponse else { + guard let httpURLResponse else { return RequestRetryAdvice(shouldRetry: false) } @@ -97,14 +103,13 @@ class RequestRetryablePolicy: RequestRetryable { /// - Parameter response: The response to get the header from /// - Returns: The value of the "Retry-After" header, or nil if not present or not convertable to Int private func getRetryAfterHeaderValue(from response: HTTPURLResponse) -> Int? { - let waitTime: Int? - switch response.allHeaderFields["Retry-After"] { + let waitTime: Int? = switch response.allHeaderFields["Retry-After"] { case let retryTime as String: - waitTime = Int(retryTime) + Int(retryTime) case let retryTime as Int: - waitTime = retryTime + retryTime default: - waitTime = nil + nil } return waitTime diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueue.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueue.swift index 4a6d765aca..92319a2352 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueue.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueue.swift @@ -14,15 +14,16 @@ typealias DisableSubscriptions = () -> Bool // Used for testing: typealias IncomingEventReconciliationQueueFactory = - ([ModelSchema], - APICategoryGraphQLBehavior, - StorageEngineAdapter, - [DataStoreSyncExpression], - AuthCategoryBehavior?, - AuthModeStrategy, - ModelReconciliationQueueFactory?, - @escaping DisableSubscriptions -) async -> IncomingEventReconciliationQueue + ( + [ModelSchema], + APICategoryGraphQLBehavior, + StorageEngineAdapter, + [DataStoreSyncExpression], + AuthCategoryBehavior?, + AuthModeStrategy, + ModelReconciliationQueueFactory?, + @escaping DisableSubscriptions + ) async -> IncomingEventReconciliationQueue final class AWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueue { @@ -45,22 +46,24 @@ final class AWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueu } private let modelSchemasCount: Int - init(modelSchemas: [ModelSchema], - api: APICategoryGraphQLBehavior, - storageAdapter: StorageEngineAdapter, - syncExpressions: [DataStoreSyncExpression], - auth: AuthCategoryBehavior? = nil, - authModeStrategy: AuthModeStrategy, - modelReconciliationQueueFactory: ModelReconciliationQueueFactory? = nil, - disableSubscriptions: @escaping () -> Bool = { false }) async { + init( + modelSchemas: [ModelSchema], + api: APICategoryGraphQLBehavior, + storageAdapter: StorageEngineAdapter, + syncExpressions: [DataStoreSyncExpression], + auth: AuthCategoryBehavior? = nil, + authModeStrategy: AuthModeStrategy, + modelReconciliationQueueFactory: ModelReconciliationQueueFactory? = nil, + disableSubscriptions: @escaping () -> Bool = { false } + ) async { self.modelSchemasCount = modelSchemas.count - self.modelReconciliationQueueSinks.set([:]) + modelReconciliationQueueSinks.set([:]) self.eventReconciliationQueueTopic = CurrentValueSubject(.idle) - self.reconciliationQueues.set([:]) + reconciliationQueues.set([:]) self.reconciliationQueueConnectionStatus = [:] self.reconcileAndSaveQueue = ReconcileAndSaveQueue(modelSchemas) - if let modelReconciliationQueueFactory = modelReconciliationQueueFactory { + if let modelReconciliationQueueFactory { self.modelReconciliationQueueFactory = modelReconciliationQueueFactory } else { self.modelReconciliationQueueFactory = AWSModelReconciliationQueue.init @@ -80,7 +83,7 @@ final class AWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueu Running DataStore on watchOS with subscriptions enabled is only possible during special circumstances such as actively streaming audio. See https://github.com/aws-amplify/amplify-swift/pull/3368 for more details. """ - self.log.verbose(message) + log.verbose(message) } #endif @@ -94,21 +97,25 @@ final class AWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueu log.warn("Duplicate model name found: \(modelName), not subscribing") continue } - let queue = await self.modelReconciliationQueueFactory(modelSchema, - storageAdapter, - api, - reconcileAndSaveQueue, - modelPredicate, - auth, - authModeStrategy, - subscriptionsDisabled ? OperationDisabledIncomingSubscriptionEventPublisher() : nil) + let queue = await self.modelReconciliationQueueFactory( + modelSchema, + storageAdapter, + api, + reconcileAndSaveQueue, + modelPredicate, + auth, + authModeStrategy, + subscriptionsDisabled ? OperationDisabledIncomingSubscriptionEventPublisher() : nil + ) reconciliationQueues.with { reconciliationQueues in reconciliationQueues[modelName] = queue } log.verbose("[InitializeSubscription.5] Sink reconciliationQueues \(modelName) \(reconciliationQueues.get().count)") - let modelReconciliationQueueSink = queue.publisher.sink(receiveCompletion: onReceiveCompletion(completed:), - receiveValue: onReceiveValue(receiveValue:)) + let modelReconciliationQueueSink = queue.publisher.sink( + receiveCompletion: onReceiveCompletion(completed:), + receiveValue: onReceiveValue(receiveValue:) + ) modelReconciliationQueueSinks.with { modelReconciliationQueueSinks in modelReconciliationQueueSinks[modelName] = modelReconciliationQueueSink } @@ -209,14 +216,16 @@ extension AWSIncomingEventReconciliationQueue: DefaultLogger { extension AWSIncomingEventReconciliationQueue { static let factory: IncomingEventReconciliationQueueFactory = { modelSchemas, api, storageAdapter, syncExpressions, auth, authModeStrategy, _, disableSubscriptions in - await AWSIncomingEventReconciliationQueue(modelSchemas: modelSchemas, - api: api, - storageAdapter: storageAdapter, - syncExpressions: syncExpressions, - auth: auth, - authModeStrategy: authModeStrategy, - modelReconciliationQueueFactory: nil, - disableSubscriptions: disableSubscriptions) + await AWSIncomingEventReconciliationQueue( + modelSchemas: modelSchemas, + api: api, + storageAdapter: storageAdapter, + syncExpressions: syncExpressions, + auth: auth, + authModeStrategy: authModeStrategy, + modelReconciliationQueueFactory: nil, + disableSubscriptions: disableSubscriptions + ) } } @@ -237,7 +246,7 @@ extension AWSIncomingEventReconciliationQueue: Resettable { reconcileAndSaveQueue.cancelAllOperations() // Reset is used in internal testing only. Some operations get kicked off at this point and do not finish // We're sometimes hitting a deadlock when waiting for them to finish. Commenting this out and letting - // the tests continue onto the next works pretty well, but ideally ReconcileAndLocalSaveOperation's should + // the tests continue onto the next works pretty well, but ideally ReconcileAndLocalSaveOperation's should // always finish. We can uncomment this to explore a better fix that will still gives us test stability. // reconcileAndSaveQueue.waitUntilOperationsAreFinished() log.verbose("Resetting reconcileAndSaveQueue: finished") diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingSubscriptionEventPublisher.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingSubscriptionEventPublisher.swift index 76c4b7dc9a..69cd551e67 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingSubscriptionEventPublisher.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingSubscriptionEventPublisher.swift @@ -22,17 +22,21 @@ final class AWSIncomingSubscriptionEventPublisher: IncomingSubscriptionEventPubl return subscriptionEventSubject.eraseToAnyPublisher() } - init(modelSchema: ModelSchema, - api: APICategoryGraphQLBehavior, - modelPredicate: QueryPredicate?, - auth: AuthCategoryBehavior?, - authModeStrategy: AuthModeStrategy) async { + init( + modelSchema: ModelSchema, + api: APICategoryGraphQLBehavior, + modelPredicate: QueryPredicate?, + auth: AuthCategoryBehavior?, + authModeStrategy: AuthModeStrategy + ) async { self.subscriptionEventSubject = PassthroughSubject() - self.asyncEvents = await IncomingAsyncSubscriptionEventPublisher(modelSchema: modelSchema, - api: api, - modelPredicate: modelPredicate, - auth: auth, - authModeStrategy: authModeStrategy) + self.asyncEvents = await IncomingAsyncSubscriptionEventPublisher( + modelSchema: modelSchema, + api: api, + modelPredicate: modelPredicate, + auth: auth, + authModeStrategy: authModeStrategy + ) self.mapper = IncomingAsyncSubscriptionEventToAnyModelMapper() asyncEvents.subscribe(subscriber: mapper) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisher.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisher.swift index e9a89800dd..33850ed97d 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisher.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisher.swift @@ -47,12 +47,14 @@ final class IncomingAsyncSubscriptionEventPublisher: AmplifyCancellable { private let taskQueue: TaskQueue private let modelName: ModelName - init(modelSchema: ModelSchema, - api: APICategoryGraphQLBehavior, - modelPredicate: QueryPredicate?, - auth: AuthCategoryBehavior?, - authModeStrategy: AuthModeStrategy, - awsAuthService: AWSAuthServiceBehavior? = nil) async { + init( + modelSchema: ModelSchema, + api: APICategoryGraphQLBehavior, + modelPredicate: QueryPredicate?, + auth: AuthCategoryBehavior?, + authModeStrategy: AuthModeStrategy, + awsAuthService: AWSAuthServiceBehavior? = nil + ) async { self.onCreateConnected = false self.onUpdateConnected = false self.onDeleteConnected = false @@ -126,20 +128,20 @@ final class IncomingAsyncSubscriptionEventPublisher: AmplifyCancellable { return RetryableGraphQLSubscriptionOperation( requestStream: AsyncStream { continuation in for authType in authTypeProvider { - continuation.yield({ [weak self] in + continuation.yield { [weak self] in guard let self else { throw APIError.operationError("GraphQL subscription cancelled", "") } - return api.subscribe(request: await IncomingAsyncSubscriptionEventPublisher.makeAPIRequest( + return await api.subscribe(request: IncomingAsyncSubscriptionEventPublisher.makeAPIRequest( for: modelSchema, subscriptionType: subscriptionType.subscriptionType, api: api, auth: auth, authType: authType.awsAuthType, - awsAuthService: self.awsAuthService + awsAuthService: awsAuthService )) - }) + } } continuation.finish() } @@ -206,33 +208,41 @@ final class IncomingAsyncSubscriptionEventPublisher: AmplifyCancellable { } } - static func makeAPIRequest(for modelSchema: ModelSchema, - subscriptionType: GraphQLSubscriptionType, - api: APICategoryGraphQLBehavior, - auth: AuthCategoryBehavior?, - authType: AWSAuthorizationType?, - awsAuthService: AWSAuthServiceBehavior) async -> GraphQLRequest { + static func makeAPIRequest( + for modelSchema: ModelSchema, + subscriptionType: GraphQLSubscriptionType, + api: APICategoryGraphQLBehavior, + auth: AuthCategoryBehavior?, + authType: AWSAuthorizationType?, + awsAuthService: AWSAuthServiceBehavior + ) async -> GraphQLRequest { let request: GraphQLRequest if modelSchema.hasAuthenticationRules, let _ = auth, let tokenString = try? await awsAuthService.getUserPoolAccessToken(), case .success(let claims) = awsAuthService.getTokenClaims(tokenString: tokenString) { - request = GraphQLRequest.subscription(to: modelSchema, - subscriptionType: subscriptionType, - claims: claims, - authType: authType) + request = GraphQLRequest.subscription( + to: modelSchema, + subscriptionType: subscriptionType, + claims: claims, + authType: authType + ) } else if modelSchema.hasAuthenticationRules, let oidcAuthProvider = hasOIDCAuthProviderAvailable(api: api), let tokenString = try? await oidcAuthProvider.getLatestAuthToken(), case .success(let claims) = awsAuthService.getTokenClaims(tokenString: tokenString) { - request = GraphQLRequest.subscription(to: modelSchema, - subscriptionType: subscriptionType, - claims: claims, - authType: authType) + request = GraphQLRequest.subscription( + to: modelSchema, + subscriptionType: subscriptionType, + claims: claims, + authType: authType + ) } else { - request = GraphQLRequest.subscription(to: modelSchema, - subscriptionType: subscriptionType, - authType: authType) + request = GraphQLRequest.subscription( + to: modelSchema, + subscriptionType: subscriptionType, + authType: authType + ) } return request @@ -253,14 +263,14 @@ final class IncomingAsyncSubscriptionEventPublisher: AmplifyCancellable { func send(_ event: Event) { taskQueue.async { [weak self] in guard let self else { return } - self.incomingSubscriptionEvents.send(event) + incomingSubscriptionEvents.send(event) } } func send(completion: Subscribers.Completion) { taskQueue.async { [weak self] in guard let self else { return } - self.incomingSubscriptionEvents.send(completion: completion) + incomingSubscriptionEvents.send(completion: completion) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/AWSModelReconciliationQueue.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/AWSModelReconciliationQueue.swift index 03074d82e3..f247b299e4 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/AWSModelReconciliationQueue.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/AWSModelReconciliationQueue.swift @@ -76,14 +76,16 @@ final class AWSModelReconciliationQueue: ModelReconciliationQueue { return modelReconciliationQueueSubject.eraseToAnyPublisher() } - init(modelSchema: ModelSchema, - storageAdapter: StorageEngineAdapter?, - api: APICategoryGraphQLBehavior, - reconcileAndSaveQueue: ReconcileAndSaveOperationQueue, - modelPredicate: QueryPredicate?, - auth: AuthCategoryBehavior?, - authModeStrategy: AuthModeStrategy, - incomingSubscriptionEvents: IncomingSubscriptionEventPublisher? = nil) async { + init( + modelSchema: ModelSchema, + storageAdapter: StorageEngineAdapter?, + api: APICategoryGraphQLBehavior, + reconcileAndSaveQueue: ReconcileAndSaveOperationQueue, + modelPredicate: QueryPredicate?, + auth: AuthCategoryBehavior?, + authModeStrategy: AuthModeStrategy, + incomingSubscriptionEvents: IncomingSubscriptionEventPublisher? = nil + ) async { self.modelSchema = modelSchema self.storageAdapter = storageAdapter @@ -100,7 +102,7 @@ final class AWSModelReconciliationQueue: ModelReconciliationQueue { incomingSubscriptionEventQueue.isSuspended = true let resolvedIncomingSubscriptionEvents: IncomingSubscriptionEventPublisher - if let incomingSubscriptionEvents = incomingSubscriptionEvents { + if let incomingSubscriptionEvents { resolvedIncomingSubscriptionEvents = incomingSubscriptionEvents } else { resolvedIncomingSubscriptionEvents = await AWSIncomingSubscriptionEventPublisher( @@ -150,29 +152,31 @@ final class AWSModelReconciliationQueue: ModelReconciliationQueue { return } - let reconcileOp = ReconcileAndLocalSaveOperation(modelSchema: modelSchema, - remoteModels: remoteModels, - storageAdapter: storageAdapter) + let reconcileOp = ReconcileAndLocalSaveOperation( + modelSchema: modelSchema, + remoteModels: remoteModels, + storageAdapter: storageAdapter + ) var reconcileAndLocalSaveOperationSink: AnyCancellable? reconcileAndLocalSaveOperationSink = reconcileOp .publisher .sink(receiveCompletion: { [weak self] completion in - guard let self = self else { + guard let self else { return } - self.reconcileAndLocalSaveOperationSinks.with { $0.remove(reconcileAndLocalSaveOperationSink) } + reconcileAndLocalSaveOperationSinks.with { $0.remove(reconcileAndLocalSaveOperationSink) } if case .failure = completion { - self.modelReconciliationQueueSubject.send(completion: completion) + modelReconciliationQueueSubject.send(completion: completion) } }, receiveValue: { [weak self] value in - guard let self = self else { + guard let self else { return } switch value { case .mutationEventDropped(let modelName, let error): - self.modelReconciliationQueueSubject.send(.mutationEventDropped(modelName: modelName, error: error)) + modelReconciliationQueueSubject.send(.mutationEventDropped(modelName: modelName, error: error)) case .mutationEvent(let event): - self.modelReconciliationQueueSubject.send(.mutationEvent(event)) + modelReconciliationQueueSubject.send(.mutationEvent(event)) } }) reconcileAndLocalSaveOperationSinks.with { $0.insert(reconcileAndLocalSaveOperationSink) } @@ -241,7 +245,7 @@ extension AWSModelReconciliationQueue: Resettable { if let resettable = incomingSubscriptionEvents as? Resettable { log.verbose("Resetting incomingSubscriptionEvents") await resettable.reset() - self.log.verbose("Resetting incomingSubscriptionEvents: finished") + log.verbose("Resetting incomingSubscriptionEvents: finished") } log.verbose("Resetting incomingSubscriptionEventQueue") @@ -285,7 +289,7 @@ extension AWSModelReconciliationQueue { } private func isOperationDisabledError(_ errorMessage: String?, _ error: Error?) -> Bool { - if let errorMessage = errorMessage, + if let errorMessage, case .operationDisabled = AppSyncErrorType(errorMessage) { return true } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation+Resolver.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation+Resolver.swift index a723b1195e..332b8a17a8 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation+Resolver.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation+Resolver.swift @@ -8,7 +8,7 @@ import Amplify extension ReconcileAndLocalSaveOperation { - struct Resolver { + enum Resolver { /// It's not absolutely required to make `resolve` a static, but it helps in two ways: /// 1. It makes it easier to avoid retain cycles, since the reducer can't close over the state machine's owning diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation.swift index 7ba4449c50..538adf5b0c 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore // swiftlint:disable type_body_length file_length /// Reconciles an incoming model mutation with the stored model. If there is no conflict (e.g., the incoming model has @@ -26,9 +26,11 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { /// sent from the remote API as part of the mutation. typealias AppliedModel = MutationSync - let id: UUID = UUID() - private let workQueue = DispatchQueue(label: "com.amazonaws.ReconcileAndLocalSaveOperation", - target: DispatchQueue.global()) + let id: UUID = .init() + private let workQueue = DispatchQueue( + label: "com.amazonaws.ReconcileAndLocalSaveOperation", + target: DispatchQueue.global() + ) private weak var storageAdapter: StorageEngineAdapter? private let stateMachine: StateMachine @@ -44,16 +46,20 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { var isEagerLoad: Bool = true - init(modelSchema: ModelSchema, - remoteModels: [RemoteModel], - storageAdapter: StorageEngineAdapter?, - stateMachine: StateMachine? = nil) { + init( + modelSchema: ModelSchema, + remoteModels: [RemoteModel], + storageAdapter: StorageEngineAdapter?, + stateMachine: StateMachine? = nil + ) { self.modelSchema = modelSchema self.remoteModels = remoteModels self.storageAdapter = storageAdapter self.stopwatch = Stopwatch() - self.stateMachine = stateMachine ?? StateMachine(initialState: .waiting, - resolver: Resolver.resolve(currentState:action:)) + self.stateMachine = stateMachine ?? StateMachine( + initialState: .waiting, + resolver: Resolver.resolve(currentState:action:) + ) self.mutationEventPublisher = PassthroughSubject() self.cancellables = Set() @@ -69,11 +75,11 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { self.stateMachineSink = self.stateMachine .$state .sink { [weak self] newState in - guard let self = self else { + guard let self else { return } - self.log.verbose("New state: \(newState)") - self.workQueue.async { + log.verbose("New state: \(newState)") + workQueue.async { self.respond(to: newState) } } @@ -128,7 +134,7 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { return } - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { let error = DataStoreError.nilStorageAdapter() notifyDropped(count: remoteModels.count, error: error) stateMachine.notify(action: .errored(error)) @@ -144,17 +150,17 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { try storageAdapter.transaction { self.queryLocalMetadata(remoteModels) .subscribe(on: workQueue) - .map { (remoteModels, localMetadatas) in + .map { remoteModels, localMetadatas in self.getDispositions(for: remoteModels, localMetadatas: localMetadatas) } .flatMap { dispositions in self.queryPendingMutations(withModels: dispositions.map(\.remoteModel.model)) .map { pendingMutations in (pendingMutations, dispositions) } } - .map { (pendingMutations, dispositions) in + .map { pendingMutations, dispositions in self.separateDispositions(pendingMutations: pendingMutations, dispositions: dispositions) } - .flatMap { (dispositions, dispositionOnlyApplyMetadata) in + .flatMap { dispositions, dispositionOnlyApplyMetadata in self.waitAllPublisherFinishes(publishers: dispositionOnlyApplyMetadata.map(self.saveMetadata(disposition:))) .flatMap { _ in self.applyRemoteModelsDispositions(dispositions) } } @@ -267,7 +273,8 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { do { let localMetadatas = try storageAdapter.queryMutationSyncMetadata( for: remoteModels.map { $0.model.identifier }, - modelName: self.modelSchema.name) + modelName: self.modelSchema.name + ) result = .success((remoteModels, localMetadatas)) } catch { let error = DataStoreError(error: error) @@ -278,14 +285,18 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { } } - func getDispositions(for remoteModels: [RemoteModel], - localMetadatas: [LocalMetadata]) -> [RemoteSyncReconciler.Disposition] { + func getDispositions( + for remoteModels: [RemoteModel], + localMetadatas: [LocalMetadata] + ) -> [RemoteSyncReconciler.Disposition] { guard !remoteModels.isEmpty else { return [] } - let dispositions = RemoteSyncReconciler.getDispositions(remoteModels, - localMetadatas: localMetadatas) + let dispositions = RemoteSyncReconciler.getDispositions( + remoteModels, + localMetadatas: localMetadatas + ) notifyDropped(count: remoteModels.count - dispositions.count) return dispositions } @@ -297,9 +308,9 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { let operation: Future switch disposition { case .create, .update: - operation = self.save(storageAdapter: storageAdapter, remoteModel: disposition.remoteModel) + operation = save(storageAdapter: storageAdapter, remoteModel: disposition.remoteModel) case .delete: - operation = self.delete(storageAdapter: storageAdapter, remoteModel: disposition.remoteModel) + operation = delete(storageAdapter: storageAdapter, remoteModel: disposition.remoteModel) } return operation @@ -314,14 +325,14 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { func applyRemoteModelsDispositions( _ dispositions: [RemoteSyncReconciler.Disposition] ) -> Future { - guard !self.isCancelled else { - self.log.info("\(#function) - cancelled, aborting") + guard !isCancelled else { + log.info("\(#function) - cancelled, aborting") return Future { $0(.successfulVoid) } } - guard let storageAdapter = self.storageAdapter else { + guard let storageAdapter else { let error = DataStoreError.nilStorageAdapter() - self.notifyDropped(count: dispositions.count, error: error) + notifyDropped(count: dispositions.count, error: error) return Future { $0(.failure(error)) } } @@ -333,7 +344,7 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { applyRemoteModelsDisposition(storageAdapter: storageAdapter, disposition: $0) } - return self.waitAllPublisherFinishes(publishers: publishers) + return waitAllPublisherFinishes(publishers: publishers) } enum ApplyRemoteModelResult { @@ -341,8 +352,10 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { case dropped } - private func delete(storageAdapter: StorageEngineAdapter, - remoteModel: RemoteModel) -> Future { + private func delete( + storageAdapter: StorageEngineAdapter, + remoteModel: RemoteModel + ) -> Future { Future { promise in guard let modelType = ModelRegistry.modelType(from: self.modelSchema.name) else { let error = DataStoreError.invalidModelName(self.modelSchema.name) @@ -350,10 +363,12 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { return } - storageAdapter.delete(untypedModelType: modelType, - modelSchema: self.modelSchema, - withIdentifier: remoteModel.model.identifier(schema: self.modelSchema), - condition: nil) { response in + storageAdapter.delete( + untypedModelType: modelType, + modelSchema: self.modelSchema, + withIdentifier: remoteModel.model.identifier(schema: self.modelSchema), + condition: nil + ) { response in switch response { case .failure(let dataStoreError): self.notifyDropped(error: dataStoreError) @@ -402,7 +417,7 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { private func saveMetadata( disposition: RemoteSyncReconciler.Disposition ) -> AnyPublisher { - guard let storageAdapter = self.storageAdapter else { + guard let storageAdapter else { return Just(()).eraseToAnyPublisher() } return saveMetadata(storageAdapter: storageAdapter, remoteModel: disposition.remoteModel, mutationType: disposition.mutationType) @@ -418,7 +433,7 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { ) -> AnyPublisher { switch result { case .applied(let remoteModel, let appliedModel): - return self.saveMetadata(storageAdapter: storageAdapter, remoteModel: remoteModel, mutationType: mutationType) + return saveMetadata(storageAdapter: storageAdapter, remoteModel: remoteModel, mutationType: mutationType) .map { MutationSync(model: appliedModel.model, syncMetadata: $0) } .map { [weak self] in self?.notify(appliedModel: $0, mutationType: mutationType) } .eraseToAnyPublisher() @@ -464,11 +479,13 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { } let modelIdentifier = appliedModel.model.instance.identifier(schema: modelSchema).stringValue - let mutationEvent = MutationEvent(modelId: modelIdentifier, - modelName: modelSchema.name, - json: json, - mutationType: mutationType, - version: appliedModel.syncMetadata.version) + let mutationEvent = MutationEvent( + modelId: modelIdentifier, + modelName: modelSchema.name, + json: json, + mutationType: mutationType, + version: appliedModel.syncMetadata.version + ) mutationEventPublisher.send(.mutationEvent(mutationEvent)) } @@ -486,14 +503,18 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { } let modelIdentifier = remoteModel.model.instance.identifier(schema: modelSchema).stringValue - let mutationEvent = MutationEvent(modelId: modelIdentifier, - modelName: modelSchema.name, - json: json, - mutationType: mutationType, - version: remoteModel.syncMetadata.version) - - let payload = HubPayload(eventName: HubPayload.EventName.DataStore.syncReceived, - data: mutationEvent) + let mutationEvent = MutationEvent( + modelId: modelIdentifier, + modelName: modelSchema.name, + json: json, + mutationType: mutationType, + version: remoteModel.syncMetadata.version + ) + + let payload = HubPayload( + eventName: HubPayload.EventName.DataStore.syncReceived, + data: mutationEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: payload) } @@ -509,7 +530,7 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { .unknown("\(name) did not fulfill promise", AmplifyErrorMessages.shouldNotHappenReportBugToAWS(), nil) } - private func waitAllPublisherFinishes(publishers: [AnyPublisher]) -> Future { + private func waitAllPublisherFinishes(publishers: [AnyPublisher]) -> Future { Future { promise in Publishers.MergeMany(publishers) .collect() diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveQueue.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveQueue.swift index 30434dc04e..a8334eea0a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveQueue.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveQueue.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore protocol ReconcileAndSaveOperationQueue { func addOperation(_ operation: ReconcileAndLocalSaveOperation, modelName: String) @@ -43,8 +43,10 @@ enum ReconcileAndSaveQueueEvent { /// continue to operate. class ReconcileAndSaveQueue: ReconcileAndSaveOperationQueue { - private let serialQueue = DispatchQueue(label: "com.amazonaws.ReconcileAndSaveQueue.serialQueue", - target: DispatchQueue.global()) + private let serialQueue = DispatchQueue( + label: "com.amazonaws.ReconcileAndSaveQueue.serialQueue", + target: DispatchQueue.global() + ) private let reconcileAndSaveQueue: OperationQueue private var modelReconcileAndSaveOperations: [String: [UUID: ReconcileAndLocalSaveOperation]] private var reconcileAndLocalSaveOperationSinks: AtomicValue> @@ -90,7 +92,7 @@ class ReconcileAndSaveQueue: ReconcileAndSaveOperationQueue { func cancelOperations(modelName: String) { serialQueue.async { if let operations = self.modelReconcileAndSaveOperations[modelName] { - operations.values.forEach { operation in + for operation in operations.values { operation.cancel() } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/RemoteSyncReconciler.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/RemoteSyncReconciler.swift index df95b21a8a..7c006b4f92 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/RemoteSyncReconciler.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/RemoteSyncReconciler.swift @@ -8,7 +8,7 @@ import Amplify /// Reconciles incoming sync mutations with the state of the local store, and mutation queue. -struct RemoteSyncReconciler { +enum RemoteSyncReconciler { typealias LocalMetadata = ReconcileAndLocalSaveOperation.LocalMetadata typealias RemoteModel = ReconcileAndLocalSaveOperation.RemoteModel @@ -50,24 +50,24 @@ struct RemoteSyncReconciler { $1.model.identifier: ($0[$1.model.identifier] ?? []) + [$1] ], uniquingKeysWith: { $1 }) } - + let optimizedRemoteModels = remoteModelsGroupByIdentifier.values.compactMap { $0.sorted(by: { $0.syncMetadata.version > $1.syncMetadata.version }).first } - + guard !optimizedRemoteModels.isEmpty else { return [] } - + guard !localMetadatas.isEmpty else { return optimizedRemoteModels.compactMap { getDisposition($0, localMetadata: nil) } } - + let metadataByModelId = localMetadatas.reduce(into: [:]) { $0[$1.modelId] = $1 } let dispositions = optimizedRemoteModels.compactMap { getDisposition($0, localMetadata: metadataByModelId[$0.model.identifier]) } - + return dispositions } @@ -85,7 +85,7 @@ struct RemoteSyncReconciler { /// - localMetadata: metadata corresponding to the remote model /// - Returns: disposition of the model, `nil` if to be dropped static func getDisposition(_ remoteModel: RemoteModel, localMetadata: LocalMetadata?) -> Disposition? { - guard let localMetadata = localMetadata else { + guard let localMetadata else { return remoteModel.syncMetadata.deleted ? nil : .create(remoteModel) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/DataStoreError+Plugin.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/DataStoreError+Plugin.swift index 812501bacc..346376521a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/DataStoreError+Plugin.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/DataStoreError+Plugin.swift @@ -10,9 +10,11 @@ import Amplify /// Convenience error types extension DataStoreError { - static func nilAPIHandle(file: StaticString = #file, - function: StaticString = #function, - line: UInt = #line) -> DataStoreError { + static func nilAPIHandle( + file: StaticString = #file, + function: StaticString = #function, + line: UInt = #line + ) -> DataStoreError { .internalOperation( "The reference to Amplify API is unexpectedly nil in an internal operation", """ @@ -23,9 +25,11 @@ extension DataStoreError { ) } - static func nilReconciliationQueue(file: StaticString = #file, - function: StaticString = #function, - line: UInt = #line) -> DataStoreError { + static func nilReconciliationQueue( + file: StaticString = #file, + function: StaticString = #function, + line: UInt = #line + ) -> DataStoreError { .internalOperation( "The reference to IncomingEventReconciliationQueue is unexpectedly nil in an internal operation", """ @@ -37,9 +41,11 @@ extension DataStoreError { ) } - static func nilStorageAdapter(file: StaticString = #file, - function: StaticString = #function, - line: UInt = #line) -> DataStoreError { + static func nilStorageAdapter( + file: StaticString = #file, + function: StaticString = #function, + line: UInt = #line + ) -> DataStoreError { .internalOperation( "storageAdapter is unexpectedly nil in an internal operation", """ diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Model+Compare.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Model+Compare.swift index ca9595dbf1..5a7c8cf4bd 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Model+Compare.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Model+Compare.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation // swiftlint:disable cyclomatic_complexity extension ModelSchema { @@ -113,15 +113,18 @@ extension ModelSchema { return false } case .enum: + // swiftformat:disable typeSugar // swiftlint:disable syntactic_sugar guard case .some(Optional.some(let value1Optional)) = value1, - case .some(Optional.some(let value2Optional)) = value2 else { + case .some(Optional.some(let value2Optional)) = value2 + else { if value1 == nil && value2 == nil { continue } return false } // swiftlint:enable syntactic_sugar + // swiftformat:enable typeSugar let enumValue1Optional = (value1Optional as? EnumPersistable)?.rawValue let enumValue2Optional = (value2Optional as? EnumPersistable)?.rawValue if !compare(enumValue1Optional, enumValue2Optional) { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Extensions.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Extensions.swift index 7d2057528e..6b9900f136 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Extensions.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Extensions.swift @@ -6,8 +6,8 @@ // import Amplify -import Dispatch import AWSPluginsCore +import Dispatch extension MutationEvent { // Consecutive operations that modify a model results in a sequence of pending mutation events that @@ -35,10 +35,12 @@ extension MutationEvent { // For a given model `id`, checks the version of the head of pending mutation event queue // against the API response version in `mutationSync` and saves it in the mutation event table if // the response version is a newer one - static func reconcilePendingMutationEventsVersion(sent mutationEvent: MutationEvent, - received mutationSync: MutationSync, - storageAdapter: StorageEngineAdapter, - completion: @escaping DataStoreCallback) { + static func reconcilePendingMutationEventsVersion( + sent mutationEvent: MutationEvent, + received mutationSync: MutationSync, + storageAdapter: StorageEngineAdapter, + completion: @escaping DataStoreCallback + ) { MutationEvent.pendingMutationEvents( forMutationEvent: mutationEvent, storageAdapter: storageAdapter @@ -52,9 +54,11 @@ extension MutationEvent { return } - guard let reconciledEvent = reconcile(pendingMutationEvent: existingEvent, - with: mutationEvent, - responseMutationSync: mutationSync) else { + guard let reconciledEvent = reconcile( + pendingMutationEvent: existingEvent, + with: mutationEvent, + responseMutationSync: mutationSync + ) else { completion(.success(())) return } @@ -71,9 +75,11 @@ extension MutationEvent { } } - static func reconcile(pendingMutationEvent: MutationEvent, - with requestMutationEvent: MutationEvent, - responseMutationSync: MutationSync) -> MutationEvent? { + static func reconcile( + pendingMutationEvent: MutationEvent, + with requestMutationEvent: MutationEvent, + responseMutationSync: MutationSync + ) -> MutationEvent? { // return if version of the pending mutation event is not nil and // is >= version contained in the response if pendingMutationEvent.version != nil && diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Query.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Query.swift index d84dad4ce7..b84665f1de 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Query.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Query.swift @@ -57,9 +57,11 @@ extension MutationEvent { ) } - private static func pendingMutationEvents(for modelIds: [(String, String)], - storageAdapter: StorageEngineAdapter, - completion: @escaping DataStoreCallback<[MutationEvent]>) { + private static func pendingMutationEvents( + for modelIds: [(String, String)], + storageAdapter: StorageEngineAdapter, + completion: @escaping DataStoreCallback<[MutationEvent]> + ) { Task { let fields = MutationEvent.keys let predicate = (fields.inProcess == false || fields.inProcess == nil) @@ -77,11 +79,13 @@ extension MutationEvent { do { let mutationEvents = try await withCheckedThrowingContinuation { continuation in - storageAdapter.query(MutationEvent.self, - predicate: final, - sort: [sort], - paginationInput: nil, - eagerLoad: true) { result in + storageAdapter.query( + MutationEvent.self, + predicate: final, + sort: [sort], + paginationInput: nil, + eagerLoad: true + ) { result in continuation.resume(with: result) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/SQLiteResultError.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/SQLiteResultError.swift index 60f1ba14d5..ec57fc6b3a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/SQLiteResultError.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/SQLiteResultError.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import SQLite import SQLite3 -import Amplify /// Checks for specific SQLLite error codes /// See https://sqlite.org/rescode.html#primary_result_code_list @@ -28,7 +28,8 @@ enum SQLiteResultError { init?(from dataStoreError: DataStoreError) { guard case let .invalidOperation(error) = dataStoreError, let resultError = error as? Result, - case .error(let message, let code, let statement) = resultError else { + case .error(let message, let code, let statement) = resultError + else { return nil } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/StateMachine.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/StateMachine.swift index 55855b1959..8b9b83c140 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/StateMachine.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/StateMachine.swift @@ -12,8 +12,10 @@ import Foundation class StateMachine { typealias Reducer = (State, Action) -> State - private let queue = DispatchQueue(label: "com.amazonaws.Amplify.StateMachine<\(State.self), \(Action.self)>", - target: DispatchQueue.global()) + private let queue = DispatchQueue( + label: "com.amazonaws.Amplify.StateMachine<\(State.self), \(Action.self)>", + target: DispatchQueue.global() + ) private var reducer: Reducer @Published var state: State diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Stopwatch.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Stopwatch.swift index c2e0111944..58032907b9 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Stopwatch.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Stopwatch.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// A simple implementation of a stopwatch used for gathering metrics of elapsed time. class Stopwatch { @@ -28,7 +28,7 @@ class Stopwatch { /// - Returns: the elapsed time in seconds func lap() -> Double { lock.execute { - guard let lapStart = lapStart else { + guard let lapStart else { return 0 } @@ -50,7 +50,7 @@ class Stopwatch { startTime = nil } - guard let startTime = startTime else { + guard let startTime else { return 0 } let endTime = DispatchTime.now() diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStoreLocalStoreTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStoreLocalStoreTests.swift index 32a80b1735..2e7a2335c9 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStoreLocalStoreTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStoreLocalStoreTests.swift @@ -7,8 +7,8 @@ import XCTest -import AWSPluginsCore import AmplifyTestCommon +import AWSPluginsCore @testable import Amplify @testable import AWSDataStorePlugin @@ -40,7 +40,7 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { let post = Post.keys let predicate = (post.id <= 1 && post.title == "title1") || (post.rating > 2 && post.status == PostStatus.private) - + let queriedPosts = try await Amplify.DataStore.query(Post.self, where: predicate) XCTAssertEqual(queriedPosts.count, 2) } @@ -59,11 +59,11 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { let queriedPosts = try await Amplify.DataStore.query(Post.self, paginate: .page(0, limit: 10)) XCTAssertEqual(queriedPosts.count, 10) posts.append(contentsOf: queriedPosts) - + let queriedPosts2 = try await Amplify.DataStore.query(Post.self, paginate: .page(1, limit: 10)) XCTAssertEqual(queriedPosts2.count, 5) posts.append(contentsOf: queriedPosts2) - + let idSet = Set(posts.map { $0.id }) XCTAssertEqual(idSet.count, 15) } @@ -103,9 +103,13 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { setUp(withModels: TestModelRegistration()) _ = try await setUpLocalStore(numberOfPosts: 50) - let posts = try await Amplify.DataStore.query(Post.self, - sort: .by(.ascending(Post.keys.rating), - .descending(Post.keys.title))) + let posts = try await Amplify.DataStore.query( + Post.self, + sort: .by( + .ascending(Post.keys.rating), + .descending(Post.keys.title) + ) + ) var previousRating: Double = 0 for post in posts { guard let rating = post.rating else { @@ -141,9 +145,11 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { setUp(withModels: TestModelRegistration()) _ = try await setUpLocalStore(numberOfPosts: 20) - let posts = try await Amplify.DataStore.query(Post.self, - where: Post.keys.rating >= 2, - sort: .ascending(Post.keys.rating)) + let posts = try await Amplify.DataStore.query( + Post.self, + where: Post.keys.rating >= 2, + sort: .ascending(Post.keys.rating) + ) var previousRating: Double = 0 for post in posts { @@ -170,10 +176,14 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { func testQueryWithSortAndPagintate() async throws { setUp(withModels: TestModelRegistration()) _ = try await setUpLocalStore(numberOfPosts: 20) - let posts = try await Amplify.DataStore.query(Post.self, - sort: .by(.ascending(Post.keys.rating), - .descending(Post.keys.title)), - paginate: .page(0, limit: 10)) + let posts = try await Amplify.DataStore.query( + Post.self, + sort: .by( + .ascending(Post.keys.rating), + .descending(Post.keys.title) + ), + paginate: .page(0, limit: 10) + ) XCTAssertEqual(posts.count, 10) var previousRating: Double = 0 @@ -201,10 +211,12 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { let filteredPosts = localPosts.filter { $0.rating! >= 2.0 } let count = filteredPosts.count - let posts = try await Amplify.DataStore.query(Post.self, - where: Post.keys.rating >= 2, - sort: .ascending(Post.keys.rating), - paginate: .page(0, limit: 10)) + let posts = try await Amplify.DataStore.query( + Post.self, + where: Post.keys.rating >= 2, + sort: .ascending(Post.keys.rating), + paginate: .page(0, limit: 10) + ) if count >= 10 { XCTAssertEqual(posts.count, 10) } else { @@ -237,17 +249,21 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { setUp(withModels: TestModelRegistration()) _ = try await setUpLocalStore(numberOfPosts: 50) - let queriedPosts = try await Amplify.DataStore.query(Post.self, - where: Post.keys.rating >= 2) - + let queriedPosts = try await Amplify.DataStore.query( + Post.self, + where: Post.keys.rating >= 2 + ) + var posts = [Post]() var currentPage: UInt = 0 var shouldRepeat = true repeat { - let returnPosts = try await Amplify.DataStore.query(Post.self, - where: Post.keys.rating >= 2, - sort: .ascending(Post.keys.rating), - paginate: .page(currentPage, limit: 10)) + let returnPosts = try await Amplify.DataStore.query( + Post.self, + where: Post.keys.rating >= 2, + sort: .ascending(Post.keys.rating), + paginate: .page(currentPage, limit: 10) + ) posts.append(contentsOf: returnPosts) if returnPosts.count == 10 { currentPage += 1 @@ -420,7 +436,7 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { let posts = try await Amplify.DataStore.query(Post.self) XCTAssertEqual(posts.count, numberOfPosts) - let randomTitleNumber = String(Int.random(in: 0.. [Post] { - let posts = (0...self, from: data) + let result = try decoder.decode(DataStoreListDecoderHarness.self, from: data) XCTAssertNil(result.listProvider) } @@ -90,14 +90,14 @@ class DataStoreListDecoderTests: BaseDataStoreTests { "associatedId": "123" ] let data = try encoder.encode(json) - let result = try self.decoder.decode(DataStoreListDecoderHarness.self, from: data) + let result = try decoder.decode(DataStoreListDecoderHarness.self, from: data) XCTAssertNil(result.listProvider) } func testDataStoreListDecoderShouldNotDecodeJSONString() throws { let json: JSONValue = "JSONString" let data = try encoder.encode(json) - let result = try self.decoder.decode(DataStoreListDecoderHarness.self, from: data) + let result = try decoder.decode(DataStoreListDecoderHarness.self, from: data) XCTAssertNil(result.listProvider) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderFunctionalTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderFunctionalTests.swift index 689448904d..5643738052 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderFunctionalTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderFunctionalTests.swift @@ -16,8 +16,10 @@ class DataStoreListProviderFunctionalTests: BaseDataStoreTests { func testDataStoreListProviderWithAssociationDataShouldLoad() async throws { let postId = preparePost4DataForTest() - let provider = DataStoreListProvider(metadata: .init(dataStoreAssociatedIdentifiers: [postId], - dataStoreAssociatedFields: ["post"])) + let provider = DataStoreListProvider(metadata: .init( + dataStoreAssociatedIdentifiers: [postId], + dataStoreAssociatedFields: ["post"] + )) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") return diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderTests.swift index d2539c4193..6d9035947f 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderTests.swift @@ -48,8 +48,10 @@ class DataStoreListProviderTests: XCTestCase { } func testInitWithAssociationDataShouldBeInNotLoadedState() { - let provider = DataStoreListProvider(metadata: .init(dataStoreAssociatedIdentifiers: ["id"], - dataStoreAssociatedFields: ["field"])) + let provider = DataStoreListProvider(metadata: .init( + dataStoreAssociatedIdentifiers: ["id"], + dataStoreAssociatedFields: ["field"] + )) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") return @@ -59,12 +61,16 @@ class DataStoreListProviderTests: XCTestCase { func testNotLoadedStateLoadSuccess() async throws { mockDataStorePlugin.responders[.queryModelsListener] = QueryModelsResponder { _, _, _, _ in - return .success([Comment4(content: "content"), - Comment4(content: "content")]) + return .success([ + Comment4(content: "content"), + Comment4(content: "content") + ]) } - let provider = DataStoreListProvider(metadata: .init(dataStoreAssociatedIdentifiers: ["postId"], - dataStoreAssociatedFields: ["post"])) + let provider = DataStoreListProvider(metadata: .init( + dataStoreAssociatedIdentifiers: ["postId"], + dataStoreAssociatedFields: ["post"] + )) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") return @@ -85,7 +91,7 @@ class DataStoreListProviderTests: XCTestCase { XCTFail("Should be loaded") return } - + let results = try await listProvider.load() XCTAssertEqual(results.count, 2) } @@ -95,9 +101,11 @@ class DataStoreListProviderTests: XCTestCase { QueryModelsResponder { _, _, _, _ in return .failure(DataStoreError.internalOperation("", "", nil)) } - - let provider = DataStoreListProvider(metadata: .init(dataStoreAssociatedIdentifiers: ["postId"], - dataStoreAssociatedFields: ["post"])) + + let provider = DataStoreListProvider(metadata: .init( + dataStoreAssociatedIdentifiers: ["postId"], + dataStoreAssociatedFields: ["post"] + )) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") return diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/QueryPredicateTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/QueryPredicateTests.swift index 77bd4cea56..aeff126f93 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/QueryPredicateTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/QueryPredicateTests.swift @@ -19,11 +19,11 @@ class QueryPredicateTests: XCTestCase { encoder.outputFormatting = [.sortedKeys] return encoder }() - + var encoder: JSONEncoder { _encoder } - + /// it should create a simple `QueryPredicateOperation` func testSingleQueryPredicateOperation() { let post = Post.keys @@ -47,7 +47,7 @@ class QueryPredicateTests: XCTestCase { ) XCTAssertEqual(predicate, expected) - + let predicateString = String(data: try! encoder.encode(predicate), encoding: .utf8)! let expectedString = String(data: try! encoder.encode(expected), encoding: .utf8)! XCTAssert(predicateString == expectedString) @@ -83,7 +83,7 @@ class QueryPredicateTests: XCTestCase { ] ) XCTAssert(predicate == expected) - + let predicateString = String(data: try! encoder.encode(predicate), encoding: .utf8)! let expectedString = String(data: try! encoder.encode(expected), encoding: .utf8)! XCTAssert(predicateString == expectedString) @@ -163,7 +163,7 @@ class QueryPredicateTests: XCTestCase { && !(post.updatedAt == nil) XCTAssertEqual(funcationPredicate, operatorPredicate) - + let funcationPredicateString = String(data: try! encoder.encode(funcationPredicate), encoding: .utf8)! let operatorPredicateString = String(data: try! encoder.encode(operatorPredicate), encoding: .utf8)! XCTAssert(funcationPredicateString == operatorPredicateString) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLStatementTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLStatementTests.swift index 149edd2edb..68aece95e8 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLStatementTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLStatementTests.swift @@ -289,10 +289,12 @@ class SQLStatementTests: XCTestCase { /// - check if the generated SQL statement is valid /// - check if the variables match the expected values func testInsertStatementFromModel() { - let post = Post(title: "title", - content: "content", - createdAt: .now(), - status: .draft) + let post = Post( + title: "title", + content: "content", + createdAt: .now(), + status: .draft + ) let statement = InsertStatement(model: post, modelSchema: post.schema) let expectedStatement = """ @@ -317,9 +319,11 @@ class SQLStatementTests: XCTestCase { let modelId = "the-id" let dob = Temporal.DateTime.now() - let model = ModelCompositePk(id: modelId, - dob: dob, - name: "the-name") + let model = ModelCompositePk( + id: modelId, + dob: dob, + name: "the-name" + ) let statement = InsertStatement(model: model, modelSchema: model.schema) let expectedStatement = """ @@ -368,13 +372,17 @@ class SQLStatementTests: XCTestCase { /// - check if the variables match the expected values /// - check if the foreign key matches `ModelCompositePkWithAssociation` PK func testInsertStatementModelWithCompositeKeyAndHasManyBidirectional() { - let parentModel = ModelCompositePkWithAssociation(id: "parent-id", - dob: .now(), - name: "parent-name") - let childModel = ModelCompositePkBelongsTo(id: "child-id", - dob: .now(), - name: "child-name", - owner: parentModel) + let parentModel = ModelCompositePkWithAssociation( + id: "parent-id", + dob: .now(), + name: "parent-name" + ) + let childModel = ModelCompositePkBelongsTo( + id: "child-id", + dob: .now(), + name: "child-name", + owner: parentModel + ) let statement = InsertStatement(model: childModel, modelSchema: childModel.schema) @@ -402,9 +410,11 @@ class SQLStatementTests: XCTestCase { /// - check if the foreign key matches `PostWithCompositeKey` PK func testInsertStatementModelWithCompositeKeyAndHasManyBidirectional2() { let parentModel = PostWithCompositeKey(id: "post-id", title: "post-title") - let childModel = CommentWithCompositeKey(id: "comment-id", - content: "content", - post: parentModel) + let childModel = CommentWithCompositeKey( + id: "comment-id", + content: "content", + post: parentModel + ) let statement = InsertStatement(model: childModel, modelSchema: childModel.schema) @@ -494,9 +504,11 @@ class SQLStatementTests: XCTestCase { func testUpdateStatementFromModelWithDefinedCustomPK() { let modelId = "the-id" let dob = Temporal.DateTime.now() - let model = ModelCustomPkDefined(id: modelId, - dob: dob, - name: "the-name") + let model = ModelCustomPkDefined( + id: modelId, + dob: dob, + name: "the-name" + ) let statement = UpdateStatement(model: model, modelSchema: model.schema) let expectedStatement = """ update "ModelCustomPkDefined" @@ -526,9 +538,11 @@ class SQLStatementTests: XCTestCase { func testUpdateStatementFromModelWithCustomPKBasedOnIndexes() { let modelId = "the-id" let dob = Temporal.DateTime.now() - let model = ModelCompositePk(id: modelId, - dob: dob, - name: "the-name") + let model = ModelCompositePk( + id: modelId, + dob: dob, + name: "the-name" + ) let statement = UpdateStatement(model: model, modelSchema: model.schema) let expectedStatement = """ update "ModelCompositePk" @@ -559,9 +573,11 @@ class SQLStatementTests: XCTestCase { /// - check if the variables match the expected values func testDeleteStatementFromModel() { let id = UUID().uuidString - let statement = DeleteStatement(Post.self, - modelSchema: Post.schema, - withId: id) + let statement = DeleteStatement( + Post.self, + modelSchema: Post.schema, + withId: id + ) let expectedStatement = """ delete from "Post" as root @@ -582,10 +598,12 @@ class SQLStatementTests: XCTestCase { /// - check if the variables match the expected values func testDeleteStatementFromModelWithCondition() { let id = UUID().uuidString - let statement = DeleteStatement(Post.self, - modelSchema: Post.schema, - withId: id, - predicate: Post.keys.content == "content") + let statement = DeleteStatement( + Post.self, + modelSchema: Post.schema, + withId: id, + predicate: Post.keys.content == "content" + ) let expectedStatement = """ delete from "Post" as root @@ -610,8 +628,10 @@ class SQLStatementTests: XCTestCase { /// - check if the variables match the expected values func testDeleteStatementFromModelWithCustomPK() { let identifier = ModelExplicitCustomPk.IdentifierProtocol.identifier(userId: "userId") - let statement = DeleteStatement(modelSchema: ModelExplicitCustomPk.schema, - withIdentifier: identifier) + let statement = DeleteStatement( + modelSchema: ModelExplicitCustomPk.schema, + withIdentifier: identifier + ) let expectedStatement = """ delete from "ModelExplicitCustomPk" as root @@ -631,10 +651,14 @@ class SQLStatementTests: XCTestCase { /// - check if the generated SQL statement is valid /// - check if the variables match the expected values func testDeleteStatementFromModelWithCompositePK() { - let identifier = ModelCompositePk.IdentifierProtocol.identifier(id: "id", - dob: Temporal.DateTime.now()) - let statement = DeleteStatement(modelSchema: ModelCompositePk.schema, - withIdentifier: identifier) + let identifier = ModelCompositePk.IdentifierProtocol.identifier( + id: "id", + dob: Temporal.DateTime.now() + ) + let statement = DeleteStatement( + modelSchema: ModelCompositePk.schema, + withIdentifier: identifier + ) let expectedStatement = """ delete from "ModelCompositePk" as root @@ -721,8 +745,10 @@ class SQLStatementTests: XCTestCase { let keys = ModelCompositePk.keys let modelId = "an-id" let dob = "2022-02-22" - let statement = SelectStatement(from: ModelCompositePk.schema, - predicate: keys.id == modelId && keys.dob == dob) + let statement = SelectStatement( + from: ModelCompositePk.schema, + predicate: keys.id == modelId && keys.dob == dob + ) let expectedStatement = """ select "root"."@@primaryKey" as "@@primaryKey", "root"."id" as "id", "root"."dob" as "dob", @@ -857,8 +883,10 @@ class SQLStatementTests: XCTestCase { func testSelectStatementWithTwoFieldsSort() { let ascSort = QuerySortDescriptor(fieldName: Post.keys.id.stringValue, order: .ascending) let dscSort = QuerySortDescriptor(fieldName: Post.keys.createdAt.stringValue, order: .descending) - let statement = SelectStatement(from: Post.schema, - sort: [ascSort, dscSort]) + let statement = SelectStatement( + from: Post.schema, + sort: [ascSort, dscSort] + ) let expectedStatement = """ select "root"."id" as "id", "root"."content" as "content", "root"."createdAt" as "createdAt", @@ -879,9 +907,11 @@ class SQLStatementTests: XCTestCase { /// - check if the statement contains the correct `where` statement, `order by` and `ascending` func testSelectStatementWithPredicateAndSort() { let sort = QuerySortDescriptor(fieldName: Post.keys.id.stringValue, order: .descending) - let statement = SelectStatement(from: Post.schema, - predicate: Post.keys.rating > 4, - sort: [sort]) + let statement = SelectStatement( + from: Post.schema, + predicate: Post.keys.rating > 4, + sort: [sort] + ) let expectedStatement = """ select "root"."id" as "id", "root"."content" as "content", "root"."createdAt" as "createdAt", @@ -905,9 +935,11 @@ class SQLStatementTests: XCTestCase { /// - check if the statement contains the correct `where` statement, `order by` and `ascending` func testSelectStatementWithSortAndPaginationInfo() { let sort = QuerySortDescriptor(fieldName: Post.keys.id.stringValue, order: .descending) - let statement = SelectStatement(from: Post.schema, - sort: [sort], - paginationInput: .page(0, limit: 5)) + let statement = SelectStatement( + from: Post.schema, + sort: [sort], + paginationInput: .page(0, limit: 5) + ) let expectedStatement = """ select "root"."id" as "id", "root"."content" as "content", "root"."createdAt" as "createdAt", @@ -931,10 +963,12 @@ class SQLStatementTests: XCTestCase { /// - check if the statement contains the correct `where` statement, `order by` and `ascending` func testSelectStatementWithPredicateAndSortAndPaginationInfo() { let sort = QuerySortDescriptor(fieldName: Post.keys.id.stringValue, order: .descending) - let statement = SelectStatement(from: Post.schema, - predicate: Post.keys.rating > 4, - sort: [sort], - paginationInput: .page(0, limit: 5)) + let statement = SelectStatement( + from: Post.schema, + predicate: Post.keys.rating > 4, + sort: [sort], + paginationInput: .page(0, limit: 5) + ) let expectedStatement = """ select "root"."id" as "id", "root"."content" as "content", "root"."createdAt" as "createdAt", @@ -1023,15 +1057,17 @@ class SQLStatementTests: XCTestCase { /// - it matches the SQL condition func testTranslateQueryPredicateOperations() { - func assertPredicate(_ predicate: QueryPredicate, - matches sql: String, - bindings: [Binding?]? = nil) { + func assertPredicate( + _ predicate: QueryPredicate, + matches sql: String, + bindings: [Binding?]? = nil + ) { let statement = ConditionStatement(modelSchema: Post.schema, predicate: predicate, namespace: "root") XCTAssertEqual(statement.stringValue, " and \(sql)") - if let bindings = bindings { + if let bindings { XCTAssertEqual(bindings.count, statement.variables.count) - bindings.enumerated().forEach { - if let one = $0.element, let other = statement.variables[$0.offset] { + for binding in bindings.enumerated() { + if let one = binding.element, let other = statement.variables[binding.offset] { // TODO find better way to test `Binding` equality XCTAssertEqual(String(describing: one), String(describing: other)) } @@ -1048,15 +1084,21 @@ class SQLStatementTests: XCTestCase { assertPredicate(post.rating >= 1, matches: "\"root\".\"rating\" >= ?", bindings: [1]) assertPredicate(post.rating < 2, matches: "\"root\".\"rating\" < ?", bindings: [2]) assertPredicate(post.rating <= 3, matches: "\"root\".\"rating\" <= ?", bindings: [3]) - assertPredicate(post.rating.between(start: 3, end: 5), - matches: "\"root\".\"rating\" between ? and ?", - bindings: [3, 5]) - assertPredicate(post.title.beginsWith("gelato"), - matches: "instr(\"root\".\"title\", ?) = 1", - bindings: ["gelato"]) - assertPredicate(post.title ~= "gelato", - matches: "instr(\"root\".\"title\", ?) > 0", - bindings: ["gelato"]) + assertPredicate( + post.rating.between(start: 3, end: 5), + matches: "\"root\".\"rating\" between ? and ?", + bindings: [3, 5] + ) + assertPredicate( + post.title.beginsWith("gelato"), + matches: "instr(\"root\".\"title\", ?) = 1", + bindings: ["gelato"] + ) + assertPredicate( + post.title ~= "gelato", + matches: "instr(\"root\".\"title\", ?) > 0", + bindings: ["gelato"] + ) } /// - Given: a grouped predicate diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterJsonTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterJsonTests.swift index 7db19c714d..fbc11605bc 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterJsonTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterJsonTests.swift @@ -35,13 +35,17 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) - let syncEngine = try RemoteSyncEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault()) - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let syncEngine = try RemoteSyncEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault() + ) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) } catch { XCTFail(String(describing: error)) return @@ -50,11 +54,13 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { return self.storageEngine } let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestJsonModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestJsonModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true @@ -77,16 +83,18 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { /// - Then: /// - call `query(Post)` to check if the model was correctly inserted func testInsertPost() async { - let expectation = self.expectation( + let expectation = expectation( description: "it should save and select a Post from the database") // insert a post let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) storageAdapter.save(model, modelSchema: ModelRegistry.modelSchema(from: "Post")!) { saveResult in @@ -94,7 +102,8 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { case .success: self.storageAdapter.query( DynamicModel.self, - modelSchema: ModelRegistry.modelSchema(from: "Post")!) { queryResult in + modelSchema: ModelRegistry.modelSchema(from: "Post")! + ) { queryResult in switch queryResult { case .success(let posts): XCTAssert(posts.count == 1) @@ -125,7 +134,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { /// - call `query(Post, where: title == post.title)` to check /// if the model was correctly inserted using a predicate func testInsertPostAndSelectByTitle() async { - let expectation = self.expectation( + let expectation = expectation( description: "it should save and select a Post from the database") // insert a post @@ -133,9 +142,11 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) storageAdapter.save(model, modelSchema: ModelRegistry.modelSchema(from: "Post")!) { saveResult in switch saveResult { @@ -174,16 +185,18 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { /// - check if the `query(Post)` returns only 1 post /// - the post has the updated title func testInsertPostAndThenUpdateIt() async { - let expectation = self.expectation( + let expectation = expectation( description: "it should insert and update a Post") // insert a post let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) func checkSavedPost(id: String) { @@ -206,9 +219,11 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { storageAdapter.save(model, modelSchema: ModelRegistry.modelSchema(from: "Post")!) { insertResult in switch insertResult { case .success: - let updatedPost = ["title": .string("title updated"), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let updatedPost = [ + "title": .string("title updated"), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(id: model.id, values: updatedPost) self.storageAdapter.save(model, modelSchema: ModelRegistry.modelSchema(from: "Post")!) { updateResult in switch updateResult { @@ -242,20 +257,24 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let schema = ModelRegistry.modelSchema(from: "Post")! - + storageAdapter.save(model, modelSchema: schema) { insertResult in switch insertResult { case .success: saveExpectation.fulfill() - self.storageAdapter.delete(DynamicModel.self, - modelSchema: schema, - withIdentifier: model.identifier(schema: schema), - condition: nil) { + self.storageAdapter.delete( + DynamicModel.self, + modelSchema: schema, + withIdentifier: model.identifier(schema: schema), + condition: nil + ) { switch $0 { case .success: deleteExpectation.fulfill() @@ -281,7 +300,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { /// - a successful update for `update(post, condition)` /// - call `query(Post)` to check if the model was correctly updated func testInsertPostAndThenUpdateItWithCondition() { - let expectation = self.expectation(description: "it should insert and update a Post") + let expectation = expectation(description: "it should insert and update a Post") let schema = ModelRegistry.modelSchema(from: "Post")! func checkSavedPost(id: String) { storageAdapter.query(DynamicModel.self, modelSchema: schema) { @@ -304,17 +323,21 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) storageAdapter.save(model, modelSchema: schema) { insertResult in switch insertResult { case .success: - let updatedPost = ["title": .string("title updated"), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let updatedPost = [ + "title": .string("title updated"), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let updatedModel = DynamicModel(id: model.id, values: updatedPost) let condition = QueryPredicateOperation(field: "content", operator: .equals(content)) self.storageAdapter.save(updatedModel, modelSchema: schema, condition: condition) { updateResult in @@ -339,16 +362,18 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { /// - Then: /// - Fails with conditional save failed error when there is no existing model instance func testUpdateWithConditionFailsWhenNoExistingModel() { - let expectation = self.expectation( + let expectation = expectation( description: "it should fail to update the Post that does not exist") // insert a post let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let schema = ModelRegistry.modelSchema(from: "Post")! let condition = QueryPredicateOperation(field: "content", operator: .equals(content)) @@ -376,31 +401,39 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { /// - call `update(post, condition)` with `post.title` updated and condition does not match /// - the update for `update(post, condition)` fails with conditional save failed error func testInsertPostAndThenUpdateItWithConditionDoesNotMatchShouldReturnError() { - let expectation = self.expectation( + let expectation = expectation( description: "it should insert and then fail to update the Post, given bad condition") // insert a post let title = "title not updated" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let schema = ModelRegistry.modelSchema(from: "Post")! storageAdapter.save(model, modelSchema: schema) { insertResult in switch insertResult { case .success: - let updatedPost = ["title": .string("title updated"), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let updatedPost = [ + "title": .string("title updated"), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let updatedModel = DynamicModel(id: model.id, values: updatedPost) - let condition = QueryPredicateOperation(field: "content", - operator: .equals("content 2 does not match previous content")) - self.storageAdapter.save(updatedModel, - modelSchema: schema, - condition: condition) { updateResult in + let condition = QueryPredicateOperation( + field: "content", + operator: .equals("content 2 does not match previous content") + ) + self.storageAdapter.save( + updatedModel, + modelSchema: schema, + condition: condition + ) { updateResult in switch updateResult { case .success: XCTFail("Update should not be successful") @@ -432,9 +465,11 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { let title = "title1" let content = "content1" let createdAt = dateInFuture.iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let schema = ModelRegistry.modelSchema(from: "Post")! @@ -442,11 +477,15 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { switch insertResult { case .success: saveExpectation.fulfill() - let predicate = QueryPredicateOperation(field: "createdAt", - operator: .greaterThan(dateTestStart.iso8601String)) - self.storageAdapter.delete(DynamicModel.self, - modelSchema: Post.schema, - filter: predicate) { result in + let predicate = QueryPredicateOperation( + field: "createdAt", + operator: .greaterThan(dateTestStart.iso8601String) + ) + self.storageAdapter.delete( + DynamicModel.self, + modelSchema: Post.schema, + filter: predicate + ) { result in switch result { case .success: deleteExpectation.fulfill() @@ -479,9 +518,11 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { let title = "\(titleX)\(counter)" let content = "\(contentX)\(counter)" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) storageAdapter.save(model, modelSchema: schema) { insertResult in @@ -490,9 +531,11 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { postsAdded.append(model.id) if counter == maxCount - 1 { saveExpectation.fulfill() - self.storageAdapter.delete(DynamicModel.self, - modelSchema: schema, - filter: QueryPredicateConstant.all) { result in + self.storageAdapter.delete( + DynamicModel.self, + modelSchema: schema, + filter: QueryPredicateConstant.all + ) { result in switch result { case .success: deleteExpectation.fulfill() diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterTests.swift index c14e909701..7d4de9d3f9 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite import SQLite3 +import XCTest @testable import Amplify -@testable import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSDataStorePlugin +@testable import AWSPluginsCore // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -24,7 +24,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - Then: /// - call `query(Post)` to check if the model was correctly inserted func testInsertPost() { - let expectation = self.expectation( + let expectation = expectation( description: "it should save and select a Post from the database") // insert a post @@ -63,7 +63,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - Then: /// - call `query(Post)` to check if the model was correctly inserted func testInsertPostWithAll() { - let expectation = self.expectation( + let expectation = expectation( description: "it should save and select a Post from the database") // insert a post @@ -103,7 +103,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - call `query(Post, where: title == post.title)` to check /// if the model was correctly inserted using a predicate func testInsertPostAndSelectByTitle() { - let expectation = self.expectation( + let expectation = expectation( description: "it should save and select a Post from the database") // insert a post @@ -145,7 +145,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - check if the `query(Post)` returns only 1 post /// - the post has the updated title func testInsertPostAndThenUpdateIt() { - let expectation = self.expectation( + let expectation = expectation( description: "it should insert and update a Post") func checkSavedPost(id: String) { @@ -195,7 +195,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - a successful update for `update(post, condition)` /// - call `query(Post)` to check if the model was correctly updated func testInsertPostAndThenUpdateItWithCondition() { - let expectation = self.expectation( + let expectation = expectation( description: "it should insert and update a Post") func checkSavedPost(id: String) { @@ -245,7 +245,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - a successful update for `update(post, condition)` /// - call `query(Post)` to check if the model was correctly updated func testInsertPostAndThenUpdateItWithConditionAll() { - let expectation = self.expectation( + let expectation = expectation( description: "it should insert and update a Post") func checkSavedPost(id: String) { @@ -292,7 +292,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - Then: /// - Fails with conditional save failed error when there is no existing model instance func testUpdateWithConditionFailsWhenNoExistingModel() { - let expectation = self.expectation( + let expectation = expectation( description: "it should fail to update the Post that does not exist") let post = Post(title: "title", content: "content", createdAt: .now()) @@ -321,7 +321,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - call `update(post, condition)` with `post.title` updated and condition does not match /// - the update for `update(post, condition)` fails with conditional save failed error func testInsertPostAndThenUpdateItWithConditionDoesNotMatchShouldReturnError() { - let expectation = self.expectation( + let expectation = expectation( description: "it should insert and then fail to update the Post, given bad condition") var post = Post(title: "title not updated", content: "content", createdAt: .now()) @@ -367,9 +367,11 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { switch insertResult { case .success: saveExpectation.fulfill() - self.storageAdapter.delete(untypedModelType: Post.self, - modelSchema: Post.schema, - withIdentifier: post.identifier(schema: Post.schema)) { + self.storageAdapter.delete( + untypedModelType: Post.self, + modelSchema: Post.schema, + withIdentifier: post.identifier(schema: Post.schema) + ) { switch $0 { case .success: deleteExpectation.fulfill() @@ -401,10 +403,12 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { saveExpectation.fulfill() let postKeys = Post.keys let predicate = postKeys.createdAt.gt(dateTestStart) - self.storageAdapter.delete(Post.self, - modelSchema: Post.schema, - withIdentifier: post.identifier(schema: Post.schema), - condition: predicate) { result in + self.storageAdapter.delete( + Post.self, + modelSchema: Post.schema, + withIdentifier: post.identifier(schema: Post.schema), + condition: predicate + ) { result in switch result { case .success: deleteExpectation.fulfill() @@ -436,10 +440,12 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { saveExpectation.fulfill() let postKeys = Post.keys let predicate = postKeys.createdAt.lt(dateTestStart) - self.storageAdapter.delete(Post.self, - modelSchema: Post.schema, - withIdentifier: post.identifier(schema: Post.schema), - condition: predicate) { result in + self.storageAdapter.delete( + Post.self, + modelSchema: Post.schema, + withIdentifier: post.identifier(schema: Post.schema), + condition: predicate + ) { result in switch result { case .success: deleteCompleteExpectation.fulfill() @@ -510,9 +516,11 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { postsAdded.append(post.id) if counter == maxCount - 1 { saveExpectation.fulfill() - self.storageAdapter.delete(Post.self, - modelSchema: Post.schema, - filter: QueryPredicateConstant.all) { result in + self.storageAdapter.delete( + Post.self, + modelSchema: Post.schema, + filter: QueryPredicateConstant.all + ) { result in switch result { case .success: deleteExpectation.fulfill() @@ -566,10 +574,12 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } do { - _ = try SQLiteStorageEngineAdapter.clearIfNewVersion(version: newVersion, - dbFilePath: URL(string: "dbFilePath")!, - userDefaults: userDefaults, - fileManager: mockFileManager) + _ = try SQLiteStorageEngineAdapter.clearIfNewVersion( + version: newVersion, + dbFilePath: URL(string: "dbFilePath")!, + userDefaults: userDefaults, + fileManager: mockFileManager + ) } catch { XCTFail("Test failed due to \(error)") } @@ -593,10 +603,12 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } do { - _ = try SQLiteStorageEngineAdapter.clearIfNewVersion(version: newVersion, - dbFilePath: URL(string: "dbFilePath")!, - userDefaults: userDefaults, - fileManager: mockFileManager) + _ = try SQLiteStorageEngineAdapter.clearIfNewVersion( + version: newVersion, + dbFilePath: URL(string: "dbFilePath")!, + userDefaults: userDefaults, + fileManager: mockFileManager + ) } catch { XCTFail("Test failed due to \(error)") } @@ -620,10 +632,12 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } do { - _ = try SQLiteStorageEngineAdapter.clearIfNewVersion(version: newVersion, - dbFilePath: URL(string: "dbFilePath")!, - userDefaults: userDefaults, - fileManager: mockFileManager) + _ = try SQLiteStorageEngineAdapter.clearIfNewVersion( + version: newVersion, + dbFilePath: URL(string: "dbFilePath")!, + userDefaults: userDefaults, + fileManager: mockFileManager + ) } catch { XCTFail("Test failed due to \(error)") } @@ -645,10 +659,12 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { mockFileManager.fileExists = true do { - _ = try SQLiteStorageEngineAdapter.clearIfNewVersion(version: newVersion, - dbFilePath: URL(string: "dbFilePath")!, - userDefaults: userDefaults, - fileManager: mockFileManager) + _ = try SQLiteStorageEngineAdapter.clearIfNewVersion( + version: newVersion, + dbFilePath: URL(string: "dbFilePath")!, + userDefaults: userDefaults, + fileManager: mockFileManager + ) } catch { guard let dataStoreError = error as? DataStoreError, case .invalidDatabase = dataStoreError else { XCTFail("Expected DataStoreErrorF") @@ -673,11 +689,13 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { let querySuccess = expectation(description: "query for metadata success") let modelId = UUID().uuidString let modelName = "modelName" - let metadata = MutationSyncMetadata(modelId: modelId, - modelName: modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let metadata = MutationSyncMetadata( + modelId: modelId, + modelName: modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) storageAdapter.save(metadata) { result in switch result { @@ -697,16 +715,20 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { func testQueryMutationSyncMetadataForModelIds() { let modelName = "modelName" - let metadata1 = MutationSyncMetadata(modelId: UUID().uuidString, - modelName: modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) - let metadata2 = MutationSyncMetadata(modelId: UUID().uuidString, - modelName: modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let metadata1 = MutationSyncMetadata( + modelId: UUID().uuidString, + modelName: modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) + let metadata2 = MutationSyncMetadata( + modelId: UUID().uuidString, + modelName: modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let saveMetadata1 = expectation(description: "save metadata1 success") storageAdapter.save(metadata1) { result in @@ -744,18 +766,22 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } func testShouldIgnoreConstraintViolationError() { - let constraintViolationError = Result.error(message: "Foreign Key Constraint Violation", - code: SQLITE_CONSTRAINT, - statement: nil) + let constraintViolationError = Result.error( + message: "Foreign Key Constraint Violation", + code: SQLITE_CONSTRAINT, + statement: nil + ) let dataStoreError = DataStoreError.invalidOperation(causedBy: constraintViolationError) XCTAssertTrue(storageAdapter.shouldIgnoreError(error: dataStoreError)) } func testShouldIgnoreErrorFalse() { - let constraintViolationError = Result.error(message: "", - code: SQLITE_BUSY, - statement: nil) + let constraintViolationError = Result.error( + message: "", + code: SQLITE_BUSY, + statement: nil + ) let dataStoreError = DataStoreError.invalidOperation(causedBy: constraintViolationError) XCTAssertFalse(storageAdapter.shouldIgnoreError(error: dataStoreError)) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SortByDependencyOrderTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SortByDependencyOrderTests.swift index 8cf43905af..3d7950a46a 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SortByDependencyOrderTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SortByDependencyOrderTests.swift @@ -39,7 +39,7 @@ class SortByDependencyOrderTests: XCTestCase { let sorted = modelSchemas.sortByDependencyOrder() - let sortedModelNames = sorted.map { $0.name } + let sortedModelNames = sorted.map(\.name) XCTAssertEqual(sortedModelNames, ["Post", "Comment"]) } @@ -53,7 +53,7 @@ class SortByDependencyOrderTests: XCTestCase { let sorted = modelSchemas.sortByDependencyOrder() - let sortedModelNames = sorted.map { $0.name } + let sortedModelNames = sorted.map(\.name) XCTAssertEqual(sortedModelNames, ["Post", "Comment", "MockSynced"]) } @@ -67,7 +67,7 @@ class SortByDependencyOrderTests: XCTestCase { let sorted = modelSchemas.sortByDependencyOrder() - let sortedModelNames = sorted.map { $0.name } + let sortedModelNames = sorted.map(\.name) XCTAssertEqual(sortedModelNames, ["Post", "Comment", "UserAccount", "UserProfile"]) } @@ -81,7 +81,7 @@ class SortByDependencyOrderTests: XCTestCase { let sorted = modelSchemas.sortByDependencyOrder() - let sortedModelNames = sorted.map { $0.name } + let sortedModelNames = sorted.map(\.name) XCTAssertEqual(sortedModelNames, ["Author", "Book", "BookAuthor"]) } @@ -91,15 +91,23 @@ class SortByDependencyOrderTests: XCTestCase { /// - Then: /// - the ordered list is deterministically sorted, although not necessarily predictable func testSortsDeterministically() { - let expectedModelNames = ["Author", "Book", "BookAuthor", "Post", "Comment", "MockUnsynced", - "UserAccount", "UserProfile"] + let expectedModelNames = [ + "Author", + "Book", + "BookAuthor", + "Post", + "Comment", + "MockUnsynced", + "UserAccount", + "UserProfile" + ] for _ in 0 ..< 10 { - let modelSchemas = modelList.shuffled().map { (modelType) -> ModelSchema in + let modelSchemas = modelList.shuffled().map { modelType -> ModelSchema in modelType.schema } let sorted = modelSchemas.sortByDependencyOrder() - let sortedModelNames = sorted.map { $0.name } + let sortedModelNames = sorted.map(\.name) XCTAssertEqual(sortedModelNames, expectedModelNames) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StateMachineTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StateMachineTests.swift index 5d36c0ca33..9ec1dfebc1 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StateMachineTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StateMachineTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Combine +import XCTest // Testable import b/c StateMachine is an internal type @testable import AWSDataStorePlugin @@ -106,12 +106,16 @@ class StateMachineTests: XCTestCase { } } - await fulfillment(of: [receivedOneOnSubscribe, - receivedTwoAfterSubscribe, - receivedThreeAfterSubscribe, - receivedOneAfterSubscribe], - timeout: 1, - enforceOrder: true) + await fulfillment( + of: [ + receivedOneOnSubscribe, + receivedTwoAfterSubscribe, + receivedThreeAfterSubscribe, + receivedOneAfterSubscribe + ], + timeout: 1, + enforceOrder: true + ) listener.cancel() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StorageAdapterMutationSyncTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StorageAdapterMutationSyncTests.swift index 07c9e922b2..557671017e 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StorageAdapterMutationSyncTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StorageAdapterMutationSyncTests.swift @@ -8,8 +8,8 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class StorageAdapterMutationSyncTests: BaseDataStoreTests { @@ -29,19 +29,21 @@ class StorageAdapterMutationSyncTests: BaseDataStoreTests { // then create sync metadata for them let syncMetadataList = posts.map { - MutationSyncMetadata(modelId: $0.id, - modelName: Post.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + MutationSyncMetadata( + modelId: $0.id, + modelName: Post.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) } populateData(syncMetadataList) do { let mutationSync = try storageAdapter.queryMutationSync(for: posts, modelName: Post.modelName) - mutationSync.forEach { - XCTAssertEqual($0.model.id, $0.syncMetadata.modelId) - let post = $0.model.instance as? Post + for item in mutationSync { + XCTAssertEqual(item.model.id, item.syncMetadata.modelId) + let post = item.model.instance as? Post XCTAssertNotNil(post) } expect.fulfill() diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MockMutationSyncMigrationDelegate.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MockMutationSyncMigrationDelegate.swift index 0b476e3669..05051f0738 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MockMutationSyncMigrationDelegate.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MockMutationSyncMigrationDelegate.swift @@ -44,14 +44,14 @@ class MockMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMigrationDe func preconditionCheck() throws { stepsCalled.append(.precondition) - if let preconditionCheckError = preconditionCheckError { + if let preconditionCheckError { throw preconditionCheckError } } func transaction(_ basicClosure: () throws -> Void) throws { stepsCalled.append(.transaction) - if let transactionError = transactionError { + if let transactionError { throw transactionError } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/ModelSyncMutationMigrationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/ModelSyncMutationMigrationTests.swift index 95e42c224a..5d7c412118 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/ModelSyncMutationMigrationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/ModelSyncMutationMigrationTests.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify -@testable import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSDataStorePlugin +@testable import AWSPluginsCore final class ModelSyncMetadataMigrationTests: XCTestCase { @@ -19,10 +19,10 @@ final class ModelSyncMetadataMigrationTests: XCTestCase { var storageEngine: StorageEngine! var storageAdapter: SQLiteStorageEngineAdapter! var dataStorePlugin: AWSDataStorePlugin! - + override func setUp() async throws { await Amplify.reset() - + do { connection = try Connection(.inMemory) storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) @@ -31,21 +31,22 @@ final class ModelSyncMetadataMigrationTests: XCTestCase { return } } - + /// Use the latest schema and create the table with it. /// The column should be found and no upgrade should occur. func testPerformModelMetadataSyncPredicateUpgrade_ColumnExists() throws { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) guard let field = ModelSyncMetadata.schema.field( - withName: ModelSyncMetadata.keys.syncPredicate.stringValue) else { + withName: ModelSyncMetadata.keys.syncPredicate.stringValue) + else { XCTFail("Could not find corresponding ModelField from ModelSyncMetadata for syncPredicate") return } let modelSyncMetadataMigration = ModelSyncMetadataMigration(storageAdapter: storageAdapter) - + let exists = try modelSyncMetadataMigration.columnExists(modelSchema: ModelSyncMetadata.schema, field: field) XCTAssertTrue(exists) - + do { let result = try modelSyncMetadataMigration.performModelMetadataSyncPredicateUpgrade() XCTAssertFalse(result) @@ -53,7 +54,7 @@ final class ModelSyncMetadataMigrationTests: XCTestCase { XCTFail("Failed to perform upgrade \(error)") } } - + /// Create a local copy of the previous ModelSyncMetadata, without sync predicate /// Create the table with the previous schema, and perform the upgrade. /// The upgrade should have occurred successfully. @@ -61,9 +62,11 @@ final class ModelSyncMetadataMigrationTests: XCTestCase { struct ModelSyncMetadata: Model { public let id: String public var lastSync: Int? - - public init(id: String, - lastSync: Int?) { + + public init( + id: String, + lastSync: Int? + ) { self.id = id self.lastSync = lastSync } @@ -83,14 +86,15 @@ final class ModelSyncMetadataMigrationTests: XCTestCase { try storageAdapter.setUp(modelSchemas: [ModelSyncMetadata.schema]) guard let field = AWSPluginsCore.ModelSyncMetadata.schema.field( - withName: AWSPluginsCore.ModelSyncMetadata.keys.syncPredicate.stringValue) else { + withName: AWSPluginsCore.ModelSyncMetadata.keys.syncPredicate.stringValue) + else { XCTFail("Could not find corresponding ModelField from ModelSyncMetadata for syncPredicate") return } let modelSyncMetadataMigration = ModelSyncMetadataMigration(storageAdapter: storageAdapter) let exists = try modelSyncMetadataMigration.columnExists(modelSchema: AWSPluginsCore.ModelSyncMetadata.schema, field: field) XCTAssertFalse(exists) - + do { let result = try modelSyncMetadataMigration.performModelMetadataSyncPredicateUpgrade() XCTAssertTrue(result) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTestBase.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTestBase.swift index e737a83d20..09a4512595 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTestBase.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -45,7 +45,7 @@ class MutationSyncMetadataMigrationTestBase: XCTestCase { // MARK: - Helpers - func save(_ model: M) { + func save(_ model: some Model) { let saveSuccess = expectation(description: "Save successful") storageAdapter.save(model) { result in switch result { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTests.swift index 51b373c436..eee67c53a9 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTests.swift @@ -78,10 +78,12 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase do { try migration.apply() } catch { - XCTAssertEqual(delegate.stepsCalled, [.precondition, - .transaction, - .mutationSyncMetadataStoreEmptyOrMigrated, - .containsDuplicateIdsAcrossModels]) + XCTAssertEqual(delegate.stepsCalled, [ + .precondition, + .transaction, + .mutationSyncMetadataStoreEmptyOrMigrated, + .containsDuplicateIdsAcrossModels + ]) return } @@ -97,11 +99,13 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase do { try migration.apply() } catch { - XCTAssertEqual(delegate.stepsCalled, [.precondition, - .transaction, - .mutationSyncMetadataStoreEmptyOrMigrated, - .containsDuplicateIdsAcrossModels, - .emptyMutationSyncMetadataStore]) + XCTAssertEqual(delegate.stepsCalled, [ + .precondition, + .transaction, + .mutationSyncMetadataStoreEmptyOrMigrated, + .containsDuplicateIdsAcrossModels, + .emptyMutationSyncMetadataStore + ]) return } XCTFail("Should catch error") @@ -116,12 +120,14 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase do { try migration.apply() } catch { - XCTAssertEqual(delegate.stepsCalled, [.precondition, - .transaction, - .mutationSyncMetadataStoreEmptyOrMigrated, - .containsDuplicateIdsAcrossModels, - .emptyMutationSyncMetadataStore, - .emptyModelSyncMetadataStore]) + XCTAssertEqual(delegate.stepsCalled, [ + .precondition, + .transaction, + .mutationSyncMetadataStoreEmptyOrMigrated, + .containsDuplicateIdsAcrossModels, + .emptyMutationSyncMetadataStore, + .emptyModelSyncMetadataStore + ]) return } XCTFail("Should catch error") @@ -137,11 +143,13 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase do { try migration.apply() } catch { - XCTAssertEqual(delegate.stepsCalled, [.precondition, - .transaction, - .mutationSyncMetadataStoreEmptyOrMigrated, - .containsDuplicateIdsAcrossModels, - .removeMutationSyncMetadataCopyStore]) + XCTAssertEqual(delegate.stepsCalled, [ + .precondition, + .transaction, + .mutationSyncMetadataStoreEmptyOrMigrated, + .containsDuplicateIdsAcrossModels, + .removeMutationSyncMetadataCopyStore + ]) return } XCTFail("Should catch error") @@ -153,15 +161,17 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase delegate.containsDuplicateIdsAcrossModelsResult = false let migration = MutationSyncMetadataMigration(delegate: delegate) try migration.apply() - XCTAssertEqual(delegate.stepsCalled, [.precondition, - .transaction, - .mutationSyncMetadataStoreEmptyOrMigrated, - .containsDuplicateIdsAcrossModels, - .removeMutationSyncMetadataCopyStore, - .createMutationSyncMetadataCopyStore, - .backfillMutationSyncMetadata, - .removeMutationSyncMetadataStore, - .renameMutationSyncMetadataCopy]) + XCTAssertEqual(delegate.stepsCalled, [ + .precondition, + .transaction, + .mutationSyncMetadataStoreEmptyOrMigrated, + .containsDuplicateIdsAcrossModels, + .removeMutationSyncMetadataCopyStore, + .createMutationSyncMetadataCopyStore, + .backfillMutationSyncMetadata, + .removeMutationSyncMetadataStore, + .renameMutationSyncMetadataCopy + ]) } func testApply() throws { @@ -177,8 +187,10 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase XCTAssertEqual(mutationSyncMetadatas.count, 1) XCTAssertEqual(mutationSyncMetadatas[0].id, restaurant.id) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) let migration = MutationSyncMetadataMigration(delegate: delegate) try migration.apply() @@ -193,7 +205,8 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase guard let restaurantMetadata = try storageAdapter.queryMutationSyncMetadata( for: restaurant.id, - modelName: Restaurant.modelName) else { + modelName: Restaurant.modelName + ) else { XCTFail("Could not get metadata") return } @@ -207,11 +220,13 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase delegate.containsDuplicateIdsAcrossModelsResult = true let migration = MutationSyncMetadataMigration(delegate: delegate) try migration.apply() - XCTAssertEqual(delegate.stepsCalled, [.precondition, - .transaction, - .mutationSyncMetadataStoreEmptyOrMigrated, - .containsDuplicateIdsAcrossModels, - .emptyMutationSyncMetadataStore, - .emptyModelSyncMetadataStore]) + XCTAssertEqual(delegate.stepsCalled, [ + .precondition, + .transaction, + .mutationSyncMetadataStoreEmptyOrMigrated, + .containsDuplicateIdsAcrossModels, + .emptyMutationSyncMetadataStore, + .emptyModelSyncMetadataStore + ]) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationDelegateTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationDelegateTests.swift index 68667e65e8..4570ec20e9 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationDelegateTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationDelegateTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -19,8 +19,10 @@ class SQLiteMutationSyncMetadataMigrationDelegateTests: MutationSyncMetadataMigr func testClearSuccess() throws { try setUpAllModels() - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) try delegate.emptyMutationSyncMetadataStore() try delegate.emptyModelSyncMetadataStore() } @@ -36,8 +38,10 @@ class SQLiteMutationSyncMetadataMigrationDelegateTests: MutationSyncMetadataMigr } XCTAssertEqual(mutationSyncMetadatas.count, 1) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) let sql = try delegate.emptyMutationSyncMetadataStore() XCTAssertEqual(sql, "delete from \"MutationSyncMetadata\" as root") guard let mutationSyncMetadatas = queryMutationSyncMetadata() else { @@ -58,8 +62,10 @@ class SQLiteMutationSyncMetadataMigrationDelegateTests: MutationSyncMetadataMigr } XCTAssertEqual(modelSyncMetadatas.count, 1) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) let sql = try delegate.emptyModelSyncMetadataStore() XCTAssertEqual(sql, "delete from \"ModelSyncMetadata\" as root") guard let modelSyncMetadatasDeleted = queryModelSyncMetadata() else { @@ -84,8 +90,10 @@ class SQLiteMutationSyncMetadataMigrationDelegateTests: MutationSyncMetadataMigr XCTAssertEqual(mutationSyncMetadatas.count, 1) XCTAssertEqual(mutationSyncMetadatas[0].id, restaurant.id) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) try delegate.removeMutationSyncMetadataCopyStore() try delegate.createMutationSyncMetadataCopyStore() @@ -103,7 +111,8 @@ class SQLiteMutationSyncMetadataMigrationDelegateTests: MutationSyncMetadataMigr guard let restaurantMetadata = try storageAdapter.queryMutationSyncMetadata( for: restaurant.id, - modelName: Restaurant.modelName) else { + modelName: Restaurant.modelName + ) else { XCTFail("Could not get metadata") return } @@ -113,8 +122,10 @@ class SQLiteMutationSyncMetadataMigrationDelegateTests: MutationSyncMetadataMigr /// Ensure creating and dropping the MutationSyncMetadataCopy works as expected func testDropMutationSyncMetadataCopyIfExists() throws { - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) try delegate.removeMutationSyncMetadataCopyStore() // Dropping the table without the table in the database is successful diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationValidationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationValidationTests.swift index d259ddf91d..1f451a37c0 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationValidationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationValidationTests.swift @@ -5,21 +5,23 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest +import SQLite3 @testable import Amplify @testable import AmplifyTestCommon @testable import AWSDataStorePlugin @testable import AWSPluginsCore -import SQLite3 class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMigrationTestBase { // MARK: - Precondition tests func testPreconditionSuccess() throws { - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) try delegate.preconditionCheck() } @@ -28,8 +30,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi func testSelectMutationSyncMetadataWithoutTableShouldThrow() { let shouldCatchFailure = expectation(description: "select MutationSyncMetadata without table should fail") do { - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) _ = try delegate.selectMutationSyncMetadataRecords() } catch { guard let resultError = error as? Result, @@ -50,8 +54,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi try setUpAllModels() let metadata = MutationSyncMetadata(id: UUID().uuidString, deleted: false, lastChangedAt: 1, version: 1) save(metadata) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) XCTAssertFalse(try delegate.mutationSyncMetadataStoreEmptyOrMigrated()) } @@ -59,14 +65,18 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi /// Set up MutationSyncMetadata records where the id is in the correct format. Check that it does not need migration func testMutationSyncMetadataStoreNotEmptyAndMigrated() throws { try setUpAllModels() - let metadata = MutationSyncMetadata(modelId: UUID().uuidString, - modelName: "modelName", - deleted: false, - lastChangedAt: 1, - version: 1) + let metadata = MutationSyncMetadata( + modelId: UUID().uuidString, + modelName: "modelName", + deleted: false, + lastChangedAt: 1, + version: 1 + ) save(metadata) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) XCTAssertTrue(try delegate.mutationSyncMetadataStoreEmptyOrMigrated()) } @@ -75,8 +85,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi func testSelectDuplicateIdCountAcrossModelsWithoutTableShouldThrow() { let shouldCatchFailure = expectation(description: "select duplicate id count without model tables should fail") - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) do { _ = try delegate.containsDuplicateIdsAcrossModels() } catch { @@ -95,8 +107,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi func testSelectDuplicateIdAcrossModelsStatement() throws { try setUpAllModels() - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) let expected = "SELECT id, tableName, count(id) as count FROM " + "(SELECT id, 'Restaurant' as tableName FROM Restaurant UNION ALL " + "SELECT id, 'Menu' as tableName FROM Menu UNION ALL " + @@ -106,8 +120,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi func testSelectDuplicateIdCountAcrossModels_NoData() throws { try setUpAllModels() - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) XCTAssertFalse(try delegate.containsDuplicateIdsAcrossModels()) } @@ -119,8 +135,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi save(menu) let dish = Dish(dishName: "name", menu: menu) save(dish) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) XCTAssertFalse(try delegate.containsDuplicateIdsAcrossModels()) } @@ -134,8 +152,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi save(menu) let dish = Dish(id: "1", dishName: "name", menu: menu) save(dish) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) XCTAssertTrue(try delegate.containsDuplicateIdsAcrossModels()) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/DynamicModel.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/DynamicModel.swift index f423694eff..9109fead18 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/DynamicModel.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/DynamicModel.swift @@ -13,8 +13,10 @@ struct DynamicModel: Model, JSONValueHolder { public let id: String public var values: [String: JSONValue] - public init(id: String = UUID().uuidString, - values: [String: JSONValue]) { + public init( + id: String = UUID().uuidString, + values: [String: JSONValue] + ) { self.id = id var valueWIthId = values valueWIthId["id"] = .string(id) @@ -23,8 +25,8 @@ struct DynamicModel: Model, JSONValueHolder { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - id = try container.decode(String.self, forKey: .id) - values = try decoder.singleValueContainer().decode([String: JSONValue].self) + self.id = try container.decode(String.self, forKey: .id) + self.values = try decoder.singleValueContainer().decode([String: JSONValue].self) } public func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/ExampleWithEveryType+Schema.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/ExampleWithEveryType+Schema.swift index 3d4f7276ba..361f2b4c12 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/ExampleWithEveryType+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/ExampleWithEveryType+Schema.swift @@ -8,11 +8,11 @@ import Amplify import Foundation -extension ExampleWithEveryType { +public extension ExampleWithEveryType { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case stringField case intField @@ -24,11 +24,11 @@ extension ExampleWithEveryType { case arrayOfStringsField } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let example = ExampleWithEveryType.keys model.listPluralName = "ExampleWithEveryTypes" diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/SQLModelValueConverterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/SQLModelValueConverterTests.swift index ac65ccd105..b3a1881469 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/SQLModelValueConverterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/SQLModelValueConverterTests.swift @@ -8,10 +8,10 @@ import Foundation import XCTest +import AmplifyTestCommon @testable import Amplify @testable import AWSDataStorePlugin @testable import SQLite -import AmplifyTestCommon class SQLModelValueConverterTests: BaseDataStoreTests { @@ -29,15 +29,17 @@ class SQLModelValueConverterTests: BaseDataStoreTests { let nonModelExample = ExampleNonModelType(someString: "string", someEnum: .foo) // example model - let example = ExampleWithEveryType(id: testId, - stringField: "string", - intField: 20, - doubleField: 6.5, - boolField: true, - dateField: testDate, - enumField: .bar, - nonModelField: nonModelExample, - arrayOfStringsField: ["foo", "bar"]) + let example = ExampleWithEveryType( + id: testId, + stringField: "string", + intField: 20, + doubleField: 6.5, + boolField: true, + dateField: testDate, + enumField: .bar, + nonModelField: nonModelExample, + arrayOfStringsField: ["foo", "bar"] + ) return example } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/CascadeDeleteOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/CascadeDeleteOperationTests.swift index f7eea5c6aa..092fb1e95a 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/CascadeDeleteOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/CascadeDeleteOperationTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import SQLite import Combine +import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -28,11 +28,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: Restaurant.self) ModelRegistry.register(modelType: Menu.self) ModelRegistry.register(modelType: Dish.self) @@ -65,19 +67,23 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { return } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id - guard case .success(let queriedRestaurants) = await queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = await queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } XCTAssertEqual(queriedRestaurants.count, 1) let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: nil, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: nil, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier + ) { result in switch result { case .success(let restaurant): XCTAssertNotNil(restaurant) @@ -88,8 +94,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() await fulfillment(of: [completed], timeout: 1) - guard case .success(let queriedRestaurants) = await queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = await queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -106,8 +114,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = ModelCompositePk.keys.id == modelId && ModelCompositePk.keys.dob == modelDob - guard case .success(let queriedModel) = queryModelSynchronous(modelType: ModelCompositePk.self, - predicate: predicate) else { + guard case .success(let queriedModel) = queryModelSynchronous( + modelType: ModelCompositePk.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -118,11 +128,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { let completed = expectation(description: "operation completed") let identifier = ModelCompositePk.IdentifierProtocol.identifier(id: modelId, dob: modelDob) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: nil, - modelType: ModelCompositePk.self, - modelSchema: ModelCompositePk.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: nil, + modelType: ModelCompositePk.self, + modelSchema: ModelCompositePk.schema, + withIdentifier: identifier + ) { result in switch result { case .success(let model): XCTAssertNotNil(model) @@ -133,8 +145,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed], timeout: 1) - guard case .success(let queriedModel) = queryModelSynchronous(modelType: ModelCompositePk.self, - predicate: predicate) else { + guard case .success(let queriedModel) = queryModelSynchronous( + modelType: ModelCompositePk.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -150,8 +164,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id && Restaurant.keys.restaurantName == restaurantName - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -159,12 +175,14 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { XCTAssertEqual(queriedRestaurants.first!.restaurantName, restaurantName) let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: nil, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier, - condition: Restaurant.keys.restaurantName.eq(restaurantName)) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: nil, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier, + condition: Restaurant.keys.restaurantName.eq(restaurantName) + ) { result in switch result { case .success(let restaurant): XCTAssertNotNil(restaurant) @@ -175,8 +193,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed], timeout: 1) - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -192,8 +212,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id && Restaurant.keys.restaurantName == restaurantName - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -201,12 +223,14 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { XCTAssertEqual(queriedRestaurants.first!.restaurantName, restaurantName) let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: nil, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier, - condition: Restaurant.keys.restaurantName.ne(restaurantName)) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: nil, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier, + condition: Restaurant.keys.restaurantName.ne(restaurantName) + ) { result in switch result { case .success: XCTFail("Should have been invalid condition error") @@ -220,8 +244,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed], timeout: 1) - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -238,19 +264,23 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id && Restaurant.keys.restaurantName == restaurantName - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } XCTAssertEqual(queriedRestaurants.count, 1) XCTAssertEqual(queriedRestaurants.first!.restaurantName, restaurantName) let completed = expectation(description: "operation completed") - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: nil, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - filter: Restaurant.keys.restaurantName.eq(restaurantName)) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: nil, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + filter: Restaurant.keys.restaurantName.eq(restaurantName) + ) { result in switch result { case .success(let restaurants): XCTAssertEqual(restaurants.count, 1) @@ -262,8 +292,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed], timeout: 1) - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -279,19 +311,23 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id && Restaurant.keys.restaurantName == restaurantName - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } XCTAssertEqual(queriedRestaurants.count, 1) XCTAssertEqual(queriedRestaurants.first!.restaurantName, restaurantName) let completed = expectation(description: "operation completed") - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: nil, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - filter: Restaurant.keys.restaurantName.ne(restaurantName)) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: nil, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + filter: Restaurant.keys.restaurantName.ne(restaurantName) + ) { result in switch result { case .success(let restaurants): XCTAssertEqual(restaurants.count, 0) @@ -302,8 +338,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed], timeout: 1) - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -320,8 +358,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { return } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id - guard case .success(let queriedRestaurants) = await queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = await queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -347,11 +387,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier + ) { result in switch result { case .success(let restaurant): XCTAssertNotNil(restaurant) @@ -363,8 +405,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { operation.start() await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess, completed], timeout: 1) - guard case .success(let queriedRestaurants) = await queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = await queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -382,8 +426,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = ModelCompositePk.keys.id == modelId && ModelCompositePk.keys.dob == modelDob - guard case .success(let queriedModels) = await queryModelSynchronous(modelType: ModelCompositePk.self, - predicate: predicate) else { + guard case .success(let queriedModels) = await queryModelSynchronous( + modelType: ModelCompositePk.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -409,11 +455,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { let completed = expectation(description: "operation completed") let identifier = ModelCompositePk.IdentifierProtocol.identifier(id: modelId, dob: modelDob) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: ModelCompositePk.self, - modelSchema: ModelCompositePk.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: ModelCompositePk.self, + modelSchema: ModelCompositePk.schema, + withIdentifier: identifier + ) { result in switch result { case .success(let restaurant): XCTAssertNotNil(restaurant) @@ -424,8 +472,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess, completed], timeout: 1) - guard case .success(let queriedModels) = await queryModelSynchronous(modelType: ModelCompositePk.self, - predicate: predicate) else { + guard case .success(let queriedModels) = await queryModelSynchronous( + modelType: ModelCompositePk.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -441,8 +491,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id && Restaurant.keys.restaurantName == restaurantName - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -469,12 +521,14 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier, - condition: Restaurant.keys.restaurantName.eq(restaurantName)) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier, + condition: Restaurant.keys.restaurantName.eq(restaurantName) + ) { result in switch result { case .success(let restaurant): XCTAssertNotNil(restaurant) @@ -485,8 +539,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed, receivedMutationEvent, expectedFailures, expectedSuccess], timeout: 1) - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -502,8 +558,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id && Restaurant.keys.restaurantName == restaurantName - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -516,7 +574,7 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { let expectedSuccess = expectation(description: "Simulated success on mutation event submitted to sync engine") expectedSuccess.expectedFulfillmentCount = 1 - + syncEngine.setCallbackOnSubmit { submittedMutationEvent, completion in receivedMutationEvent.fulfill() if submittedMutationEvent.modelId == restaurant.id { @@ -529,11 +587,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let completed = expectation(description: "operation completed") - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - filter: Restaurant.keys.restaurantName.eq(restaurantName)) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + filter: Restaurant.keys.restaurantName.eq(restaurantName) + ) { result in switch result { case .success(let restaurants): XCTAssertEqual(restaurants.count, 1) @@ -545,8 +605,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed, receivedMutationEvent, expectedFailures, expectedSuccess], timeout: 1) - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -562,11 +624,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { return } let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier) { _ in } + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier + ) { _ in } let result = await operation.queryAndDeleteTransaction() switch result { @@ -612,11 +676,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier + ) { result in switch result { case .success: completed.fulfill() @@ -645,7 +711,7 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { expectedSuccess.expectedFulfillmentCount = 3 var submittedEvents = [MutationEvent]() - + syncEngine.setCallbackOnSubmit { submittedMutationEvent, completion in submittedEvents.append(submittedMutationEvent) receivedMutationEvent.fulfill() @@ -683,11 +749,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { let completed = expectation(description: "operation completed") let identifier = PostWithCompositeKey.IdentifierProtocol.identifier(id: post.id, title: post.title) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: PostWithCompositeKey.self, - modelSchema: PostWithCompositeKey.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: PostWithCompositeKey.self, + modelSchema: PostWithCompositeKey.schema, + withIdentifier: identifier + ) { result in switch result { case .success: completed.fulfill() @@ -715,7 +783,7 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { expectedSuccess.expectedFulfillmentCount = 2 var submittedEvents = [MutationEvent]() - + syncEngine.setCallbackOnSubmit { submittedMutationEvent, completion in submittedEvents.append(submittedMutationEvent) receivedMutationEvent.fulfill() @@ -751,11 +819,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier + ) { result in switch result { case .success: XCTFail("Should have failed") @@ -784,7 +854,7 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { expectedSuccess.expectedFulfillmentCount = 2 var submittedEvents = [MutationEvent]() - + syncEngine.setCallbackOnSubmit { submittedMutationEvent, completion in submittedEvents.append(submittedMutationEvent) receivedMutationEvent.fulfill() diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEnginePublisherTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEnginePublisherTests.swift index 6f189b06bb..fea95315a4 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEnginePublisherTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEnginePublisherTests.swift @@ -12,6 +12,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSDataStorePlugin + class StorageEnginePublisherTests: StorageEngineTestsBase { override func setUp() { @@ -23,11 +24,13 @@ class StorageEnginePublisherTests: StorageEngineTestsBase { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) } catch { XCTFail(String(describing: error)) return @@ -35,18 +38,22 @@ class StorageEnginePublisherTests: StorageEngineTestsBase { } func testStorageEnginePublisherEvents() { - let modelSyncedEvent = ModelSyncedEvent(modelName: "", - isFullSync: true, - isDeltaSync: false, - added: 1, - updated: 1, - deleted: 1) - let mutationEvent = MutationEvent(id: "", - modelId: "", - modelName: "", - json: "", - mutationType: .create, - createdAt: .now()) + let modelSyncedEvent = ModelSyncedEvent( + modelName: "", + isFullSync: true, + isDeltaSync: false, + added: 1, + updated: 1, + deleted: 1 + ) + let mutationEvent = MutationEvent( + id: "", + modelId: "", + modelName: "", + json: "", + mutationType: .create, + createdAt: .now() + ) let receivedMutationEvent = expectation(description: "Received mutationEvent event") let receivedModelSyncedEvent = expectation(description: "Received ModelSynced event") let receivedSyncQueriesReadyEvent = expectation(description: "Received syncQueries event") diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsBase.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsBase.swift index bdd3ef26ac..0928490153 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsBase.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsBase.swift @@ -38,7 +38,7 @@ class StorageEngineTestsBase: XCTestCase { } return saveResult } - + func saveModelSynchronous(model: M) async -> DataStoreResult { let saveFinished = expectation(description: "Save finished") var result: DataStoreResult? @@ -62,7 +62,7 @@ class StorageEngineTestsBase: XCTestCase { } } } - + func querySingleModelSynchronous(modelType: M.Type, predicate: QueryPredicate) -> DataStoreResult { let result = queryModelSynchronous(modelType: modelType, predicate: predicate) @@ -95,7 +95,7 @@ class StorageEngineTestsBase: XCTestCase { } return queryResult } - + func queryModelSynchronous(modelType: M.Type, predicate: QueryPredicate) async -> DataStoreResult<[M]> { let queryFinished = expectation(description: "Query Finished") var result: DataStoreResult<[M]>? @@ -111,14 +111,16 @@ class StorageEngineTestsBase: XCTestCase { } return queryResult } - - func queryAsync(_ modelType: M.Type, - byIdentifier identifier: String, - eagerLoad: Bool = true) async throws -> M? { + + func queryAsync( + _ modelType: M.Type, + byIdentifier identifier: String, + eagerLoad: Bool = true + ) async throws -> M? { let predicate: QueryPredicate = field("id").eq(identifier) return try await queryAsync(modelType, predicate: predicate, eagerLoad: eagerLoad).first } - + func queryAsync(_ modelType: M.Type, predicate: QueryPredicate? = nil, eagerLoad: Bool = true) async throws -> [M] { try await withCheckedThrowingContinuation { continuation in storageEngine.query(modelType, predicate: predicate, eagerLoad: eagerLoad) { qResult in @@ -126,10 +128,12 @@ class StorageEngineTestsBase: XCTestCase { } } } - - func queryStorageAdapter(_ modelType: M.Type, - byIdentifier identifier: String, - eagerLoad: Bool = true) async throws -> M? { + + func queryStorageAdapter( + _ modelType: M.Type, + byIdentifier identifier: String, + eagerLoad: Bool = true + ) async throws -> M? { let predicate: QueryPredicate = field("id").eq(identifier) return try await withCheckedThrowingContinuation { continuation in storageAdapter.query(modelType, predicate: predicate) { result in @@ -138,17 +142,21 @@ class StorageEngineTestsBase: XCTestCase { }.first } - func deleteModelSynchronousOrFailOtherwise(modelType: M.Type, - withId id: String, - where predicate: QueryPredicate? = nil, - timeout: TimeInterval = 1) -> DataStoreResult { - let result = deleteModelSynchronous(modelType: modelType, - withId: id, - where: predicate, - timeout: timeout) + func deleteModelSynchronousOrFailOtherwise( + modelType: M.Type, + withId id: String, + where predicate: QueryPredicate? = nil, + timeout: TimeInterval = 1 + ) -> DataStoreResult { + let result = deleteModelSynchronous( + modelType: modelType, + withId: id, + where: predicate, + timeout: timeout + ) switch result { case .success(let model): - if let model = model { + if let model { return .success(model) } else { return .failure(causedBy: "") @@ -158,21 +166,25 @@ class StorageEngineTestsBase: XCTestCase { } } - func deleteModelSynchronous(modelType: M.Type, - withId id: String, - where predicate: QueryPredicate? = nil, - timeout: TimeInterval = 10) -> DataStoreResult { + func deleteModelSynchronous( + modelType: M.Type, + withId id: String, + where predicate: QueryPredicate? = nil, + timeout: TimeInterval = 10 + ) -> DataStoreResult { let deleteFinished = expectation(description: "Delete Finished") var result: DataStoreResult? - storageEngine.delete(modelType, - modelSchema: modelType.schema, - withId: id, - condition: predicate, - completion: { dResult in + storageEngine.delete( + modelType, + modelSchema: modelType.schema, + withId: id, + condition: predicate, + completion: { dResult in result = dResult deleteFinished.fulfill() - }) + } + ) wait(for: [deleteFinished], timeout: timeout) guard let deleteResult = result else { @@ -180,15 +192,19 @@ class StorageEngineTestsBase: XCTestCase { } return deleteResult } - - func deleteAsync(modelType: M.Type, - withId id: String, - where predicate: QueryPredicate? = nil) async throws -> M? { + + func deleteAsync( + modelType: M.Type, + withId id: String, + where predicate: QueryPredicate? = nil + ) async throws -> M? { try await withCheckedThrowingContinuation { continuation in - storageEngine.delete(modelType, - modelSchema: modelType.schema, - withId: id, - condition: predicate) { dResult in + storageEngine.delete( + modelType, + modelSchema: modelType.schema, + withId: id, + condition: predicate + ) { dResult in continuation.resume(with: dResult) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsDelete.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsDelete.swift index 14e44c62ac..efa786e685 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsDelete.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsDelete.swift @@ -27,11 +27,13 @@ class StorageEngineTestsDelete: StorageEngineTestsBase { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: Team.self) ModelRegistry.register(modelType: Project.self) @@ -60,8 +62,10 @@ class StorageEngineTestsDelete: StorageEngineTestsBase { func testDeleteSuccessWhenItemDoesNotExist() { let teamA = Team(name: "A-Team") let projectA = Project(name: "ProjectA", team: teamA) - let result = deleteModelSynchronous(modelType: Project.self, - withId: projectA.id) + let result = deleteModelSynchronous( + modelType: Project.self, + withId: projectA.id + ) switch result { case .success(let model): guard model == nil else { @@ -77,9 +81,11 @@ class StorageEngineTestsDelete: StorageEngineTestsBase { let teamA = Team(name: "A-Team") let projectA = Project(name: "ProjectA", team: teamA) let project = Project.keys - let result = deleteModelSynchronous(modelType: Project.self, - withId: projectA.id, - where: project.name == "ProjectA") + let result = deleteModelSynchronous( + modelType: Project.self, + withId: projectA.id, + where: project.name == "ProjectA" + ) switch result { case .success(let model): guard model == nil else { @@ -111,9 +117,11 @@ class StorageEngineTestsDelete: StorageEngineTestsBase { return } let project = Project.keys - let result = deleteModelSynchronous(modelType: Project.self, - withId: projectA.id, - where: project.name == "NotProjectA") + let result = deleteModelSynchronous( + modelType: Project.self, + withId: projectA.id, + where: project.name == "NotProjectA" + ) switch result { case .success: @@ -163,9 +171,11 @@ class StorageEngineTestsDelete: StorageEngineTestsBase { } let project = Project.keys - guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: Project.self, - withId: projectA.id, - where: project.name == "ProjectA") else { + guard case .success = deleteModelSynchronousOrFailOtherwise( + modelType: Project.self, + withId: projectA.id, + where: project.name == "ProjectA" + ) else { XCTFail("Failed to delete projectA") return } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasMany.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasMany.swift index 98234107dc..859dc66a78 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasMany.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasMany.swift @@ -28,11 +28,13 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: Restaurant.self) ModelRegistry.register(modelType: Menu.self) ModelRegistry.register(modelType: Dish.self) @@ -83,8 +85,10 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { } guard case .success = - querySingleModelSynchronous(modelType: Restaurant.self, - predicate: Restaurant.keys.id == dreamRestaurant.id) else { + querySingleModelSynchronous( + modelType: Restaurant.self, + predicate: Restaurant.keys.id == dreamRestaurant.id + ) else { XCTFail("Failed to query Restaurant") return } @@ -106,8 +110,10 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { receivedMutationEvent.fulfill() completion(.success(submittedMutationEvent)) } - guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: Restaurant.self, - withId: dreamRestaurant.id) else { + guard case .success = deleteModelSynchronousOrFailOtherwise( + modelType: Restaurant.self, + withId: dreamRestaurant.id + ) else { XCTFail("Failed to delete restaurant") return } @@ -169,22 +175,28 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { } // Query individually without lazy loading and verify counts. guard case .success(let savedRestaurant) = - querySingleModelSynchronous(modelType: Restaurant.self, - predicate: Restaurant.keys.id == restaurant1.id) else { + querySingleModelSynchronous( + modelType: Restaurant.self, + predicate: Restaurant.keys.id == restaurant1.id + ) else { XCTFail("Failed to query Restaurant") return } XCTAssertEqual(savedRestaurant.id, restaurant1.id) guard case .success(let menus) = - queryModelSynchronous(modelType: Menu.self, - predicate: QueryPredicateConstant.all) else { + queryModelSynchronous( + modelType: Menu.self, + predicate: QueryPredicateConstant.all + ) else { XCTFail("Failed to query menus") return } XCTAssertEqual(menus.count, numberOfMenus) guard case .success(let dishes) = - queryModelSynchronous(modelType: Dish.self, - predicate: QueryPredicateConstant.all) else { + queryModelSynchronous( + modelType: Dish.self, + predicate: QueryPredicateConstant.all + ) else { XCTFail("Failed to query dishes") return } @@ -198,9 +210,11 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { receivedMutationEvent.fulfill() completion(.success(submittedMutationEvent)) } - guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: Restaurant.self, - withId: restaurant1.id, - timeout: 100) else { + guard case .success = deleteModelSynchronousOrFailOtherwise( + modelType: Restaurant.self, + withId: restaurant1.id, + timeout: 100 + ) else { XCTFail("Failed to delete restaurant") return } @@ -240,8 +254,10 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { } } - guard case .failure(let error) = deleteModelSynchronousOrFailOtherwise(modelType: Restaurant.self, - withId: restaurant1.id) else { + guard case .failure(let error) = deleteModelSynchronousOrFailOtherwise( + modelType: Restaurant.self, + withId: restaurant1.id + ) else { XCTFail("Deleting should have failed due to our mock") return } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasOne.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasOne.swift index 2627faa3a0..4e5e6ed2e7 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasOne.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasOne.swift @@ -27,11 +27,13 @@ class StorageEngineTestsHasOne: StorageEngineTestsBase { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: Team.self) ModelRegistry.register(modelType: Project.self) @@ -81,7 +83,7 @@ class StorageEngineTestsHasOne: StorageEngineTestsBase { saveFinished.fulfill() } guard case .failure(let error) = result, - case . invalidCondition(let errorDescription, let recoverySuggestion, _) = error else { + case .invalidCondition(let errorDescription, let recoverySuggestion, _) = error else { XCTFail("Expected failure with .invalidCondition, got \(result)") return } @@ -127,8 +129,10 @@ class StorageEngineTestsHasOne: StorageEngineTestsBase { mutationEventOnProject.fulfill() completion(.success(submittedMutationEvent)) } - guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: Project.self, - withId: projectA.id) else { + guard case .success = deleteModelSynchronousOrFailOtherwise( + modelType: Project.self, + withId: projectA.id + ) else { XCTFail("Failed to delete projectA") return } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsLazyPostComment4V2Tests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsLazyPostComment4V2Tests.swift index 62f06849b6..c6425bb0fb 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsLazyPostComment4V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsLazyPostComment4V2Tests.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation import SQLite import XCTest @@ -15,28 +14,30 @@ import XCTest @testable import AWSDataStorePlugin final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, SharedTestCasesPostComment4V2 { - + override func setUp() { super.setUp() Amplify.Logging.logLevel = .verbose - + let validAPIPluginKey = "MockAPICategoryPlugin" let validAuthPluginKey = "MockAuthCategoryPlugin" do { connection = try Connection(.inMemory) storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) - + syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) - + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) + ModelListDecoderRegistry.registerDecoder(DataStoreListDecoder.self) ModelProviderRegistry.registerDecoder(DataStoreModelDecoder.self) - + ModelRegistry.register(modelType: LazyParentPost4V2.self) ModelRegistry.register(modelType: LazyChildComment4V2.self) do { @@ -50,7 +51,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S return } } - + func testSaveCommentThenQueryComment() async throws { let comment = LazyChildComment4V2(content: "content") let savedComment = try await saveAsync(comment) @@ -58,13 +59,15 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S switch savedComment._post.modelProvider.getState() { case .notLoaded(let identifiers): XCTAssertNil(identifiers) - + case .loaded: XCTFail("should be loaded, with `nil` element") } - guard let queriedComment = try await queryAsync(LazyChildComment4V2.self, - byIdentifier: comment.id, - eagerLoad: true) else { + guard let queriedComment = try await queryAsync( + LazyChildComment4V2.self, + byIdentifier: comment.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved comment") return } @@ -76,15 +79,17 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("should be not loaded, with `nil` identifiers") } } - + func testSavePostThenQueryPost() async throws { let post = LazyParentPost4V2(title: "title") let savedPost = try await saveAsync(post) XCTAssertEqual(savedPost.id, post.id) - - guard let queriedPost = try await queryAsync(LazyParentPost4V2.self, - byIdentifier: post.id, - eagerLoad: true) else { + + guard let queriedPost = try await queryAsync( + LazyParentPost4V2.self, + byIdentifier: post.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved post") return } @@ -99,39 +104,45 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("missing comments") } } - + func testSaveMultipleThenQueryComments() async throws { try await saveAsync(LazyChildComment4V2(content: "content")) try await saveAsync(LazyChildComment4V2(content: "content")) - - let comments = try await queryAsync(LazyChildComment4V2.self, - eagerLoad: true) + + let comments = try await queryAsync( + LazyChildComment4V2.self, + eagerLoad: true + ) XCTAssertEqual(comments.count, 2) } - + func testSaveMultipleThenQueryPosts() async throws { try await saveAsync(LazyParentPost4V2(title: "title")) try await saveAsync(LazyParentPost4V2(title: "title")) - - let comments = try await queryAsync(LazyParentPost4V2.self, - eagerLoad: true) + + let comments = try await queryAsync( + LazyParentPost4V2.self, + eagerLoad: true + ) XCTAssertEqual(comments.count, 2) } - + func testCommentWithPost_TranslateToStorageValues() async throws { let post = LazyParentPost4V2(id: "postId", title: "title") _ = try await saveAsync(post) var comment = LazyChildComment4V2(content: "content", post: post) - + // Model.sqlValues tesitng - let sqlValues = comment.sqlValues(for: LazyChildComment4V2.schema.columns, - modelSchema: LazyChildComment4V2.schema) + let sqlValues = comment.sqlValues( + for: LazyChildComment4V2.schema.columns, + modelSchema: LazyChildComment4V2.schema + ) XCTAssertEqual(sqlValues[0] as? String, comment.id) XCTAssertEqual(sqlValues[1] as? String, comment.content) XCTAssertNil(sqlValues[2]) // createdAt XCTAssertNil(sqlValues[3]) // updatedAt XCTAssertEqual(sqlValues[4] as? String, post.id) - + // Insert let insertStatement = InsertStatement(model: comment, modelSchema: LazyChildComment4V2.schema) XCTAssertEqual(insertStatement.variables[0] as? String, comment.id) @@ -140,61 +151,75 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTAssertNil(insertStatement.variables[3]) // updatedAt XCTAssertEqual(insertStatement.variables[4] as? String, post.id) _ = try connection.prepare(insertStatement.stringValue).run(insertStatement.variables) - + // Update comment.content = "updatedContent" - let updateStatement = UpdateStatement(model: comment, - modelSchema: LazyChildComment4V2.schema, - condition: nil) + let updateStatement = UpdateStatement( + model: comment, + modelSchema: LazyChildComment4V2.schema, + condition: nil + ) _ = try connection.prepare(updateStatement.stringValue).run(updateStatement.variables) - + // Select with eagerLoad true - let selectStatement = SelectStatement(from: LazyChildComment4V2.schema, - predicate: field("id").eq(comment.id), - sort: nil, - paginationInput: nil, - eagerLoad: true) + let selectStatement = SelectStatement( + from: LazyChildComment4V2.schema, + predicate: field("id").eq(comment.id), + sort: nil, + paginationInput: nil, + eagerLoad: true + ) let rows = try connection.prepare(selectStatement.stringValue).run(selectStatement.variables) - _ = try rows.convertToModelValues(to: LazyChildComment4V2.self, - withSchema: LazyChildComment4V2.schema, - using: selectStatement) - let comments = try rows.convert(to: LazyChildComment4V2.self, - withSchema: LazyChildComment4V2.schema, - using: selectStatement) + _ = try rows.convertToModelValues( + to: LazyChildComment4V2.self, + withSchema: LazyChildComment4V2.schema, + using: selectStatement + ) + let comments = try rows.convert( + to: LazyChildComment4V2.self, + withSchema: LazyChildComment4V2.schema, + using: selectStatement + ) XCTAssertEqual(comments.count, 1) guard let comment = comments.first else { XCTFail("Should retrieve single comment") return } - + XCTAssertEqual(comment.content, "updatedContent") switch comment._post.modelProvider.getState() { case .notLoaded: XCTFail("Should have been loaded") case .loaded(let post): - guard let post = post else { + guard let post else { XCTFail("Loaded with no post") return } XCTAssertEqual(post.id, "postId") XCTAssertEqual(post.title, "title") } - + // Select with eagerLoad false - let selectStatement2 = SelectStatement(from: LazyChildComment4V2.schema, - predicate: field("id").eq(comment.id), - sort: nil, - paginationInput: nil, - eagerLoad: false) + let selectStatement2 = SelectStatement( + from: LazyChildComment4V2.schema, + predicate: field("id").eq(comment.id), + sort: nil, + paginationInput: nil, + eagerLoad: false + ) let rows2 = try connection.prepare(selectStatement2.stringValue).run(selectStatement2.variables) - _ = try rows2.convertToModelValues(to: LazyChildComment4V2.self, - withSchema: LazyChildComment4V2.schema, - using: selectStatement2, - eagerLoad: false) - let comments2 = try rows2.convert(to: LazyChildComment4V2.self, - withSchema: LazyChildComment4V2.schema, - using: selectStatement2, - eagerLoad: false) + _ = try rows2.convertToModelValues( + to: LazyChildComment4V2.self, + withSchema: LazyChildComment4V2.schema, + using: selectStatement2, + eagerLoad: false + ) + let comments2 = try rows2.convert( + to: LazyChildComment4V2.self, + withSchema: LazyChildComment4V2.schema, + using: selectStatement2, + eagerLoad: false + ) XCTAssertEqual(comments.count, 1) guard let comment2 = comments2.first else { XCTFail("Should retrieve single comment") @@ -204,7 +229,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTAssertEqual(comment2.content, "updatedContent") switch comment2._post.modelProvider.getState() { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { + guard let identifiers else { XCTFail("Missing identifiers") return } @@ -213,13 +238,13 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("Should be not loaded") } } - + func testSaveCommentWithPostThenQueryCommentAndAccessPost() async throws { let post = LazyParentPost4V2(title: "title") try await saveAsync(post) let comment = LazyChildComment4V2(content: "content", post: post) let savedComment = try await saveAsync(comment) - + // The post should be eager loaded by default on a save switch savedComment._post.modelProvider.getState() { case .notLoaded: @@ -231,11 +256,13 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S } XCTAssertEqual(loadedPost.id, post.id) } - + // The query with eagerLoad should load the post - guard let queriedCommentEagerLoadedPost = try await queryAsync(LazyChildComment4V2.self, - byIdentifier: comment.id, - eagerLoad: true) else { + guard let queriedCommentEagerLoadedPost = try await queryAsync( + LazyChildComment4V2.self, + byIdentifier: comment.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved comment") return } @@ -249,11 +276,13 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S } XCTAssertEqual(loadedPost.id, post.id) } - + // The query with eagerLoad false should create a not loaded post for lazy loading - guard let queriedCommentLazyLoadedPost = try await queryAsync(LazyChildComment4V2.self, - byIdentifier: comment.id, - eagerLoad: false) else { + guard let queriedCommentLazyLoadedPost = try await queryAsync( + LazyChildComment4V2.self, + byIdentifier: comment.id, + eagerLoad: false + ) else { XCTFail("Failed to query saved comment") return } @@ -266,7 +295,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S switch queriedCommentLazyLoadedPost._post.modelProvider.getState() { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { + guard let identifiers else { XCTFail("Missing identifiers") return } @@ -275,16 +304,18 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("lazy loaded post should be not loaded") } } - + func testSaveCommentWithPostThenQueryPostAndAccessComments() async throws { let post = LazyParentPost4V2(title: "title") try await saveAsync(post) let comment = LazyChildComment4V2(content: "content", post: post) try await saveAsync(comment) - - guard let queriedPost = try await queryAsync(LazyParentPost4V2.self, - byIdentifier: post.id, - eagerLoad: true) else { + + guard let queriedPost = try await queryAsync( + LazyParentPost4V2.self, + byIdentifier: post.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved post") return } @@ -293,7 +324,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("Failed to get comments from queried post") return } - + switch comments.listProvider.getState() { case .notLoaded(let associatedIdentifiers, let associatedFields): XCTAssertEqual(associatedIdentifiers, [post.id]) @@ -302,7 +333,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("Should not be loaded") } } - + func testSaveMultipleCommentWithPostThenQueryCommentsAndAccessPost() async throws { let post1 = LazyParentPost4V2(id: "postId1", title: "title1") try await saveAsync(post1) @@ -315,8 +346,10 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S try await saveAsync(comment2) // Query with eagerLoad true - var comments = try await queryAsync(LazyChildComment4V2.self, - eagerLoad: true) + var comments = try await queryAsync( + LazyChildComment4V2.self, + eagerLoad: true + ) XCTAssertEqual(comments.count, 2) guard let comment1 = comments.first(where: { $0.id == "id1" }) else { @@ -341,10 +374,12 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTAssertEqual(post!.id, "postId2") XCTAssertEqual(post!.title, "title2") } - + // Query with eagerLoad false - comments = try await queryAsync(LazyChildComment4V2.self, - eagerLoad: false) + comments = try await queryAsync( + LazyChildComment4V2.self, + eagerLoad: false + ) XCTAssertEqual(comments.count, 2) guard let comment1 = comments.first(where: { $0.id == "id1" }) else { @@ -357,7 +392,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S } switch comment1._post.modelProvider.getState() { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { + guard let identifiers else { XCTFail("Missing identifiers") return } @@ -367,7 +402,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S } switch comment2._post.modelProvider.getState() { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { + guard let identifiers else { XCTFail("Missing identifiers") return } @@ -376,7 +411,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("Should be not loaded") } } - + func testSaveMultipleCommentWithPostThenQueryPostAndAccessComments() async throws { let post1 = LazyParentPost4V2(id: "postId1", title: "title1") try await saveAsync(post1) @@ -386,7 +421,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S try await saveAsync(post2) let comment2 = LazyChildComment4V2(id: "id2", content: "content", post: post2) try await saveAsync(comment2) - + var posts = try await queryAsync(LazyParentPost4V2.self) XCTAssertEqual(posts.count, 2) guard let postId1 = posts.first(where: { $0.id == "postId1" }) else { @@ -401,7 +436,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("Failed to get comments from post1") return } - + switch comments1.listProvider.getState() { case .notLoaded(let associatedIdentifiers, let associatedFields): XCTAssertEqual(associatedIdentifiers, [post1.id]) @@ -409,7 +444,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S case .loaded: XCTFail("Should not be loaded") } - + guard let comments2 = postId2.comments else { XCTFail("Failed to get comments from post2") return diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsManyToMany.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsManyToMany.swift index 4280e73a26..1d6604be01 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsManyToMany.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsManyToMany.swift @@ -27,11 +27,13 @@ class StorageEngineTestsManyToMany: StorageEngineTestsBase { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: M2MPost.self) ModelRegistry.register(modelType: M2MPostEditor.self) ModelRegistry.register(modelType: M2MUser.self) @@ -73,20 +75,26 @@ class StorageEngineTestsManyToMany: StorageEngineTestsBase { } guard case .success = - querySingleModelSynchronous(modelType: M2MPost.self, - predicate: M2MPost.keys.id == post1.id) else { + querySingleModelSynchronous( + modelType: M2MPost.self, + predicate: M2MPost.keys.id == post1.id + ) else { XCTFail("Failed to query M2MPost") return } guard case .success = - querySingleModelSynchronous(modelType: M2MPostEditor.self, - predicate: M2MPostEditor.keys.id == postEditors1.id) else { + querySingleModelSynchronous( + modelType: M2MPostEditor.self, + predicate: M2MPostEditor.keys.id == postEditors1.id + ) else { XCTFail("Failed to query M2MPostEditor") return } guard case .success = - querySingleModelSynchronous(modelType: M2MUser.self, - predicate: M2MUser.keys.id == user1.id) else { + querySingleModelSynchronous( + modelType: M2MUser.self, + predicate: M2MUser.keys.id == user1.id + ) else { XCTFail("Failed to query M2MUser") return } @@ -98,8 +106,10 @@ class StorageEngineTestsManyToMany: StorageEngineTestsBase { mutationEvents.fulfill() completion(.success(submittedMutationEvent)) } - guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: M2MPost.self, - withId: post1.id) else { + guard case .success = deleteModelSynchronousOrFailOtherwise( + modelType: M2MPost.self, + withId: post1.id + ) else { XCTFail("Failed to delete post1") return } @@ -130,20 +140,26 @@ class StorageEngineTestsManyToMany: StorageEngineTestsBase { } guard case .success = - querySingleModelSynchronous(modelType: M2MPost.self, - predicate: M2MPost.keys.id == post1.id) else { + querySingleModelSynchronous( + modelType: M2MPost.self, + predicate: M2MPost.keys.id == post1.id + ) else { XCTFail("Failed to query M2MPost") return } guard case .success = - querySingleModelSynchronous(modelType: M2MPostEditor.self, - predicate: M2MPostEditor.keys.id == postEditors1.id) else { + querySingleModelSynchronous( + modelType: M2MPostEditor.self, + predicate: M2MPostEditor.keys.id == postEditors1.id + ) else { XCTFail("Failed to query M2MPostEditor") return } guard case .success = - querySingleModelSynchronous(modelType: M2MUser.self, - predicate: M2MUser.keys.id == user1.id) else { + querySingleModelSynchronous( + modelType: M2MUser.self, + predicate: M2MUser.keys.id == user1.id + ) else { XCTFail("Failed to query M2MUser") return } @@ -155,8 +171,10 @@ class StorageEngineTestsManyToMany: StorageEngineTestsBase { mutationEvents.fulfill() completion(.success(submittedMutationEvent)) } - guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: M2MUser.self, - withId: user1.id) else { + guard case .success = deleteModelSynchronousOrFailOtherwise( + modelType: M2MUser.self, + withId: user1.id + ) else { XCTFail("Failed to delete post1") return } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsOptionalAssociation.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsOptionalAssociation.swift index ef740ed914..9b2dc3f91f 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsOptionalAssociation.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsOptionalAssociation.swift @@ -27,11 +27,13 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: Blog8.self) ModelRegistry.register(modelType: Post8.self) ModelRegistry.register(modelType: Comment8.self) @@ -56,8 +58,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { } guard case let .success(queriedComment) = - querySingleModelSynchronous(modelType: Comment8.self, - predicate: Comment8.keys.id == comment.id) else { + querySingleModelSynchronous( + modelType: Comment8.self, + predicate: Comment8.keys.id == comment.id + ) else { XCTFail("Failed to query post") return } @@ -73,8 +77,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { } guard case let .success(queriedPost) = - querySingleModelSynchronous(modelType: Post8.self, - predicate: Post8.keys.id == post.id) else { + querySingleModelSynchronous( + modelType: Post8.self, + predicate: Post8.keys.id == post.id + ) else { XCTFail("Failed to query post") return } @@ -92,8 +98,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { } guard case let .success(queriedBlog) = - querySingleModelSynchronous(modelType: Blog8.self, - predicate: Blog8.keys.id == blog.id) else { + querySingleModelSynchronous( + modelType: Blog8.self, + predicate: Blog8.keys.id == blog.id + ) else { XCTFail("Failed to query blog") return } @@ -119,8 +127,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { return } guard case let .success(queriedComment) = - querySingleModelSynchronous(modelType: Comment8.self, - predicate: Comment8.keys.id == comment.id) else { + querySingleModelSynchronous( + modelType: Comment8.self, + predicate: Comment8.keys.id == comment.id + ) else { XCTFail("Failed to query post") return } @@ -148,8 +158,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { } guard case let .success(updatedPost) = - querySingleModelSynchronous(modelType: Post8.self, - predicate: Post8.keys.id == post.id) else { + querySingleModelSynchronous( + modelType: Post8.self, + predicate: Post8.keys.id == post.id + ) else { XCTFail("Failed to query post") return } @@ -180,8 +192,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { } guard case let .success(queriedComment) = - querySingleModelSynchronous(modelType: Comment8.self, - predicate: Comment8.keys.id == comment.id) else { + querySingleModelSynchronous( + modelType: Comment8.self, + predicate: Comment8.keys.id == comment.id + ) else { XCTFail("Failed to query comment") return } @@ -203,8 +217,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { return } guard case let .success(queriedComment) = - querySingleModelSynchronous(modelType: Comment8.self, - predicate: Comment8.keys.id == comment.id) else { + querySingleModelSynchronous( + modelType: Comment8.self, + predicate: Comment8.keys.id == comment.id + ) else { XCTFail("Failed to query comment") return } @@ -217,8 +233,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { return } guard case let .success(queriedComment) = - querySingleModelSynchronous(modelType: Comment8.self, - predicate: Comment8.keys.id == comment.id) else { + querySingleModelSynchronous( + modelType: Comment8.self, + predicate: Comment8.keys.id == comment.id + ) else { XCTFail("Failed to query comment") return } @@ -229,8 +247,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { return } guard case let .success(queriedPost) = - querySingleModelSynchronous(modelType: Post8.self, - predicate: Post8.keys.id == post.id) else { + querySingleModelSynchronous( + modelType: Post8.self, + predicate: Post8.keys.id == post.id + ) else { XCTFail("Failed to query post") return } @@ -243,18 +263,22 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { XCTFail("Failed to save post") return } - let statement = SelectStatement(from: Post8.schema, - predicate: nil, - sort: nil, - paginationInput: nil) + let statement = SelectStatement( + from: Post8.schema, + predicate: nil, + sort: nil, + paginationInput: nil + ) let rows = try connection.prepare(statement.stringValue).run(statement.variables) // Eager loading selects all fields and associated fields. The number of columns is the number of fields of // Post8 plus it's associated field Blog8. This excludes the association itself, ie. post.blog is excluded // and blog.posts is excluded. So there are 6 Post8 fields and 6 Blog8 fields. XCTAssertEqual(rows.columnCount, 12) - let results: [Post8] = try rows.convert(to: Post8.self, - withSchema: Post8.schema, - using: statement) + let results: [Post8] = try rows.convert( + to: Post8.self, + withSchema: Post8.schema, + using: statement + ) XCTAssertNotNil(results) // The result is the single post which was saved and queried @@ -279,14 +303,18 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { return } - let statement = SelectStatement(from: Post8.schema, - predicate: nil, - sort: nil, - paginationInput: nil) + let statement = SelectStatement( + from: Post8.schema, + predicate: nil, + sort: nil, + paginationInput: nil + ) let rows = try connection.prepare(statement.stringValue).run(statement.variables) - let results: [Post8] = try rows.convert(to: Post8.self, - withSchema: Post8.schema, - using: statement) + let results: [Post8] = try rows.convert( + to: Post8.self, + withSchema: Post8.schema, + using: statement + ) XCTAssertNotNil(results) XCTAssertEqual(results.count, 1) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsPostComment4V2Tests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsPostComment4V2Tests.swift index 25db881a49..00459a4cbd 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsPostComment4V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsPostComment4V2Tests.swift @@ -27,15 +27,17 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) - + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) + ModelListDecoderRegistry.registerDecoder(DataStoreListDecoder.self) ModelProviderRegistry.registerDecoder(DataStoreModelDecoder.self) - + ModelRegistry.register(modelType: ParentPost4V2.self) ModelRegistry.register(modelType: ChildComment4V2.self) do { @@ -55,8 +57,9 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share let expectedSuccess = expectation(description: "Simulated success on mutation event submitted to sync engine") let post = ParentPost4V2( id: "postId1", - title: "title1") - + title: "title1" + ) + syncEngine.setCallbackOnSubmit { submittedMutationEvent, completion in receivedMutationEvent.fulfill() if submittedMutationEvent.modelId == post.id { @@ -69,9 +72,9 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share } try await saveAsync(post) await fulfillment(of: [receivedMutationEvent, expectedSuccess], timeout: 1) - + } - + /// A save should fail if the corresponding MutationEvent could not be submitted to the syncEngine. func testSavePostFailDueToSyncEngineMissing() async throws { storageEngine.syncEngine = nil @@ -79,7 +82,8 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share try await saveAsync( ParentPost4V2( id: "postId1", - title: "title1")) + title: "title1" + )) XCTFail("Expected to fail when sync engine is `nil`") } catch { guard let dataStoreError = error as? DataStoreError else { @@ -88,112 +92,129 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share } XCTAssertEqual( dataStoreError.errorDescription, - "No SyncEngine available to sync mutation event, rollback save.") + "No SyncEngine available to sync mutation event, rollback save." + ) } } - + func testSaveCommentThenQueryComment() async throws { let comment = ChildComment4V2(content: "content") let savedComment = try await saveAsync(comment) XCTAssertEqual(savedComment.id, comment.id) - - guard let queriedComment = try await queryAsync(ChildComment4V2.self, - byIdentifier: comment.id, - eagerLoad: true) else { + + guard let queriedComment = try await queryAsync( + ChildComment4V2.self, + byIdentifier: comment.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved comment") return } XCTAssertEqual(queriedComment.id, comment.id) } - + func testSavePostThenQueryPost() async throws { let post = ParentPost4V2(title: "title") let savedPost = try await saveAsync(post) XCTAssertEqual(savedPost.id, post.id) - - guard let queriedPost = try await queryAsync(ParentPost4V2.self, - byIdentifier: post.id, - eagerLoad: true) else { + + guard let queriedPost = try await queryAsync( + ParentPost4V2.self, + byIdentifier: post.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved post") return } XCTAssertEqual(queriedPost.id, post.id) } - + func testSaveMultipleThenQueryComments() async throws { try await saveAsync(ChildComment4V2(content: "content")) try await saveAsync(ChildComment4V2(content: "content")) - + let comments = try await queryAsync(ChildComment4V2.self, eagerLoad: true) XCTAssertEqual(comments.count, 2) } - + func testSaveMultipleThenQueryPosts() async throws { try await saveAsync(ParentPost4V2(title: "title")) try await saveAsync(ParentPost4V2(title: "title")) - + let comments = try await queryAsync(ParentPost4V2.self, eagerLoad: true) XCTAssertEqual(comments.count, 2) } - + // TODO: clean up this test func testCommentWithPost_TranslateToStorageValues() async throws { let post = ParentPost4V2(id: "postId", title: "title") _ = try await saveAsync(post) var comment = ChildComment4V2(content: "content", post: post) - + // Model.sqlValues testing - let sqlValues = comment.sqlValues(for: ChildComment4V2.schema.columns, - modelSchema: ChildComment4V2.schema) + let sqlValues = comment.sqlValues( + for: ChildComment4V2.schema.columns, + modelSchema: ChildComment4V2.schema + ) XCTAssertEqual(sqlValues[0] as? String, comment.id) XCTAssertEqual(sqlValues[1] as? String, comment.content) XCTAssertNil(sqlValues[2]) // createdAt XCTAssertNil(sqlValues[3]) // updatedAt XCTAssertEqual(sqlValues[4] as? String, post.id) - + // InsertStatement testing - let insertStatement = InsertStatement(model: comment, - modelSchema: ChildComment4V2.schema) + let insertStatement = InsertStatement( + model: comment, + modelSchema: ChildComment4V2.schema + ) XCTAssertEqual(insertStatement.variables[0] as? String, comment.id) XCTAssertEqual(insertStatement.variables[1] as? String, comment.content) XCTAssertNil(insertStatement.variables[2]) // createdAt XCTAssertNil(insertStatement.variables[3]) // updatedAt XCTAssertEqual(insertStatement.variables[4] as? String, post.id) _ = try connection.prepare(insertStatement.stringValue).run(insertStatement.variables) - + // UpdateStatement testing comment.content = "updatedContent" - let updateStatement = UpdateStatement(model: comment, - modelSchema: ChildComment4V2.schema, - condition: nil) + let updateStatement = UpdateStatement( + model: comment, + modelSchema: ChildComment4V2.schema, + condition: nil + ) _ = try connection.prepare(updateStatement.stringValue).run(updateStatement.variables) - - + + // Select - let selectStatement = SelectStatement(from: ChildComment4V2.schema, - predicate: field("id").eq(comment.id), - sort: nil, - paginationInput: nil, - eagerLoad: true) + let selectStatement = SelectStatement( + from: ChildComment4V2.schema, + predicate: field("id").eq(comment.id), + sort: nil, + paginationInput: nil, + eagerLoad: true + ) let rows = try connection.prepare(selectStatement.stringValue).run(selectStatement.variables) print(rows) - let result: [ModelValues] = try rows.convertToModelValues(to: ChildComment4V2.self, - withSchema: ChildComment4V2.schema, - using: selectStatement) + let result: [ModelValues] = try rows.convertToModelValues( + to: ChildComment4V2.self, + withSchema: ChildComment4V2.schema, + using: selectStatement + ) print(result) XCTAssertEqual(result.count, 1) // asert content is "updatedContent" } - + func testSaveCommentWithPostThenQueryCommentAndAccessPost() async throws { let post = ParentPost4V2(title: "title") _ = try await saveAsync(post) let comment = ChildComment4V2(content: "content", post: post) _ = try await saveAsync(comment) - - guard let queriedComment = try await queryAsync(ChildComment4V2.self, - byIdentifier: comment.id, - eagerLoad: true) else { + + guard let queriedComment = try await queryAsync( + ChildComment4V2.self, + byIdentifier: comment.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved comment") return } @@ -204,16 +225,18 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share } XCTAssertEqual(eagerLoadedPost.id, post.id) } - + func testSaveCommentWithPostThenQueryPostAndAccessComments() async throws { let post = ParentPost4V2(title: "title") _ = try await saveAsync(post) let comment = ChildComment4V2(content: "content", post: post) _ = try await saveAsync(comment) - - guard let queriedPost = try await queryAsync(ParentPost4V2.self, - byIdentifier: post.id, - eagerLoad: true) else { + + guard let queriedPost = try await queryAsync( + ParentPost4V2.self, + byIdentifier: post.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved post") return } @@ -232,7 +255,7 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share XCTFail("Should not be loaded") } } - + func testSaveMultipleCommentWithPostThenQueryCommentsAndAccessPost() async throws { let post1 = try await saveAsync(ParentPost4V2(id: "postId1", title: "title1")) _ = try await saveAsync(ChildComment4V2(id: "id1", content: "content", post: post1)) @@ -261,7 +284,7 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share XCTAssertEqual(post2.id, "postId2") XCTAssertEqual(post2.title, "title2") } - + func testSaveMultipleCommentWithPostThenQueryPostAndAccessComments() async throws { let post1 = try await saveAsync(ParentPost4V2(id: "postId1", title: "title1")) _ = try await saveAsync(ChildComment4V2(id: "id1", content: "content", post: post1)) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsSQLiteIndex.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsSQLiteIndex.swift index c13a16895d..c11689fe66 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsSQLiteIndex.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsSQLiteIndex.swift @@ -33,11 +33,13 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: CustomerSecondaryIndexV2.self) ModelRegistry.register(modelType: CustomerMultipleSecondaryIndexV2.self) @@ -74,7 +76,7 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { // 5000 - 0.0032134409993886948 - 0.00478174310119357 // 10000 - 0.0033998960039345548 - 0.006051322101324331 func testQueryPerformanceForModelWithSingleIndex() { - var averageTimeForQuery: Double = 0.0 + var averageTimeForQuery = 0.0 var iterations = 0 measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: false) { iterations += 1 @@ -85,7 +87,8 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { phoneNumber: randomNumericString(length: 10), accountRepresentativeID: randomCapitalCharacterString(length: 10), createdAt: Temporal.DateTime.now(), - updatedAt: Temporal.DateTime.now()) + updatedAt: Temporal.DateTime.now() + ) guard case .success = saveModelSynchronous(model: customer, storageEngine: storageEngine) else { XCTFail("Failed to save customer \(customer)") @@ -102,7 +105,8 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { phoneNumber: phoneNumber, accountRepresentativeID: accountRepresentativeID, createdAt: Temporal.DateTime.now(), - updatedAt: Temporal.DateTime.now()) + updatedAt: Temporal.DateTime.now() + ) guard case .success = saveModelSynchronous(model: uniqueCustomer, storageEngine: storageEngine) else { XCTFail("Failed to save customer \(uniqueCustomer)") @@ -113,9 +117,11 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { let startTimeQuery1 = CFAbsoluteTimeGetCurrent() startMeasuring() - guard case .success = queryModelSynchronous(modelType: CustomerSecondaryIndexV2.self, - predicate: predicate, - storageEngine: storageEngine) else { + guard case .success = queryModelSynchronous( + modelType: CustomerSecondaryIndexV2.self, + predicate: predicate, + storageEngine: storageEngine + ) else { XCTFail("Failed to query customer") return } @@ -149,7 +155,7 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { // 5000 - 0.03966123380087083 - 0.04700456840073457 // 10000 - 0.08497165249864339 - 0.09597435819596285 func testQueryPerformanceForModelWithMultipleIndexes1() { - var averageTimeForQuery: Double = 0.0 + var averageTimeForQuery = 0.0 var iterations = 0 measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: false) { iterations += 1 @@ -161,7 +167,8 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { age: Int.random(in: 1 ..< 100), accountRepresentativeID: randomCapitalCharacterString(length: 10), createdAt: Temporal.DateTime.now(), - updatedAt: Temporal.DateTime.now()) + updatedAt: Temporal.DateTime.now() + ) guard case .success = saveModelSynchronous(model: customer, storageEngine: storageEngine) else { XCTFail("Failed to save customer \(customer)") @@ -179,7 +186,8 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { age: 30, accountRepresentativeID: accountRepresentativeID, createdAt: Temporal.DateTime.now(), - updatedAt: Temporal.DateTime.now()) + updatedAt: Temporal.DateTime.now() + ) guard case .success = saveModelSynchronous(model: uniqueCustomer, storageEngine: storageEngine) else { XCTFail("Failed to save customer \(uniqueCustomer)") @@ -191,9 +199,11 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { let startTimeQuery1 = CFAbsoluteTimeGetCurrent() startMeasuring() - guard case .success = queryModelSynchronous(modelType: CustomerMultipleSecondaryIndexV2.self, - predicate: predicate, - storageEngine: storageEngine) else { + guard case .success = queryModelSynchronous( + modelType: CustomerMultipleSecondaryIndexV2.self, + predicate: predicate, + storageEngine: storageEngine + ) else { XCTFail("Failed to query customer") return } @@ -227,7 +237,7 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { // 5000 - 0.011302956998406444 - 0.013200746997934766 // 10000 - 0.02146193390071858 - 0.025970560003770515 func testQueryPerformanceForModelWithMultipleIndexes2() { - var averageTimeForQuery: Double = 0.0 + var averageTimeForQuery = 0.0 var iterations = 0 measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: false) { iterations += 1 @@ -239,7 +249,8 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { age: Int.random(in: 1 ..< 100), accountRepresentativeID: randomCapitalCharacterString(length: 10), createdAt: Temporal.DateTime.now(), - updatedAt: Temporal.DateTime.now()) + updatedAt: Temporal.DateTime.now() + ) guard case .success = saveModelSynchronous(model: customer, storageEngine: storageEngine) else { XCTFail("Failed to save customer \(customer)") @@ -258,7 +269,8 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { age: age, accountRepresentativeID: accountRepresentativeID, createdAt: Temporal.DateTime.now(), - updatedAt: Temporal.DateTime.now()) + updatedAt: Temporal.DateTime.now() + ) guard case .success = saveModelSynchronous(model: uniqueCustomer, storageEngine: storageEngine) else { XCTFail("Failed to save customer \(uniqueCustomer)") @@ -272,9 +284,11 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { let startTimeQuery1 = CFAbsoluteTimeGetCurrent() startMeasuring() guard case .success = - queryModelSynchronous(modelType: CustomerMultipleSecondaryIndexV2.self, - predicate: predicate, - storageEngine: storageEngine) else { + queryModelSynchronous( + modelType: CustomerMultipleSecondaryIndexV2.self, + predicate: predicate, + storageEngine: storageEngine + ) else { XCTFail("Failed to query customer") return } @@ -329,9 +343,11 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { return saveResult } - func queryModelSynchronous(modelType: M.Type, - predicate: QueryPredicate, - storageEngine: StorageEngine) -> DataStoreResult<[M]> { + func queryModelSynchronous( + modelType: M.Type, + predicate: QueryPredicate, + storageEngine: StorageEngine + ) -> DataStoreResult<[M]> { let queryFinished = expectation(description: "Query Finished") var result: DataStoreResult<[M]>? diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveQueryTaskRunnerTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveQueryTaskRunnerTests.swift index 75ede3ddd9..3d2dce808d 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveQueryTaskRunnerTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveQueryTaskRunnerTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class ObserveQueryTaskRunnerTests: XCTestCase { var storageEngine: MockStorageEngineBehavior! @@ -24,7 +24,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { storageEngine = MockStorageEngineBehavior() dataStorePublisher = DataStorePublisher() } - + /// An item changed observed will be returned in a single snapshot /// /// - Given: The operation has started and the first query has completed. @@ -45,7 +45,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -64,14 +65,14 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 1) let post = try createPost(id: "1") dataStorePublisher.send(input: post) await fulfillment(of: [secondSnapshot], timeout: 10) } - + /// ObserveQuery will send a single snapshot when the sync state toggles /// from false to true. The operation internally listens to `.modelSynced` event from /// the Hub. @@ -98,7 +99,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: dispatchedModelSyncedEvent, - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -122,23 +124,32 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 5) - + dispatchedModelSyncedEvent.set(true) - let modelSyncedEventPayload = HubPayload(eventName: HubPayload.EventName.DataStore.modelSynced, - data: ModelSyncedEvent(modelName: Post.modelName, isFullSync: true, - isDeltaSync: false, added: 0, updated: 0, - deleted: 0)) + let modelSyncedEventPayload = HubPayload( + eventName: HubPayload.EventName.DataStore.modelSynced, + data: ModelSyncedEvent( + modelName: Post.modelName, + isFullSync: true, + isDeltaSync: false, + added: 0, + updated: 0, + deleted: 0 + ) + ) Amplify.Hub.dispatch(to: .dataStore, payload: modelSyncedEventPayload) await fulfillment(of: [secondSnapshot], timeout: 10) - - let modelSyncedEventNotMatch = HubPayload(eventName: HubPayload.EventName.DataStore.modelSynced, - data: ModelSyncedEvent.Builder().modelName) + + let modelSyncedEventNotMatch = HubPayload( + eventName: HubPayload.EventName.DataStore.modelSynced, + data: ModelSyncedEvent.Builder().modelName + ) Amplify.Hub.dispatch(to: .dataStore, payload: modelSyncedEventNotMatch) await fulfillment(of: [thirdSnapshot], timeout: 10) } - + /// ObserveQuery will send the first snapshot with 2 items when storage engine /// is mocked to return 2 items. /// @@ -159,10 +170,13 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) - let post = Post(title: "model1", - content: "content1", - createdAt: .now()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) + let post = Post( + title: "model1", + content: "content1", + createdAt: .now() + ) storageEngine.responders[.query] = QueryResponder(callback: { _ in return .success([post, Post(title: "model1", content: "content1", createdAt: .now())]) }) @@ -177,14 +191,14 @@ class ObserveQueryTaskRunnerTests: XCTestCase { firstSnapshot.fulfill() } } - + } catch { XCTFail("Failed with error \(error)") } } await fulfillment(of: [firstSnapshot], timeout: 10) } - + /// Multiple item changed observed will be returned in a single snapshot /// /// - Given: The operation has started and the first query has completed. @@ -206,7 +220,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -225,7 +240,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 1) let post1 = try createPost(id: "1") @@ -236,7 +251,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher.send(input: post3) await fulfillment(of: [secondSnapshot], timeout: 10) } - + /// Multiple published objects (more than the `.collect` count of 1000) in a relatively short time window /// will cause the operation in test to exceed the limit of 1000 in its collection of items before sending a snapshot. /// The first snapshot will have 1000 items, and subsequent snapshots will follow as the remaining objects are published and processed. @@ -262,7 +277,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -277,7 +293,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { thirdSnapshot.fulfill() } } - + XCTAssertTrue(querySnapshots.count >= 3) XCTAssertTrue(querySnapshots[0].items.count <= querySnapshots[1].items.count) XCTAssertTrue(querySnapshots[1].items.count <= querySnapshots[2].items.count) @@ -287,7 +303,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 1) for postId in 1 ... 1_100 { @@ -299,7 +315,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { snapshots.cancel() await fulfillment(of: [validateSnapshotsComplete], timeout: 1.0) } - + /// Cancelling the subscription will no longer receive snapshots /// /// - Given: subscriber to the operation @@ -322,7 +338,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -340,14 +357,14 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 1) snapshots.cancel() let post1 = try createPost(id: "1") dataStorePublisher.send(input: post1) await fulfillment(of: [secondSnapshot], timeout: 1) } - + /// Cancelling the underlying operation will emit a completion to the subscribers /// /// - Given: subscriber to the operation @@ -371,7 +388,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -397,7 +415,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { await fulfillment(of: [secondSnapshot, completedEvent], timeout: 1) } - + /// ObserveQuery's state should be able to be reset and initial query able to be started again. func testObserveQueryResetStateThenStartObserveQuery() async { let firstSnapshot = expectation(description: "first query snapshot") @@ -411,7 +429,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -428,13 +447,13 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 1) dataStoreStateSubject.send(.stop) dataStoreStateSubject.send(.start(storageEngine: storageEngine)) await fulfillment(of: [secondSnapshot], timeout: 1) } - + /// Multiple calls to start the observeQuery should not start again /// /// - Given: ObserverQuery operation is created, and then reset @@ -457,7 +476,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -476,7 +496,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 1) dataStoreStateSubject.send(.stop) dataStoreStateSubject.send(.start(storageEngine: storageEngine)) @@ -484,7 +504,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { await fulfillment(of: [secondSnapshot, thirdSnapshot], timeout: 1) XCTAssertTrue(taskRunner.observeQueryStarted) } - + /// ObserveQuery operation entry points are `resetState`, `startObserveQuery`, and `onItemChanges(mutationEvents)`. /// Ensure concurrent random sequences of these API calls do not cause issues such as data race. func testConcurrent() async { @@ -499,10 +519,13 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) - let post = Post(title: "model1", - content: "content1", - createdAt: .now()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) + let post = Post( + title: "model1", + content: "content1", + createdAt: .now() + ) storageEngine.responders[.query] = QueryResponder(callback: { _ in return .success([post, Post(title: "model1", content: "content1", createdAt: .now())]) }) @@ -517,7 +540,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { } } await withTaskGroup(of: Void.self) { group in - for _ in 0..<3000 { + for _ in 0 ..< 3_000 { group.addTask { let index = Int.random(in: 1 ... 5) if index == 1 { @@ -540,7 +563,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { } await fulfillment(of: [completeReceived], timeout: 10) } - + /// When a predicate like `title.beginsWith("title")` is given, the models that matched the predicate /// should be added to the snapshots, like `post` and `post2`. When `post2.title` is updated to no longer /// match the predicate, it should be removed from the snapshot. @@ -558,7 +581,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: true), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { @@ -604,16 +628,20 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher.send(input: updatedPost2) await fulfillment(of: [secondSnapshot, thirdSnapshot, fourthSnapshot], timeout: 10) } - - + + // MARK: - Helpers func createPost(id: String = UUID().uuidString, title: String? = nil) throws -> MutationEvent { - try MutationEvent(model: Post(id: id, - title: title ?? "model1", - content: "content1", - createdAt: .now()), - modelSchema: Post.schema, - mutationType: MutationEvent.MutationType.create) + try MutationEvent( + model: Post( + id: id, + title: title ?? "model1", + content: "content1", + createdAt: .now() + ), + modelSchema: Post.schema, + mutationType: MutationEvent.MutationType.create + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveTaskRunnerTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveTaskRunnerTests.swift index cf6a843b52..1d701ab868 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveTaskRunnerTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveTaskRunnerTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest @testable import AWSDataStorePlugin final class ObserveTaskRunnerTests: XCTestCase { @@ -15,7 +15,7 @@ final class ObserveTaskRunnerTests: XCTestCase { let dataStorePublisher = DataStorePublisher() let runner = ObserveTaskRunner(publisher: dataStorePublisher.publisher) let sequence = runner.sequence - + let started = expectation(description: "started") let mutationEventReceived = expectation(description: "mutationEvent received") mutationEventReceived.expectedFulfillmentCount = 5 @@ -37,24 +37,28 @@ final class ObserveTaskRunnerTests: XCTestCase { } } await fulfillment(of: [started], timeout: 10.0) - var mutationEvent = MutationEvent(id: "id", - modelId: "id", - modelName: "name", - json: "json", - mutationType: .create) + var mutationEvent = MutationEvent( + id: "id", + modelId: "id", + modelName: "name", + json: "json", + mutationType: .create + ) dataStorePublisher.send(input: mutationEvent) dataStorePublisher.send(input: mutationEvent) dataStorePublisher.send(input: mutationEvent) dataStorePublisher.send(input: mutationEvent) dataStorePublisher.send(input: mutationEvent) await fulfillment(of: [mutationEventReceived], timeout: 1.0) - + task.cancel() - mutationEvent = MutationEvent(id: "id2", - modelId: "id", - modelName: "name", - json: "json", - mutationType: .create) + mutationEvent = MutationEvent( + id: "id2", + modelId: "id", + modelName: "name", + json: "json", + mutationType: .create + ) dataStorePublisher.send(input: mutationEvent) await fulfillment(of: [mutationEventReceivedAfterCancel], timeout: 1.0) } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/ModelSortTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/ModelSortTests.swift index db351bf91d..33b2499beb 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/ModelSortTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/ModelSortTests.swift @@ -5,22 +5,24 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore // swiftlint:disable type_body_length class ModelSortTests: XCTestCase { func testSortModelString() throws { - var posts = [createPost(id: "1"), - createPost(id: "3"), - createPost(id: "2")] + var posts = [ + createPost(id: "1"), + createPost(id: "3"), + createPost(id: "2") + ] posts.sortModels(by: QuerySortBy.ascending(Post.keys.id).sortDescriptor, modelSchema: Post.schema) XCTAssertEqual(posts[0].id, "1") XCTAssertEqual(posts[1].id, "2") @@ -32,44 +34,61 @@ class ModelSortTests: XCTestCase { } func testSortModelOptionalString() { - var models = [QPredGen(name: "name", myString: "1"), - QPredGen(name: "name", myString: nil), - QPredGen(name: "name", myString: "2")] - models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myString).sortDescriptor, - modelSchema: QPredGen.schema) + var models = [ + QPredGen(name: "name", myString: "1"), + QPredGen(name: "name", myString: nil), + QPredGen(name: "name", myString: "2") + ] + models.sortModels( + by: QuerySortBy.ascending(QPredGen.keys.myString).sortDescriptor, + modelSchema: QPredGen.schema + ) XCTAssertEqual(models[0].myString, nil) XCTAssertEqual(models[1].myString, "1") XCTAssertEqual(models[2].myString, "2") - models.sortModels(by: QuerySortBy.descending(QPredGen.keys.myString).sortDescriptor, - modelSchema: QPredGen.schema) + models.sortModels( + by: QuerySortBy.descending(QPredGen.keys.myString).sortDescriptor, + modelSchema: QPredGen.schema + ) XCTAssertEqual(models[0].myString, "2") XCTAssertEqual(models[1].myString, "1") XCTAssertEqual(models[2].myString, nil) } func testSortModelInt() { - var models = [MutationSyncMetadata( - modelId: UUID().uuidString, modelName: "", deleted: false, lastChangedAt: 1, version: 1), - MutationSyncMetadata( - modelId: UUID().uuidString, modelName: "", deleted: false, lastChangedAt: 1, version: 2), - MutationSyncMetadata( - modelId: UUID().uuidString, modelName: "", deleted: false, lastChangedAt: 1, version: 3)] - models.sortModels(by: QuerySortBy.ascending(MutationSyncMetadata.keys.version).sortDescriptor, - modelSchema: MutationSyncMetadata.schema) + var models = [ + MutationSyncMetadata( + modelId: UUID().uuidString, modelName: "", deleted: false, lastChangedAt: 1, version: 1 + ), + MutationSyncMetadata( + modelId: UUID().uuidString, modelName: "", deleted: false, lastChangedAt: 1, version: 2 + ), + MutationSyncMetadata( + modelId: UUID().uuidString, modelName: "", deleted: false, lastChangedAt: 1, version: 3 + ) + ] + models.sortModels( + by: QuerySortBy.ascending(MutationSyncMetadata.keys.version).sortDescriptor, + modelSchema: MutationSyncMetadata.schema + ) XCTAssertEqual(models[0].version, 1) XCTAssertEqual(models[1].version, 2) XCTAssertEqual(models[2].version, 3) - models.sortModels(by: QuerySortBy.descending(MutationSyncMetadata.keys.version).sortDescriptor, - modelSchema: MutationSyncMetadata.schema) + models.sortModels( + by: QuerySortBy.descending(MutationSyncMetadata.keys.version).sortDescriptor, + modelSchema: MutationSyncMetadata.schema + ) XCTAssertEqual(models[0].version, 3) XCTAssertEqual(models[1].version, 2) XCTAssertEqual(models[2].version, 1) } func testSortModelOptionalInt() { - var models = [QPredGen(name: "name", myInt: 1), - QPredGen(name: "name", myInt: nil), - QPredGen(name: "name", myInt: 2)] + var models = [ + QPredGen(name: "name", myInt: 1), + QPredGen(name: "name", myInt: nil), + QPredGen(name: "name", myInt: 2) + ] models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myInt).sortDescriptor, modelSchema: QPredGen.schema) XCTAssertEqual(models[0].myInt, nil) XCTAssertEqual(models[1].myInt, 1) @@ -93,16 +112,22 @@ class ModelSortTests: XCTestCase { } func testSortModelOptionalDouble() { - var models = [QPredGen(name: "name", myDouble: 1.1), - QPredGen(name: "name", myDouble: nil), - QPredGen(name: "name", myDouble: 2.2)] - models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myDouble).sortDescriptor, - modelSchema: QPredGen.schema) + var models = [ + QPredGen(name: "name", myDouble: 1.1), + QPredGen(name: "name", myDouble: nil), + QPredGen(name: "name", myDouble: 2.2) + ] + models.sortModels( + by: QuerySortBy.ascending(QPredGen.keys.myDouble).sortDescriptor, + modelSchema: QPredGen.schema + ) XCTAssertEqual(models[0].myDouble, nil) XCTAssertEqual(models[1].myDouble, 1.1) XCTAssertEqual(models[2].myDouble, 2.2) - models.sortModels(by: QuerySortBy.descending(QPredGen.keys.myDouble).sortDescriptor, - modelSchema: QPredGen.schema) + models.sortModels( + by: QuerySortBy.descending(QPredGen.keys.myDouble).sortDescriptor, + modelSchema: QPredGen.schema + ) XCTAssertEqual(models[0].myDouble, 2.2) XCTAssertEqual(models[1].myDouble, 1.1) XCTAssertEqual(models[2].myDouble, nil) @@ -112,16 +137,22 @@ class ModelSortTests: XCTestCase { let date1 = Temporal.Date.now() let date2 = Temporal.Date.now().add(value: 1, to: .day) let date3 = Temporal.Date.now().add(value: 2, to: .day) - var models = [createModel(date: date1), - createModel(date: date2), - createModel(date: date3)] - models.sortModels(by: QuerySortBy.ascending(ExampleWithEveryType.keys.dateField).sortDescriptor, - modelSchema: ExampleWithEveryType.schema) + var models = [ + createModel(date: date1), + createModel(date: date2), + createModel(date: date3) + ] + models.sortModels( + by: QuerySortBy.ascending(ExampleWithEveryType.keys.dateField).sortDescriptor, + modelSchema: ExampleWithEveryType.schema + ) XCTAssertEqual(models[0].dateField, date1) XCTAssertEqual(models[1].dateField, date2) XCTAssertEqual(models[2].dateField, date3) - models.sortModels(by: QuerySortBy.descending(ExampleWithEveryType.keys.dateField).sortDescriptor, - modelSchema: ExampleWithEveryType.schema) + models.sortModels( + by: QuerySortBy.descending(ExampleWithEveryType.keys.dateField).sortDescriptor, + modelSchema: ExampleWithEveryType.schema + ) XCTAssertEqual(models[0].dateField, date3) XCTAssertEqual(models[1].dateField, date2) XCTAssertEqual(models[2].dateField, date1) @@ -130,9 +161,11 @@ class ModelSortTests: XCTestCase { func testSortModelOptionalDate() { let date1 = Temporal.Date.now().add(value: 1, to: .day) let date2 = Temporal.Date.now().add(value: 2, to: .day) - var models = [QPredGen(name: "name", myDate: date1), - QPredGen(name: "name", myDate: nil), - QPredGen(name: "name", myDate: date2)] + var models = [ + QPredGen(name: "name", myDate: date1), + QPredGen(name: "name", myDate: nil), + QPredGen(name: "name", myDate: date2) + ] models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myDate).sortDescriptor, modelSchema: QPredGen.schema) XCTAssertEqual(models[0].myDate, nil) XCTAssertEqual(models[1].myDate, date1) @@ -147,9 +180,11 @@ class ModelSortTests: XCTestCase { let dateTime1 = Temporal.DateTime.now() let dateTime2 = Temporal.DateTime.now().add(value: 1, to: .day) let dateTime3 = Temporal.DateTime.now().add(value: 2, to: .day) - var posts = [createPost(createdAt: dateTime1), - createPost(createdAt: dateTime2), - createPost(createdAt: dateTime3)] + var posts = [ + createPost(createdAt: dateTime1), + createPost(createdAt: dateTime2), + createPost(createdAt: dateTime3) + ] posts.sortModels(by: QuerySortBy.ascending(Post.keys.createdAt).sortDescriptor, modelSchema: Post.schema) XCTAssertEqual(posts[0].createdAt, dateTime1) XCTAssertEqual(posts[1].createdAt, dateTime2) @@ -163,16 +198,22 @@ class ModelSortTests: XCTestCase { func testSortModelOptionalDateTime() { let datetime1 = Temporal.DateTime.now().add(value: 1, to: .day) let datetime2 = Temporal.DateTime.now().add(value: 2, to: .day) - var models = [QPredGen(name: "name", myDateTime: datetime1), - QPredGen(name: "name", myDateTime: nil), - QPredGen(name: "name", myDateTime: datetime2)] - models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myDateTime).sortDescriptor, - modelSchema: QPredGen.schema) + var models = [ + QPredGen(name: "name", myDateTime: datetime1), + QPredGen(name: "name", myDateTime: nil), + QPredGen(name: "name", myDateTime: datetime2) + ] + models.sortModels( + by: QuerySortBy.ascending(QPredGen.keys.myDateTime).sortDescriptor, + modelSchema: QPredGen.schema + ) XCTAssertEqual(models[0].myDateTime, nil) XCTAssertEqual(models[1].myDateTime, datetime1) XCTAssertEqual(models[2].myDateTime, datetime2) - models.sortModels(by: QuerySortBy.descending(QPredGen.keys.myDateTime).sortDescriptor, - modelSchema: QPredGen.schema) + models.sortModels( + by: QuerySortBy.descending(QPredGen.keys.myDateTime).sortDescriptor, + modelSchema: QPredGen.schema + ) XCTAssertEqual(models[0].myDateTime, datetime2) XCTAssertEqual(models[1].myDateTime, datetime1) XCTAssertEqual(models[2].myDateTime, nil) @@ -182,9 +223,11 @@ class ModelSortTests: XCTestCase { let time1 = Temporal.Time.now() let time2 = Temporal.Time.now().add(value: 2, to: .day) let time3 = Temporal.Time.now().add(value: 3, to: .day) - var models = [QPredGen(name: "name", myTime: time2), - QPredGen(name: "name", myTime: time1), - QPredGen(name: "name", myTime: time3)] + var models = [ + QPredGen(name: "name", myTime: time2), + QPredGen(name: "name", myTime: time1), + QPredGen(name: "name", myTime: time3) + ] models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myTime).sortDescriptor, modelSchema: QPredGen.schema) XCTAssertEqual(models[0].myTime, time1) @@ -200,9 +243,11 @@ class ModelSortTests: XCTestCase { func testSortModelOptionalTime() { let time1 = Temporal.Time.now().add(value: 1, to: .day) let time2 = Temporal.Time.now().add(value: 2, to: .day) - var models = [QPredGen(name: "name", myTime: time1), - QPredGen(name: "name", myTime: nil), - QPredGen(name: "name", myTime: time2)] + var models = [ + QPredGen(name: "name", myTime: time1), + QPredGen(name: "name", myTime: nil), + QPredGen(name: "name", myTime: time2) + ] models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myTime).sortDescriptor, modelSchema: QPredGen.schema) XCTAssertEqual(models[0].myTime, nil) @@ -216,25 +261,33 @@ class ModelSortTests: XCTestCase { } func testSortModelBool() { - var models = [createModel(bool: false), - createModel(bool: true), - createModel(bool: false)] - models.sortModels(by: QuerySortBy.ascending(ExampleWithEveryType.keys.boolField).sortDescriptor, - modelSchema: ExampleWithEveryType.schema) + var models = [ + createModel(bool: false), + createModel(bool: true), + createModel(bool: false) + ] + models.sortModels( + by: QuerySortBy.ascending(ExampleWithEveryType.keys.boolField).sortDescriptor, + modelSchema: ExampleWithEveryType.schema + ) XCTAssertEqual(models[0].boolField, false) XCTAssertEqual(models[1].boolField, false) XCTAssertEqual(models[2].boolField, true) - models.sortModels(by: QuerySortBy.descending(ExampleWithEveryType.keys.boolField).sortDescriptor, - modelSchema: ExampleWithEveryType.schema) + models.sortModels( + by: QuerySortBy.descending(ExampleWithEveryType.keys.boolField).sortDescriptor, + modelSchema: ExampleWithEveryType.schema + ) XCTAssertEqual(models[0].boolField, true) XCTAssertEqual(models[1].boolField, false) XCTAssertEqual(models[2].boolField, false) } func testSortModelOptionalBool() { - var models = [QPredGen(name: "name", myBool: true), - QPredGen(name: "name", myBool: nil), - QPredGen(name: "name", myBool: false)] + var models = [ + QPredGen(name: "name", myBool: true), + QPredGen(name: "name", myBool: nil), + QPredGen(name: "name", myBool: false) + ] models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myBool).sortDescriptor, modelSchema: QPredGen.schema) XCTAssertEqual(models[0].myBool, nil) XCTAssertEqual(models[1].myBool, false) @@ -246,26 +299,34 @@ class ModelSortTests: XCTestCase { } func testSortModelEnum() { - var models = [createModel(enum: .bar), - createModel(enum: .foo), - createModel(enum: .bar)] - models.sortModels(by: QuerySortBy.ascending(ExampleWithEveryType.keys.enumField).sortDescriptor, - modelSchema: ExampleWithEveryType.schema) + var models = [ + createModel(enum: .bar), + createModel(enum: .foo), + createModel(enum: .bar) + ] + models.sortModels( + by: QuerySortBy.ascending(ExampleWithEveryType.keys.enumField).sortDescriptor, + modelSchema: ExampleWithEveryType.schema + ) XCTAssertEqual(models[0].enumField, .bar) XCTAssertEqual(models[1].enumField, .bar) XCTAssertEqual(models[2].enumField, .foo) - models.sortModels(by: QuerySortBy.descending(ExampleWithEveryType.keys.enumField).sortDescriptor, - modelSchema: ExampleWithEveryType.schema) + models.sortModels( + by: QuerySortBy.descending(ExampleWithEveryType.keys.enumField).sortDescriptor, + modelSchema: ExampleWithEveryType.schema + ) XCTAssertEqual(models[0].enumField, .foo) XCTAssertEqual(models[1].enumField, .bar) XCTAssertEqual(models[2].enumField, .bar) } func testSortModelOptionalEnum() { - var posts = [createPost(status: .draft), - createPost(status: .private), - createPost(status: .published), - createPost(status: nil)] + var posts = [ + createPost(status: .draft), + createPost(status: .private), + createPost(status: .published), + createPost(status: nil) + ] posts.sortModels(by: QuerySortBy.ascending(Post.keys.status).sortDescriptor, modelSchema: Post.schema) XCTAssertEqual(posts[0].status, nil) XCTAssertEqual(posts[1].status, .draft) @@ -282,9 +343,11 @@ class ModelSortTests: XCTestCase { let dateTime1 = Temporal.DateTime.now() let dateTime2 = Temporal.DateTime.now().add(value: 1, to: .day) let dateTime3 = Temporal.DateTime.now().add(value: 2, to: .day) - var posts = [createPost(rating: 1.0, createdAt: dateTime2), - createPost(rating: 1.0, createdAt: dateTime1), - createPost(rating: 2.0, createdAt: dateTime3)] + var posts = [ + createPost(rating: 1.0, createdAt: dateTime2), + createPost(rating: 1.0, createdAt: dateTime1), + createPost(rating: 2.0, createdAt: dateTime3) + ] posts.sortModels(by: QuerySortBy.ascending(Post.keys.rating).sortDescriptor, modelSchema: Post.schema) // overall order does not change since ratings are already in asecnding order @@ -306,34 +369,44 @@ class ModelSortTests: XCTestCase { // MARK: - Helpers - func createPost(id: String = UUID().uuidString, - draft: Bool = false, - rating: Double = 1.0, - createdAt: Temporal.DateTime = .now(), - status: PostStatus? = .draft) -> Post { - Post(id: id, - title: "A", - content: "content", - createdAt: createdAt, - updatedAt: .now(), - draft: draft, - rating: rating, - status: status, - comments: nil) + func createPost( + id: String = UUID().uuidString, + draft: Bool = false, + rating: Double = 1.0, + createdAt: Temporal.DateTime = .now(), + status: PostStatus? = .draft + ) -> Post { + Post( + id: id, + title: "A", + content: "content", + createdAt: createdAt, + updatedAt: .now(), + draft: draft, + rating: rating, + status: status, + comments: nil + ) } - func createModel(date: Temporal.Date = .now(), - bool: Bool = false, - enum: ExampleEnum = .bar) -> ExampleWithEveryType { - ExampleWithEveryType(id: UUID().uuidString, - stringField: "string", - intField: 1, - doubleField: 1.0, - boolField: bool, - dateField: date, - enumField: `enum`, - nonModelField: .init(someString: "some string", - someEnum: .bar), - arrayOfStringsField: []) + func createModel( + date: Temporal.Date = .now(), + bool: Bool = false, + enum: ExampleEnum = .bar + ) -> ExampleWithEveryType { + ExampleWithEveryType( + id: UUID().uuidString, + stringField: "string", + intField: 1, + doubleField: 1.0, + boolField: bool, + dateField: date, + enumField: `enum`, + nonModelField: .init( + someString: "some string", + someEnum: .bar + ), + arrayOfStringsField: [] + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/SortedListTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/SortedListTests.swift index 48dd62f55e..511b9229e9 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/SortedListTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/SortedListTests.swift @@ -5,25 +5,29 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class SortedListTests: XCTestCase { func testSortedListSetAndReset() { - let posts = [createPost(id: "1", rating: 5.0), - createPost(id: "2", rating: 5.0), - createPost(id: "3", rating: 5.0), - createPost(id: "4", rating: 5.0)] - - let list = SortedList(sortInput: [QuerySortBy.ascending(Post.keys.rating).sortDescriptor], - modelSchema: Post.schema) + let posts = [ + createPost(id: "1", rating: 5.0), + createPost(id: "2", rating: 5.0), + createPost(id: "3", rating: 5.0), + createPost(id: "4", rating: 5.0) + ] + + let list = SortedList( + sortInput: [QuerySortBy.ascending(Post.keys.rating).sortDescriptor], + modelSchema: Post.schema + ) list.set(sortedModels: posts) assertPosts(list.sortedModels, expectedIds: ["1", "2", "3", "4"]) @@ -35,13 +39,17 @@ class SortedListTests: XCTestCase { } func testSortedListSingleSort() { - let posts = [createPost(id: "1"), - createPost(id: "2"), - createPost(id: "5"), - createPost(id: "6")] + let posts = [ + createPost(id: "1"), + createPost(id: "2"), + createPost(id: "5"), + createPost(id: "6") + ] let sortInput = [QuerySortBy.ascending(Post.keys.id).sortDescriptor] - let list = SortedList(sortInput: sortInput, - modelSchema: Post.schema) + let list = SortedList( + sortInput: sortInput, + modelSchema: Post.schema + ) list.set(sortedModels: posts) @@ -81,14 +89,20 @@ class SortedListTests: XCTestCase { } func testSortedListMultipleSort() { - let posts = [createPost(id: "1", rating: 5.0), - createPost(id: "2", rating: 10.0), - createPost(id: "6", rating: 10.0), - createPost(id: "5", rating: 20.0)] - let sortInput = [QuerySortBy.ascending(Post.keys.rating).sortDescriptor, - QuerySortBy.ascending(Post.keys.id).sortDescriptor] - let list = SortedList(sortInput: sortInput, - modelSchema: Post.schema) + let posts = [ + createPost(id: "1", rating: 5.0), + createPost(id: "2", rating: 10.0), + createPost(id: "6", rating: 10.0), + createPost(id: "5", rating: 20.0) + ] + let sortInput = [ + QuerySortBy.ascending(Post.keys.rating).sortDescriptor, + QuerySortBy.ascending(Post.keys.id).sortDescriptor + ] + let list = SortedList( + sortInput: sortInput, + modelSchema: Post.schema + ) list.set(sortedModels: posts) // After id: "1", rating: 5.0 @@ -120,14 +134,18 @@ class SortedListTests: XCTestCase { } func testSortedListAllEqual() { - let posts = [createPost(id: "1", rating: 5.0), - createPost(id: "2", rating: 5.0), - createPost(id: "3", rating: 5.0), - createPost(id: "4", rating: 5.0)] + let posts = [ + createPost(id: "1", rating: 5.0), + createPost(id: "2", rating: 5.0), + createPost(id: "3", rating: 5.0), + createPost(id: "4", rating: 5.0) + ] let sortInput = [QuerySortBy.ascending(Post.keys.rating).sortDescriptor] - let list = SortedList(sortInput: [QuerySortBy.ascending(Post.keys.rating).sortDescriptor], - modelSchema: Post.schema) + let list = SortedList( + sortInput: [QuerySortBy.ascending(Post.keys.rating).sortDescriptor], + modelSchema: Post.schema + ) list.set(sortedModels: posts) // Since this is a binary search, the first index where the predicate returns `nil` is the middle index @@ -149,19 +167,23 @@ class SortedListTests: XCTestCase { XCTAssertEqual(post.rating, rating) } - func createPost(id: String = UUID().uuidString, - draft: Bool = false, - rating: Double = 1.0, - createdAt: Temporal.DateTime = .now(), - status: PostStatus? = .draft) -> Post { - Post(id: id, - title: "A", - content: "content", - createdAt: createdAt, - updatedAt: .now(), - draft: draft, - rating: rating, - status: status, - comments: nil) + func createPost( + id: String = UUID().uuidString, + draft: Bool = false, + rating: Double = 1.0, + createdAt: Temporal.DateTime = .now(), + status: PostStatus? = .draft + ) -> Post { + Post( + id: id, + title: "A", + content: "content", + createdAt: createdAt, + updatedAt: .now(), + draft: draft, + rating: rating, + status: status, + comments: nil + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/APICategoryDependencyTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/APICategoryDependencyTests.swift index c578764c7c..f68ca5b877 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/APICategoryDependencyTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/APICategoryDependencyTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -62,25 +62,31 @@ extension APICategoryDependencyTests { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) - let syncEngine = try RemoteSyncEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault()) + let syncEngine = try RemoteSyncEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault() + ) let validAPIPluginKey = "MockAPICategoryPlugin" let validAuthPluginKey = "MockAuthCategoryPlugin" - let storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let storageEngineBehaviorFactory: StorageEngineBehaviorFactory = {_, _, _, _, _, _ throws in return storageEngine } let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) try Amplify.add(plugin: dataStorePlugin) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationSyncExpressionTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationSyncExpressionTests.swift index e118693987..da1713986a 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationSyncExpressionTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationSyncExpressionTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import SQLite import Combine +import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -34,16 +34,22 @@ class InitialSyncOperationSyncExpressionTests: XCTestCase { apiWasQueried = expectation(description: "API was queried with sync expression") } - func initialSyncOperation(withSyncExpression syncExpression: DataStoreSyncExpression, - responder: APIPluginQueryResponder) -> InitialSyncOperation { + func initialSyncOperation( + withSyncExpression syncExpression: DataStoreSyncExpression, + responder: APIPluginQueryResponder + ) -> InitialSyncOperation { apiPlugin.responders[.queryRequestResponse] = responder #if os(watchOS) - let configuration = DataStoreConfiguration.custom(syncPageSize: 10, - syncExpressions: [syncExpression], - disableSubscriptions: { false }) + let configuration = DataStoreConfiguration.custom( + syncPageSize: 10, + syncExpressions: [syncExpression], + disableSubscriptions: { false } + ) #else - let configuration = DataStoreConfiguration.custom(syncPageSize: 10, - syncExpressions: [syncExpression]) + let configuration = DataStoreConfiguration.custom( + syncPageSize: 10, + syncExpressions: [syncExpression] + ) #endif return InitialSyncOperation( modelSchema: MockSynced.schema, @@ -51,7 +57,8 @@ class InitialSyncOperationSyncExpressionTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: configuration, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) } func testBaseQueryWithBasicSyncExpression() async throws { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationTests.swift index 07cdd95ecb..de12a9357d 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import SQLite import Combine +import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -25,7 +25,7 @@ class InitialSyncOperationTests: XCTestCase { // MARK: - GetLastSyncTime func testFullSyncWhenLastSyncPredicateNilAndCurrentSyncPredicateNonNil() async { - let lastSyncTime: Int64 = 123456 + let lastSyncTime: Int64 = 123_456 let lastSyncPredicate: String? = nil let currentSyncPredicate: DataStoreConfiguration #if os(watchOS) @@ -59,7 +59,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: nil, storageAdapter: nil, dataStoreConfiguration: currentSyncPredicate, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let sink = operation .publisher .sink(receiveCompletion: { _ in @@ -74,9 +75,11 @@ class InitialSyncOperationTests: XCTestCase { } }) - let lastSyncMetadataLastSyncNil = ModelSyncMetadata(id: MockSynced.schema.name, - lastSync: lastSyncTime, - syncPredicate: lastSyncPredicate) + let lastSyncMetadataLastSyncNil = ModelSyncMetadata( + id: MockSynced.schema.name, + lastSync: lastSyncTime, + syncPredicate: lastSyncPredicate + ) XCTAssertEqual(operation.getLastSyncTime(lastSyncMetadataLastSyncNil), expectedLastSync) await fulfillment(of: [syncStartedReceived], timeout: 1) @@ -84,7 +87,7 @@ class InitialSyncOperationTests: XCTestCase { } func testFullSyncWhenLastSyncPredicateNonNilAndCurrentSyncPredicateNil() async { - let lastSyncTime: Int64 = 123456 + let lastSyncTime: Int64 = 123_456 let lastSyncPredicate: String? = "non nil" let expectedSyncType = SyncType.fullSync let expectedLastSync: Int64? = nil @@ -96,7 +99,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: nil, storageAdapter: nil, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let sink = operation .publisher .sink(receiveCompletion: { _ in @@ -111,9 +115,11 @@ class InitialSyncOperationTests: XCTestCase { } }) - let lastSyncMetadataLastSyncNil = ModelSyncMetadata(id: MockSynced.schema.name, - lastSync: lastSyncTime, - syncPredicate: lastSyncPredicate) + let lastSyncMetadataLastSyncNil = ModelSyncMetadata( + id: MockSynced.schema.name, + lastSync: lastSyncTime, + syncPredicate: lastSyncPredicate + ) XCTAssertEqual(operation.getLastSyncTime(lastSyncMetadataLastSyncNil), expectedLastSync) await fulfillment(of: [syncStartedReceived], timeout: 1) @@ -121,7 +127,7 @@ class InitialSyncOperationTests: XCTestCase { } func testFullSyncWhenLastSyncPredicateDifferentFromCurrentSyncPredicate() async { - let lastSyncTime: Int64 = 123456 + let lastSyncTime: Int64 = 123_456 let lastSyncPredicate: String? = "non nil different from current predicate" let currentSyncPredicate: DataStoreConfiguration #if os(watchOS) @@ -155,7 +161,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: nil, storageAdapter: nil, dataStoreConfiguration: currentSyncPredicate, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let sink = operation .publisher .sink(receiveCompletion: { _ in @@ -170,9 +177,11 @@ class InitialSyncOperationTests: XCTestCase { } }) - let lastSyncMetadataLastSyncNil = ModelSyncMetadata(id: MockSynced.schema.name, - lastSync: lastSyncTime, - syncPredicate: lastSyncPredicate) + let lastSyncMetadataLastSyncNil = ModelSyncMetadata( + id: MockSynced.schema.name, + lastSync: lastSyncTime, + syncPredicate: lastSyncPredicate + ) XCTAssertEqual(operation.getLastSyncTime(lastSyncMetadataLastSyncNil), expectedLastSync) await fulfillment(of: [syncStartedReceived], timeout: 1) @@ -215,7 +224,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: nil, storageAdapter: nil, dataStoreConfiguration: currentSyncPredicate, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let sink = operation .publisher .sink(receiveCompletion: { _ in @@ -230,9 +240,11 @@ class InitialSyncOperationTests: XCTestCase { } }) - let lastSyncMetadataLastSyncNil = ModelSyncMetadata(id: MockSynced.schema.name, - lastSync: lastSyncTime, - syncPredicate: lastSyncPredicate) + let lastSyncMetadataLastSyncNil = ModelSyncMetadata( + id: MockSynced.schema.name, + lastSync: lastSyncTime, + syncPredicate: lastSyncPredicate + ) XCTAssertEqual(operation.getLastSyncTime(lastSyncMetadataLastSyncNil), expectedLastSync) await fulfillment(of: [syncStartedReceived], timeout: 1) @@ -269,7 +281,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -326,7 +339,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -381,7 +395,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") let finishedReceived = expectation(description: "InitialSyncOperation finished paginating and offering") @@ -436,7 +451,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") let finishedReceived = expectation(description: "InitialSyncOperation finished paginating and offering") @@ -468,11 +484,13 @@ class InitialSyncOperationTests: XCTestCase { let startedAtMilliseconds = Int64(Date().timeIntervalSince1970) * 1_000 let model = MockSynced(id: "1") let anyModel = AnyModel(model) - let metadata = MutationSyncMetadata(modelId: "1", - modelName: MockSynced.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let metadata = MutationSyncMetadata( + modelId: "1", + modelName: MockSynced.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let mutationSync = MutationSync(model: anyModel, syncMetadata: metadata) let responder = QueryRequestResponder> { _ in let list = PaginatedList(items: [mutationSync], nextToken: nil, startedAt: startedAtMilliseconds) @@ -501,7 +519,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -560,7 +579,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -620,14 +640,16 @@ class InitialSyncOperationTests: XCTestCase { #if os(watchOS) let configuration = DataStoreConfiguration.custom(errorHandler: { error in guard let dataStoreError = error as? DataStoreError, - case let .api(amplifyError, mutationEventOptional) = dataStoreError else { + case let .api(amplifyError, mutationEventOptional) = dataStoreError + else { XCTFail("Expected API error with mutationEvent") return } guard let actualAPIError = amplifyError as? APIError, case let .operationError(_, _, underlyingError) = actualAPIError, let authError = underlyingError as? AuthError, - case .signedOut = authError else { + case .signedOut = authError + else { XCTFail("Should be `signedOut` error but got \(amplifyError)") return } @@ -637,14 +659,16 @@ class InitialSyncOperationTests: XCTestCase { #else let configuration = DataStoreConfiguration.custom(errorHandler: { error in guard let dataStoreError = error as? DataStoreError, - case let .api(amplifyError, mutationEventOptional) = dataStoreError else { + case let .api(amplifyError, mutationEventOptional) = dataStoreError + else { XCTFail("Expected API error with mutationEvent") return } guard let actualAPIError = amplifyError as? APIError, case let .operationError(_, _, underlyingError) = actualAPIError, let authError = underlyingError as? AuthError, - case .signedOut = authError else { + case .signedOut = authError + else { XCTFail("Should be `signedOut` error but got \(amplifyError)") return } @@ -658,7 +682,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: configuration, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -744,7 +769,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -818,7 +844,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: configuration, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -880,7 +907,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: configuration, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -906,12 +934,15 @@ class InitialSyncOperationTests: XCTestCase { operation.main() - await fulfillment(of: [ - syncStartedReceived, - syncCompletionReceived, - finishedReceived, - apiWasQueried], - timeout: 1) + await fulfillment( + of: [ + syncStartedReceived, + syncCompletionReceived, + finishedReceived, + apiWasQueried + ], + timeout: 1 + ) sink.cancel() } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOrchestratorTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOrchestratorTests.swift index 1e4a7ca208..a177f57beb 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOrchestratorTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOrchestratorTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Foundation +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -41,12 +41,14 @@ class InitialSyncOrchestratorTests: XCTestCase { let reconciliationQueue = MockReconciliationQueue() - let orchestrator: AWSInitialSyncOrchestrator = - AWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - api: apiPlugin, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) + let orchestrator = + AWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + api: apiPlugin, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) let syncCallbackReceived = expectation(description: "Sync callback received, sync operation is complete") let syncQueriesStartedReceived = expectation(description: "syncQueriesStarted received") @@ -109,7 +111,7 @@ class InitialSyncOrchestratorTests: XCTestCase { Amplify.Hub.removeListener(hubListener) sink.cancel() } - + /// - Given: An InitialSyncOrchestrator with a model dependency graph, API is expected to return an error for certain models /// - When: /// - The orchestrator starts up @@ -137,12 +139,14 @@ class InitialSyncOrchestratorTests: XCTestCase { let reconciliationQueue = MockReconciliationQueue() - let orchestrator: AWSInitialSyncOrchestrator = - AWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - api: apiPlugin, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) + let orchestrator = + AWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + api: apiPlugin, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) let syncCallbackReceived = expectation(description: "Sync callback received, sync operation is complete") let syncQueriesStartedReceived = expectation(description: "syncQueriesStarted received") @@ -213,7 +217,7 @@ class InitialSyncOrchestratorTests: XCTestCase { Amplify.Hub.removeListener(hubListener) sink.cancel() } - + /// - Given: An InitialSyncOrchestrator with a model dependency graph containing no associations /// - When: /// - The orchestrator starts up @@ -246,11 +250,13 @@ class InitialSyncOrchestratorTests: XCTestCase { let reconciliationQueue = MockReconciliationQueue() - let orchestrator = AWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - api: apiPlugin, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) + let orchestrator = AWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + api: apiPlugin, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) let syncCallbackReceived = expectation(description: "Sync callback received, sync operation is complete") let syncStartedReceived = expectation(description: "Sync started received, sync operation started") syncStartedReceived.expectedFulfillmentCount = 2 @@ -258,8 +264,9 @@ class InitialSyncOrchestratorTests: XCTestCase { finishedReceived.expectedFulfillmentCount = 2 let sink = orchestrator .publisher - .sink(receiveCompletion: { _ in }, - receiveValue: { value in + .sink( + receiveCompletion: { _ in }, + receiveValue: { value in switch value { case .started: syncStartedReceived.fulfill() @@ -268,7 +275,8 @@ class InitialSyncOrchestratorTests: XCTestCase { default: break } - }) + } + ) orchestrator.sync { _ in syncCallbackReceived.fulfill() @@ -311,12 +319,14 @@ class InitialSyncOrchestratorTests: XCTestCase { let reconciliationQueue = MockReconciliationQueue() - let orchestrator: AWSInitialSyncOrchestrator = - AWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - api: apiPlugin, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) + let orchestrator = + AWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + api: apiPlugin, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") syncStartedReceived.expectedFulfillmentCount = 2 @@ -324,8 +334,9 @@ class InitialSyncOrchestratorTests: XCTestCase { finishedReceived.expectedFulfillmentCount = 2 let sink = orchestrator .publisher - .sink(receiveCompletion: { _ in }, - receiveValue: { value in + .sink( + receiveCompletion: { _ in }, + receiveValue: { value in switch value { case .started: syncStartedReceived.fulfill() @@ -334,7 +345,8 @@ class InitialSyncOrchestratorTests: XCTestCase { default: break } - }) + } + ) orchestrator.sync { _ in } @@ -384,12 +396,14 @@ class InitialSyncOrchestratorTests: XCTestCase { let reconciliationQueue = MockReconciliationQueue() - let orchestrator: AWSInitialSyncOrchestrator = - AWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - api: apiPlugin, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) + let orchestrator = + AWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + api: apiPlugin, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") syncStartedReceived.expectedFulfillmentCount = 2 @@ -397,8 +411,9 @@ class InitialSyncOrchestratorTests: XCTestCase { finishedReceived.expectedFulfillmentCount = 2 let sink = orchestrator .publisher - .sink(receiveCompletion: { _ in }, - receiveValue: { value in + .sink( + receiveCompletion: { _ in }, + receiveValue: { value in switch value { case .started: syncStartedReceived.fulfill() @@ -407,7 +422,8 @@ class InitialSyncOrchestratorTests: XCTestCase { default: break } - }) + } + ) orchestrator.sync { _ in } @@ -427,35 +443,43 @@ class InitialSyncOrchestratorTests: XCTestCase { let apiPlugin = MockAPICategoryPlugin() let storageAdapter = MockSQLiteStorageEngineAdapter() let reconciliationQueue = MockReconciliationQueue() - + let orchestrator = - AWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - api: apiPlugin, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) - - let error1 = DataStoreError.api(APIError.httpStatusError(401, HTTPURLResponse(url: URL(string: "https://aws.amazon.com")!, - statusCode: 401, - httpVersion: nil, - headerFields: nil)!)) + AWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + api: apiPlugin, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) + + let error1 = DataStoreError.api(APIError.httpStatusError(401, HTTPURLResponse( + url: URL(string: "https://aws.amazon.com")!, + statusCode: 401, + httpVersion: nil, + headerFields: nil + )!)) XCTAssertTrue(orchestrator.isUnauthorizedError(DataStoreError.sync("", "", error1))) - - let error2 = DataStoreError.api(APIError.httpStatusError(403, HTTPURLResponse(url: URL(string: "https://aws.amazon.com")!, - statusCode: 403, - httpVersion: nil, - headerFields: nil)!)) + + let error2 = DataStoreError.api(APIError.httpStatusError(403, HTTPURLResponse( + url: URL(string: "https://aws.amazon.com")!, + statusCode: 403, + httpVersion: nil, + headerFields: nil + )!)) XCTAssertTrue(orchestrator.isUnauthorizedError(DataStoreError.sync("", "", error2))) - - let error3 = DataStoreError.api(APIError.httpStatusError(404, HTTPURLResponse(url: URL(string: "https://aws.amazon.com")!, - statusCode: 404, - httpVersion: nil, - headerFields: nil)!)) + + let error3 = DataStoreError.api(APIError.httpStatusError(404, HTTPURLResponse( + url: URL(string: "https://aws.amazon.com")!, + statusCode: 404, + httpVersion: nil, + headerFields: nil + )!)) XCTAssertFalse(orchestrator.isUnauthorizedError(DataStoreError.sync("", "", error3))) - + let error4 = DataStoreError.api(APIError.operationError("Unauthorized error", "", nil)) XCTAssertTrue(orchestrator.isUnauthorizedError(DataStoreError.sync("", "", error4))) - + let error5 = DataStoreError.api(APIError.operationError("An error occurred", "", nil)) XCTAssertFalse(orchestrator.isUnauthorizedError(DataStoreError.sync("", "", error5))) } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ModelSyncedEventEmitterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ModelSyncedEventEmitterTests.swift index d3ee5e1a1b..7ce773e356 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ModelSyncedEventEmitterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ModelSyncedEventEmitterTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class ModelSyncedEventEmitterTests: XCTestCase { @@ -20,15 +20,19 @@ class ModelSyncedEventEmitterTests: XCTestCase { var reconciliationQueue: MockAWSIncomingEventReconciliationQueue? override func setUp() { - initialSyncOrchestrator = MockAWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - api: nil, - reconciliationQueue: nil, - storageAdapter: nil) - reconciliationQueue = MockAWSIncomingEventReconciliationQueue(modelSchemas: [Post.schema], - api: nil, - storageAdapter: nil, - syncExpressions: [], - auth: nil) + initialSyncOrchestrator = MockAWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + api: nil, + reconciliationQueue: nil, + storageAdapter: nil + ) + reconciliationQueue = MockAWSIncomingEventReconciliationQueue( + modelSchemas: [Post.schema], + api: nil, + storageAdapter: nil, + syncExpressions: [], + auth: nil + ) ModelRegistry.register(modelType: Post.self) } @@ -46,11 +50,13 @@ class ModelSyncedEventEmitterTests: XCTestCase { mutationEventAppliedReceived.expectedFulfillmentCount = 3 let mutationEventDroppedReceived = expectation(description: "mutationEventDropped received") mutationEventDroppedReceived.expectedFulfillmentCount = 2 - let anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: Post.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: Post.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) let anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) @@ -58,9 +64,11 @@ class ModelSyncedEventEmitterTests: XCTestCase { var receivedMutationEventsCount = 0 var modelSyncedEventReceivedLast = false - let emitter = ModelSyncedEventEmitter(modelSchema: Post.schema, - initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + let emitter = ModelSyncedEventEmitter( + modelSchema: Post.schema, + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) var emitterSink: AnyCancellable? emitterSink = emitter.publisher.sink { _ in @@ -68,12 +76,14 @@ class ModelSyncedEventEmitterTests: XCTestCase { } receiveValue: { value in switch value { case .modelSyncedEvent(let modelSyncedEvent): - let expectedModelSyncedEventPayload = ModelSyncedEvent(modelName: "Post", - isFullSync: true, - isDeltaSync: false, - added: 3, - updated: 0, - deleted: 0) + let expectedModelSyncedEventPayload = ModelSyncedEvent( + modelName: "Post", + isFullSync: true, + isDeltaSync: false, + added: 3, + updated: 0, + deleted: 0 + ) XCTAssertEqual(modelSyncedEvent, expectedModelSyncedEventPayload) if receivedMutationEventsCount == 5 { modelSyncedEventReceivedLast = true @@ -88,18 +98,30 @@ class ModelSyncedEventEmitterTests: XCTestCase { } } - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started(modelName: Post.modelName, - syncType: .fullSync)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started( + modelName: Post.modelName, + syncType: .fullSync + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.finished(modelName: Post.modelName)) reconciliationQueue?.incomingEventSubject.send(.mutationEventApplied(postMutationEvent)) reconciliationQueue?.incomingEventSubject.send(.mutationEventDropped(modelName: Post.modelName)) @@ -126,18 +148,22 @@ class ModelSyncedEventEmitterTests: XCTestCase { mutationEventAppliedReceived.expectedFulfillmentCount = 5 let mutationEventDroppedReceived = expectation(description: "mutationEventDropped received") mutationEventDroppedReceived.expectedFulfillmentCount = 3 - let anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: "", - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: "", + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) let anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) let postMutationEvent = try MutationEvent(untypedModel: testPost, mutationType: .create) - let emitter = ModelSyncedEventEmitter(modelSchema: Post.schema, - initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + let emitter = ModelSyncedEventEmitter( + modelSchema: Post.schema, + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) var emitterSink: AnyCancellable? emitterSink = emitter.publisher.sink { _ in @@ -145,12 +171,14 @@ class ModelSyncedEventEmitterTests: XCTestCase { } receiveValue: { value in switch value { case .modelSyncedEvent(let modelSyncedEvent): - let expectedModelSyncedEventPayload = ModelSyncedEvent(modelName: "Post", - isFullSync: true, - isDeltaSync: false, - added: 2, - updated: 0, - deleted: 0) + let expectedModelSyncedEventPayload = ModelSyncedEvent( + modelName: "Post", + isFullSync: true, + isDeltaSync: false, + added: 2, + updated: 0, + deleted: 0 + ) XCTAssertEqual(modelSyncedEvent, expectedModelSyncedEventPayload) modelSyncedReceived.fulfill() case .mutationEventApplied: @@ -160,12 +188,18 @@ class ModelSyncedEventEmitterTests: XCTestCase { } } - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started(modelName: Post.modelName, - syncType: .fullSync)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started( + modelName: Post.modelName, + syncType: .fullSync + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.finished(modelName: Post.modelName)) reconciliationQueue?.incomingEventSubject.send(.mutationEventApplied(postMutationEvent)) reconciliationQueue?.incomingEventSubject.send(.mutationEventApplied(postMutationEvent)) @@ -199,22 +233,28 @@ class ModelSyncedEventEmitterTests: XCTestCase { mutationEventAppliedReceived.assertForOverFulfill = false let mutationEventDroppedReceived = expectation(description: "mutationEventDropped received") mutationEventDroppedReceived.assertForOverFulfill = false - let anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: Post.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: Post.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) let anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) let postMutationEvent = try MutationEvent(untypedModel: testPost, mutationType: .create) - let emitter = ModelSyncedEventEmitter(modelSchema: Post.schema, - initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + let emitter = ModelSyncedEventEmitter( + modelSchema: Post.schema, + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started(modelName: Post.modelName, - syncType: .fullSync)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started( + modelName: Post.modelName, + syncType: .fullSync + )) DispatchQueue.concurrentPerform(iterations: 1_000) { _ in let index = Int.random(in: 1 ... 10) if index == 1 { @@ -222,8 +262,10 @@ class ModelSyncedEventEmitterTests: XCTestCase { } else if index == 2 { reconciliationQueue?.incomingEventSubject.send(.mutationEventDropped(modelName: Post.modelName)) } else { - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ReadyEventEmitterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ReadyEventEmitterTests.swift index 9d105456e1..c19590406c 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ReadyEventEmitterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ReadyEventEmitterTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation -import XCTest import SQLite -import Combine +import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class ReadyEventEmitterTests: XCTestCase { var stateMachine: MockStateMachine! diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/SyncEventEmitterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/SyncEventEmitterTests.swift index 09b3177891..5ed6e24569 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/SyncEventEmitterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/SyncEventEmitterTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class SyncEventEmitterTests: XCTestCase { var initialSyncOrchestrator: MockAWSInitialSyncOrchestrator? @@ -42,27 +42,35 @@ class SyncEventEmitterTests: XCTestCase { ModelRegistry.register(modelType: Post.self) let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) - let anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: Post.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: Post.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) let postMutationEvent = try MutationEvent(untypedModel: testPost, mutationType: .create) - reconciliationQueue = MockAWSIncomingEventReconciliationQueue(modelSchemas: [Post.schema], - api: nil, - storageAdapter: nil, - syncExpressions: [], - auth: nil) - - initialSyncOrchestrator = MockAWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - api: nil, - reconciliationQueue: nil, - storageAdapter: nil) - - syncEventEmitter = SyncEventEmitter(initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + reconciliationQueue = MockAWSIncomingEventReconciliationQueue( + modelSchemas: [Post.schema], + api: nil, + storageAdapter: nil, + syncExpressions: [], + auth: nil + ) + + initialSyncOrchestrator = MockAWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + api: nil, + reconciliationQueue: nil, + storageAdapter: nil + ) + + syncEventEmitter = SyncEventEmitter( + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) var syncEventEmitterSink: AnyCancellable? syncEventEmitterSink = syncEventEmitter?.publisher.sink(receiveCompletion: { completion in XCTFail("Should not have completed: \(completion)") @@ -73,9 +81,14 @@ class SyncEventEmitterTests: XCTestCase { case .mutationEventDropped: break case .modelSyncedEvent(let modelSyncedEvent): - let expectedModelSyncedEventPayload = ModelSyncedEvent(modelName: "Post", - isFullSync: true, isDeltaSync: false, - added: 1, updated: 0, deleted: 0) + let expectedModelSyncedEventPayload = ModelSyncedEvent( + modelName: "Post", + isFullSync: true, + isDeltaSync: false, + added: 1, + updated: 0, + deleted: 0 + ) XCTAssertTrue(modelSyncedEvent == expectedModelSyncedEventPayload) modelSyncedReceived.fulfill() case .syncQueriesReadyEvent: @@ -83,10 +96,14 @@ class SyncEventEmitterTests: XCTestCase { } }) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started(modelName: Post.modelName, - syncType: .fullSync)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started( + modelName: Post.modelName, + syncType: .fullSync + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.finished(modelName: Post.modelName)) reconciliationQueue?.incomingEventSubject.send(.mutationEventApplied(postMutationEvent)) @@ -116,28 +133,46 @@ class SyncEventEmitterTests: XCTestCase { var modelSyncedEventPayloads = [ModelSyncedEvent]() let expectedModelSyncedEventPayloads: [ModelSyncedEvent] - = [ModelSyncedEvent(modelName: "Comment", - isFullSync: true, isDeltaSync: false, - added: 0, updated: 0, deleted: 0), - ModelSyncedEvent(modelName: "Post", - isFullSync: true, isDeltaSync: false, - added: 0, updated: 0, deleted: 0)] - - let syncableModelSchemas = ModelRegistry.modelSchemas.filter { $0.isSyncable } - - reconciliationQueue = MockAWSIncomingEventReconciliationQueue(modelSchemas: syncableModelSchemas, - api: nil, - storageAdapter: nil, - syncExpressions: [], - auth: nil) - - initialSyncOrchestrator = MockAWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - api: nil, - reconciliationQueue: nil, - storageAdapter: nil) - - syncEventEmitter = SyncEventEmitter(initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + = [ + ModelSyncedEvent( + modelName: "Comment", + isFullSync: true, + isDeltaSync: false, + added: 0, + updated: 0, + deleted: 0 + ), + ModelSyncedEvent( + modelName: "Post", + isFullSync: true, + isDeltaSync: false, + added: 0, + updated: 0, + deleted: 0 + ) + ] + + let syncableModelSchemas = ModelRegistry.modelSchemas.filter(\.isSyncable) + + reconciliationQueue = MockAWSIncomingEventReconciliationQueue( + modelSchemas: syncableModelSchemas, + api: nil, + storageAdapter: nil, + syncExpressions: [], + auth: nil + ) + + initialSyncOrchestrator = MockAWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + api: nil, + reconciliationQueue: nil, + storageAdapter: nil + ) + + syncEventEmitter = SyncEventEmitter( + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) var syncEventEmitterSink: AnyCancellable? syncEventEmitterSink = syncEventEmitter?.publisher.sink(receiveCompletion: { completion in @@ -193,49 +228,71 @@ class SyncEventEmitterTests: XCTestCase { ModelRegistry.register(modelType: Comment.self) let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) - let anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: Post.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: Post.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) let postMutationEvent = try MutationEvent(untypedModel: testPost, mutationType: .create) let testComment = Comment(id: "1", content: "content", createdAt: .now(), post: testPost) let anyComment = AnyModel(testComment) - let anyCommentMetadata = MutationSyncMetadata(modelId: "1", - modelName: Comment.modelName, - deleted: true, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 2) + let anyCommentMetadata = MutationSyncMetadata( + modelId: "1", + modelName: Comment.modelName, + deleted: true, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 2 + ) let anyCommentMutationSync = MutationSync(model: anyComment, syncMetadata: anyCommentMetadata) let commentMutationEvent = try MutationEvent(untypedModel: testComment, mutationType: .delete) let expectedModelSyncedEventPayloads: [ModelSyncedEvent] - = [ModelSyncedEvent(modelName: "Comment", - isFullSync: true, isDeltaSync: false, - added: 0, updated: 0, deleted: 1), - ModelSyncedEvent(modelName: "Post", - isFullSync: true, isDeltaSync: false, - added: 1, updated: 0, deleted: 0)] + = [ + ModelSyncedEvent( + modelName: "Comment", + isFullSync: true, + isDeltaSync: false, + added: 0, + updated: 0, + deleted: 1 + ), + ModelSyncedEvent( + modelName: "Post", + isFullSync: true, + isDeltaSync: false, + added: 1, + updated: 0, + deleted: 0 + ) + ] var modelSyncedEventPayloads = [ModelSyncedEvent]() - let syncableModelSchemas = ModelRegistry.modelSchemas.filter { $0.isSyncable } + let syncableModelSchemas = ModelRegistry.modelSchemas.filter(\.isSyncable) - reconciliationQueue = MockAWSIncomingEventReconciliationQueue(modelSchemas: syncableModelSchemas, - api: nil, - storageAdapter: nil, - syncExpressions: [], - auth: nil) + reconciliationQueue = MockAWSIncomingEventReconciliationQueue( + modelSchemas: syncableModelSchemas, + api: nil, + storageAdapter: nil, + syncExpressions: [], + auth: nil + ) - initialSyncOrchestrator = MockAWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - api: nil, - reconciliationQueue: nil, - storageAdapter: nil) + initialSyncOrchestrator = MockAWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + api: nil, + reconciliationQueue: nil, + storageAdapter: nil + ) - syncEventEmitter = SyncEventEmitter(initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + syncEventEmitter = SyncEventEmitter( + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) var syncEventEmitterSink: AnyCancellable? syncEventEmitterSink = syncEventEmitter?.publisher.sink(receiveCompletion: { completion in @@ -262,16 +319,24 @@ class SyncEventEmitterTests: XCTestCase { } }) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started(modelName: Post.modelName, - syncType: .fullSync)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started( + modelName: Post.modelName, + syncType: .fullSync + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.finished(modelName: Post.modelName)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started(modelName: Comment.modelName, - syncType: .fullSync)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyCommentMutationSync, - modelName: Comment.modelName)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started( + modelName: Comment.modelName, + syncType: .fullSync + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyCommentMutationSync, + modelName: Comment.modelName + )) initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.finished(modelName: Comment.modelName)) reconciliationQueue?.incomingEventSubject.send(.mutationEventApplied(postMutationEvent)) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionTests.swift index 13d8333dc5..1f0212559e 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest import Combine @testable import Amplify -@testable import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSDataStorePlugin +@testable import AWSPluginsCore /// Tests behavior of local DataStore subscriptions (as opposed to remote API subscription behaviors) class LocalSubscriptionTests: XCTestCase { @@ -36,8 +36,10 @@ class LocalSubscriptionTests: XCTestCase { let outgoingMutationQueue = NoOpMutationQueue() let mutationDatabaseAdapter = try AWSMutationDatabaseAdapter(storageAdapter: storageAdapter) let awsMutationEventPublisher = AWSMutationEventPublisher(eventSource: mutationDatabaseAdapter) - stateMachine = MockStateMachine(initialState: .notStarted, - resolver: RemoteSyncEngine.Resolver.resolve(currentState:action:)) + stateMachine = MockStateMachine( + initialState: .notStarted, + resolver: RemoteSyncEngine.Resolver.resolve(currentState:action:) + ) let syncEngine = RemoteSyncEngine( storageAdapter: storageAdapter, @@ -53,11 +55,13 @@ class LocalSubscriptionTests: XCTestCase { requestRetryablePolicy: MockRequestRetryablePolicy() ) - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) } catch { XCTFail(String(describing: error)) return @@ -67,11 +71,13 @@ class LocalSubscriptionTests: XCTestCase { return storageEngine } let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true @@ -112,14 +118,16 @@ class LocalSubscriptionTests: XCTestCase { } } - let model = Post(id: UUID().uuidString, - title: "Test Post", - content: "Test Post Content", - createdAt: .now(), - updatedAt: nil, - draft: false, - rating: nil, - comments: []) + let model = Post( + id: UUID().uuidString, + title: "Test Post", + content: "Test Post Content", + createdAt: .now(), + updatedAt: nil, + draft: false, + rating: nil, + comments: [] + ) _ = try await Amplify.DataStore.save(model) await fulfillment(of: [receivedMutationEvent], timeout: 1.0) @@ -147,14 +155,16 @@ class LocalSubscriptionTests: XCTestCase { } } - let model = Post(id: UUID().uuidString, - title: "Test Post", - content: "Test Post Content", - createdAt: .now(), - updatedAt: nil, - draft: false, - rating: nil, - comments: []) + let model = Post( + id: UUID().uuidString, + title: "Test Post", + content: "Test Post Content", + createdAt: .now(), + updatedAt: nil, + draft: false, + rating: nil, + comments: [] + ) _ = try await Amplify.DataStore.save(model) await fulfillment(of: [receivedMutationEvent], timeout: 1.0) @@ -169,14 +179,16 @@ class LocalSubscriptionTests: XCTestCase { /// - I am notified of `update` mutations func testUpdate() async throws { let originalContent = "Content as of \(Date())" - let model = Post(id: UUID().uuidString, - title: "Test Post", - content: originalContent, - createdAt: .now(), - updatedAt: nil, - draft: false, - rating: nil, - comments: []) + let model = Post( + id: UUID().uuidString, + title: "Test Post", + content: originalContent, + createdAt: .now(), + updatedAt: nil, + draft: false, + rating: nil, + comments: [] + ) _ = try await Amplify.DataStore.save(model) @@ -198,7 +210,7 @@ class LocalSubscriptionTests: XCTestCase { XCTFail("Unexpected error: \(error)") } } - + _ = try await Amplify.DataStore.save(newModel) await fulfillment(of: [receivedMutationEvent], timeout: 1.0) @@ -228,9 +240,11 @@ class LocalSubscriptionTests: XCTestCase { } } - let model = Post(title: "Test Post", - content: "Test Post Content", - createdAt: .now()) + let model = Post( + title: "Test Post", + content: "Test Post Content", + createdAt: .now() + ) _ = try await Amplify.DataStore.save(model) _ = try await Amplify.DataStore.delete(model) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionWithJSONModelTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionWithJSONModelTests.swift index c20ad32848..6d63939ea9 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionWithJSONModelTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionWithJSONModelTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest import Combine @testable import Amplify -@testable import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSDataStorePlugin +@testable import AWSPluginsCore /// Tests behavior of local DataStore subscriptions (as opposed to remote API subscription behaviors) /// using serialized JSON models @@ -38,8 +38,10 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let outgoingMutationQueue = NoOpMutationQueue() let mutationDatabaseAdapter = try AWSMutationDatabaseAdapter(storageAdapter: storageAdapter) let awsMutationEventPublisher = AWSMutationEventPublisher(eventSource: mutationDatabaseAdapter) - stateMachine = MockStateMachine(initialState: .notStarted, - resolver: RemoteSyncEngine.Resolver.resolve(currentState:action:)) + stateMachine = MockStateMachine( + initialState: .notStarted, + resolver: RemoteSyncEngine.Resolver.resolve(currentState:action:) + ) let syncEngine = RemoteSyncEngine( storageAdapter: storageAdapter, @@ -55,11 +57,13 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { requestRetryablePolicy: MockRequestRetryablePolicy() ) - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) } catch { XCTFail(String(describing: error)) return @@ -69,11 +73,13 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { return storageEngine } let dataStorePublisher = DataStorePublisher() - dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestJsonModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestJsonModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true @@ -121,9 +127,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! dataStorePlugin.save(model, modelSchema: postSchema) { _ in } @@ -160,24 +168,29 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { print("Ignore") } - }) + } + ) // insert a post let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! dataStorePlugin.save(model, modelSchema: postSchema) { _ in } // insert a comment let commentContent = "some content" - let comment = ["content": .string(commentContent), - "createdAt": .string(createdAt), - "post": .object(model.values)] as [String: JSONValue] + let comment = [ + "content": .string(commentContent), + "createdAt": .string(createdAt), + "post": .object(model.values) + ] as [String: JSONValue] let commentModel = DynamicModel(values: comment) let commentSchema = ModelRegistry.modelSchema(from: "Comment")! dataStorePlugin.save(commentModel, modelSchema: commentSchema) { result in @@ -219,9 +232,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! dataStorePlugin.save(model, modelSchema: postSchema) { _ in } @@ -239,9 +254,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let originalContent = "Content as of \(Date())" let title = "a title" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(originalContent), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(originalContent), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! @@ -305,9 +322,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! dataStorePlugin.save(model, modelSchema: postSchema) { _ in } @@ -344,9 +363,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! let savedPost = expectation(description: "post saved") @@ -362,9 +383,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { wait(for: [savedPost], timeout: 1.0) let commentContent = "some content" - let comment = ["content": .string(commentContent), - "createdAt": .string(createdAt), - "post": .object(model.values)] as [String: JSONValue] + let comment = [ + "content": .string(commentContent), + "createdAt": .string(createdAt), + "post": .object(model.values) + ] as [String: JSONValue] let commentModel = DynamicModel(values: comment) let commentSchema = ModelRegistry.modelSchema(from: "Comment")! let savedComment = expectation(description: "comment saved") @@ -380,9 +403,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { wait(for: [savedComment], timeout: 1.0) let queryCommentSuccess = expectation(description: "querying for comment should exist") - dataStorePlugin.query(DynamicModel.self, - modelSchema: commentSchema, - where: DynamicModel.keys.id == commentModel.id) { result in + dataStorePlugin.query( + DynamicModel.self, + modelSchema: commentSchema, + where: DynamicModel.keys.id == commentModel.id + ) { result in switch result { case .success(let comments): XCTAssertEqual(comments.count, 1) @@ -406,9 +431,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { subscriptionPost.cancel() let queryCommentEmpty = expectation(description: "querying for comment should be empty") - dataStorePlugin.query(DynamicModel.self, - modelSchema: commentSchema, - where: DynamicModel.keys.id == commentModel.id) { result in + dataStorePlugin.query( + DynamicModel.self, + modelSchema: commentSchema, + where: DynamicModel.keys.id == commentModel.id + ) { result in switch result { case .success(let comments): XCTAssertEqual(comments.count, 0) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationDatabaseAdapterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationDatabaseAdapterTests.swift index ff87ba4b70..7c999ec533 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationDatabaseAdapterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationDatabaseAdapterTests.swift @@ -9,10 +9,10 @@ import Foundation import SQLite import XCTest +import AWSPluginsCore @testable import Amplify @testable import AmplifyTestCommon @testable import AWSDataStorePlugin -import AWSPluginsCore class AWSMutationDatabaseAdapterTests: XCTestCase { var databaseAdapter: AWSMutationDatabaseAdapter! @@ -30,12 +30,16 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_replaceLocal_localCreateCandidateUpdate() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.create) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.update) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.create + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.update + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) @@ -43,42 +47,54 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_saveCandidate_CanadidateUpdateWithCondition() throws { - let anyLocal = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.create) + let anyLocal = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.create + ) let queryPredicate = post.title == model1.title let graphQLFilterJSON = try GraphQLFilterConverter.toJSON(queryPredicate, modelSchema: model1.schema) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.update, - graphQLFilterJSON: graphQLFilterJSON) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.update, + graphQLFilterJSON: graphQLFilterJSON + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [anyLocal]) XCTAssertEqual(disposition, .saveCandidate) } func test_saveCandidate_CanadidateDeleteWithCondition() throws { - let anyLocal = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.create) + let anyLocal = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.create + ) let queryPredicate = post.title == model1.title let graphQLFilterJSON = try GraphQLFilterConverter.toJSON(queryPredicate, modelSchema: model1.schema) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.delete, - graphQLFilterJSON: graphQLFilterJSON) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.delete, + graphQLFilterJSON: graphQLFilterJSON + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [anyLocal]) XCTAssertEqual(disposition, .saveCandidate) } func test_replaceLocal_BothUpdate() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.update) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.update) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.update + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.update + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) @@ -86,12 +102,16 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_replaceLocal_localUpdateCandidateDelete() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.update) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.delete) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.update + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.delete + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) @@ -99,12 +119,16 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_replaceLocal_BothDelete() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.delete) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.delete) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.delete + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.delete + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) @@ -112,12 +136,16 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_dropCandidate_localCreateCandidateDelete() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.create) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.delete) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.create + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.delete + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) @@ -125,12 +153,16 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_dropCandidateWithError_localItemExistsAlreadyCandidateCreates() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.create) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.create) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.create + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.create + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) @@ -138,31 +170,39 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_dropCandidateWithError_updateMutationForItemMarkedDeleted() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.delete) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.update) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.delete + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.update + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) XCTAssertEqual(disposition, .dropCandidateWithError(DataStoreError.unknown("", "", nil))) } - + /// Retrieve the first MutationEvent func test_getNextMutationEvent_AlreadyInProcess() async { let queryExpectation = expectation(description: "query called") let getMutationEventCompleted = expectation(description: "getNextMutationEvent completed") - var mutationEvent1 = MutationEvent(modelId: "1111-22", - modelName: "Post", - json: "{}", - mutationType: .create) + var mutationEvent1 = MutationEvent( + modelId: "1111-22", + modelName: "Post", + json: "{}", + mutationType: .create + ) mutationEvent1.inProcess = true - let mutationEvent2 = MutationEvent(modelId: "1111-22", - modelName: "Post", - json: "{}", - mutationType: .create) + let mutationEvent2 = MutationEvent( + modelId: "1111-22", + modelName: "Post", + json: "{}", + mutationType: .create + ) let queryResponder = QueryModelTypePredicateResponder { _, _ in queryExpectation.fulfill() return .success([mutationEvent1, mutationEvent2]) @@ -177,23 +217,27 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } getMutationEventCompleted.fulfill() } - + await fulfillment(of: [getMutationEventCompleted, queryExpectation], timeout: 1) } - + /// Retrieve the first MutationEvent func test_getNextMutationEvent_MarkInProcess() async { let queryExpectation = expectation(description: "query called") let getMutationEventCompleted = expectation(description: "getNextMutationEvent completed") - let mutationEvent1 = MutationEvent(modelId: "1111-22", - modelName: "Post", - json: "{}", - mutationType: .create) + let mutationEvent1 = MutationEvent( + modelId: "1111-22", + modelName: "Post", + json: "{}", + mutationType: .create + ) XCTAssertFalse(mutationEvent1.inProcess) - let mutationEvent2 = MutationEvent(modelId: "1111-22", - modelName: "Post", - json: "{}", - mutationType: .create) + let mutationEvent2 = MutationEvent( + modelId: "1111-22", + modelName: "Post", + json: "{}", + mutationType: .create + ) let queryResponder = QueryModelTypePredicateResponder { _, _ in queryExpectation.fulfill() return .success([mutationEvent1, mutationEvent2]) @@ -206,10 +250,10 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { case .failure(let error): XCTFail("Should have been successful result, error: \(error)") } - + getMutationEventCompleted.fulfill() } - + await fulfillment(of: [getMutationEventCompleted, queryExpectation], timeout: 1) } @@ -226,18 +270,22 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { let oldestCreatedAt = Temporal.DateTime.now().add(value: -1, to: .second) let newerCreatedAt = Temporal.DateTime.now().add(value: 1, to: .second) databaseAdapter.storageAdapter = storageAdapter - let m1 = MutationEvent(modelId: "m1", - modelName: "Post", - json: "{}", - mutationType: .create, - createdAt: newerCreatedAt, - inProcess: false) - let m2 = MutationEvent(modelId: "m2", - modelName: "Post", - json: "{}", - mutationType: .create, - createdAt: oldestCreatedAt, - inProcess: false) + let m1 = MutationEvent( + modelId: "m1", + modelName: "Post", + json: "{}", + mutationType: .create, + createdAt: newerCreatedAt, + inProcess: false + ) + let m2 = MutationEvent( + modelId: "m2", + modelName: "Post", + json: "{}", + mutationType: .create, + createdAt: oldestCreatedAt, + inProcess: false + ) let setUpM1 = storageAdapter.save(m1, modelSchema: MutationEvent.schema) guard case .success = setUpM1 else { XCTFail("Could not set up mutation event: \(m1)") @@ -282,9 +330,11 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { await fulfillment(of: [secondQueryCompleted], timeout: 1) // (3) - storageAdapter.delete(MutationEvent.self, - modelSchema: MutationEvent.schema, - withId: m2.id) { result in + storageAdapter.delete( + MutationEvent.self, + modelSchema: MutationEvent.schema, + withId: m2.id + ) { result in switch result { case .success: break @@ -312,8 +362,10 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } extension AWSMutationDatabaseAdapter.MutationDisposition: Equatable { - public static func == (lhs: AWSMutationDatabaseAdapter.MutationDisposition, - rhs: AWSMutationDatabaseAdapter.MutationDisposition) -> Bool { + public static func == ( + lhs: AWSMutationDatabaseAdapter.MutationDisposition, + rhs: AWSMutationDatabaseAdapter.MutationDisposition + ) -> Bool { switch (lhs, rhs) { case (.dropCandidateWithError, .dropCandidateWithError): return true diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationEventIngesterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationEventIngesterTests.swift index 40dfb6a6b6..a3a9880143 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationEventIngesterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationEventIngesterTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -36,26 +36,32 @@ class AWSMutationEventIngesterTests: XCTestCase { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) - let syncEngine = try RemoteSyncEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault()) + let syncEngine = try RemoteSyncEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault() + ) let validAPIPluginKey = "MockAPICategoryPlugin" let validAuthPluginKey = "MockAuthCategoryPlugin" - let storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let storageEngineBehaviorFactory: StorageEngineBehaviorFactory = {_, _, _, _, _, _ throws in return storageEngine } let publisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: publisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: publisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) try Amplify.add(plugin: apiPlugin) try Amplify.add(plugin: dataStorePlugin) @@ -71,9 +77,11 @@ class AWSMutationEventIngesterTests: XCTestCase { /// - Then: /// - The mutation queue writes events func testMutationQueueWritesSaveEvents() async throws { - let post = Post(title: "Post title", - content: "Post content", - createdAt: .now()) + let post = Post( + title: "Post title", + content: "Post content", + createdAt: .now() + ) _ = try await Amplify.DataStore.save(post) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationEventClearStateTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationEventClearStateTests.swift index 56860bea60..7ab2367f33 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationEventClearStateTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationEventClearStateTests.swift @@ -10,8 +10,8 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class MutationEventClearStateTests: XCTestCase { var mockStorageAdapter: MockSQLiteStorageEngineAdapter! @@ -29,10 +29,12 @@ class MutationEventClearStateTests: XCTestCase { let queryResponder = QueryModelTypePredicateResponder { _, _ in queryExpectation.fulfill() - var mutationEvent = MutationEvent(modelId: "1111-22", - modelName: "Post", - json: "{}", - mutationType: .create) + var mutationEvent = MutationEvent( + modelId: "1111-22", + modelName: "Post", + json: "{}", + mutationType: .create + ) mutationEvent.inProcess = true return .success([mutationEvent]) } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationIngesterConflictResolutionTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationIngesterConflictResolutionTests.swift index 6f8981eb00..42d05d05a4 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationIngesterConflictResolutionTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationIngesterConflictResolutionTests.swift @@ -30,10 +30,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - I receive an error /// - The mutation queue retains the original event func test_create_create() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -51,8 +53,10 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -83,10 +87,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is updated with the new values func test_create_update() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -103,8 +109,10 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -122,7 +130,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { } mutationEventVerified.fulfill() } - + await fulfillment(of: [mutationEventVerified], timeout: 1.0) } @@ -133,10 +141,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The delete is saved to DataStore /// - The mutation event is removed from the mutation queue func test_create_delete() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -145,13 +155,15 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { try setUpDataStore() try await startAmplifyAndWaitForSync() } - + try await Amplify.DataStore.delete(post) let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -173,10 +185,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - I receive an error /// - The mutation queue retains the original event func test_update_create() async { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -194,15 +208,19 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) case .success(let mutationEvents): XCTAssertEqual(mutationEvents.count, 1) - XCTAssertEqual(mutationEvents.first?.mutationType, - GraphQLMutationType.update.rawValue) + XCTAssertEqual( + mutationEvents.first?.mutationType, + GraphQLMutationType.update.rawValue + ) let firstEventJSON = mutationEvents[0].json let firstEventData = Data(firstEventJSON.utf8) @@ -228,10 +246,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is updated with the new values func test_update_update() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -248,8 +268,10 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -267,7 +289,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { } mutationEventVerified.fulfill() } - + await fulfillment(of: [mutationEventVerified], timeout: 1.0) } @@ -278,10 +300,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The delete is saved to DataStore /// - The mutation event is updated to a .delete type func test_update_delete() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -290,13 +314,15 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { try setUpDataStore() try await startAmplifyAndWaitForSync() } - + try await Amplify.DataStore.delete(post) let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -322,10 +348,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - I receive an error /// - The mutation queue retains the original event func test_delete_create() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -343,8 +371,10 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -369,10 +399,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - I receive an error /// - The mutation queue retains the original event func test_delete_update() async { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -393,8 +425,10 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -420,10 +454,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is appended to the queue func testCreateMutationAppendedToEmptyQueue() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -433,7 +469,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let savedPost = try await Amplify.DataStore.save(post) XCTAssertNotNil(savedPost) - + let mutationEventVerified = expectation(description: "Verified mutation event") storageAdapter.query(MutationEvent.self, predicate: nil) { result in switch result { @@ -464,10 +500,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is appended to the queue func testUpdateMutationAppendedToEmptyQueue() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -509,10 +547,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is appended to the queue func testDeleteMutationAppendedToEmptyQueue() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -551,10 +591,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is appended to the queue, even though it would normally have thrown an error func testCreateMutationAppendedToInProcessQueue() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -565,7 +607,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let savedPost = try await Amplify.DataStore.save(post) XCTAssertNotNil(savedPost) - + let mutationEventVerified = expectation(description: "Verified mutation event") storageAdapter.query(MutationEvent.self, predicate: nil) { result in switch result { @@ -590,10 +632,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The mutation event is appended to the queue, even though it would normally have overwritten the existing /// create func testUpdateMutationAppendedToInProcessQueue() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -643,10 +687,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is appended to the queue, even though it would normally have thrown an error func testDeleteMutationAppendedToInProcessQueue() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -657,7 +703,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { } try await Amplify.DataStore.delete(post) - + let mutationEventVerified = expectation(description: "Verified mutation event") storageAdapter.query(MutationEvent.self, predicate: nil) { result in switch result { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueNetworkTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueNetworkTests.swift index cafe0f5569..032dd9c5c3 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueNetworkTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueNetworkTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import SQLite import Combine +import SQLite +import XCTest +@_implementationOnly import AmplifyAsyncTesting @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin -@_implementationOnly import AmplifyAsyncTesting +@testable import AWSPluginsCore class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { @@ -36,13 +36,11 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { } } - let connectionError: APIError = { - APIError.networkError( - "TEST: Network not available", - nil, - URLError(.notConnectedToInternet) - ) - }() + let connectionError: APIError = .networkError( + "TEST: Network not available", + nil, + URLError(.notConnectedToInternet) + ) override func setUpWithError() throws { cancellables = [] @@ -96,8 +94,8 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { // The first response is a success for the initial "Create" mutation let apiRespondedWithSuccess = expectation(description: "apiRespondedWithSuccess") - let acceptInitialMutation = setUpInitialMutationRequestResponder( - for: try post.eraseToAnyModel(), + let acceptInitialMutation = try setUpInitialMutationRequestResponder( + for: post.eraseToAnyModel(), fulfilling: apiRespondedWithSuccess, incrementing: version ) @@ -155,7 +153,7 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { // the RemoteSyncEngine will stop the outgoing mutation queue. We will set the retry // advice interval to be very high, so it will be preempted by the "network available" // message we send later. - + let networkUnavailable = expectation(description: "networkUnavailable") setUpNetworkUnavailableListener( fulfillingWhenNetworkUnavailable: networkUnavailable @@ -208,13 +206,13 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { setUpOutboxEmptyListener( fulfillingWhenOutboxEmpty: outboxEmpty ) - + // Once we've rejected some mutations due to an unreachable network, we'll allow the final // mutation to succeed. This is where we will assert that we've seen the last mutation // to be processed let expectedFinalContentReceived = expectation(description: "expectedFinalContentReceived") - let acceptSubsequentMutations = setUpSubsequentMutationRequestResponder( - for: try post.eraseToAnyModel(), + let acceptSubsequentMutations = try setUpSubsequentMutationRequestResponder( + for: post.eraseToAnyModel(), fulfilling: expectedFinalContentReceived, whenContentContains: expectedFinalContent, incrementing: version @@ -228,7 +226,7 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { setUpNetworkAvailableListener( fulfillingWhenNetworkAvailableAgain: networkAvailableAgain ) - + apiPlugin.responders = [.mutateRequestResponse: acceptSubsequentMutations] reachabilitySubject.send(ReachabilityUpdate(isOnline: true)) await fulfillment( @@ -280,7 +278,8 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { ) -> MutateRequestResponder> { MutateRequestResponder> { request in guard let input = request.variables?["input"] as? [String: Any], - let content = input["content"] as? String else { + let content = input["content"] as? String + else { XCTFail("Unexpected request structure: no `content` in variables.") return .failure(.unknown("Unexpected request structure: no `content` in variables.", "", nil)) } @@ -295,7 +294,7 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { version: version.increment() ) ) - + if content == expectedFinalContent { expectation.fulfill() } @@ -325,7 +324,7 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { } .store(in: &cancellables) } - + private func setUpNetworkAvailableListener( fulfillingWhenNetworkAvailableAgain networkAvailableAgain: XCTestExpectation ) { @@ -339,14 +338,14 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { XCTFail("Failed to cast payload data as NetworkStatusEvent") return } - + if networkStatusEvent.active { networkAvailableAgain.fulfill() } } .store(in: &cancellables) } - + private func setUpSyncStartedListener( fulfillingWhenSyncStarted syncStarted: XCTestExpectation ) { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTests.swift index 8802e832ff..e0a51437f5 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTests.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class OutgoingMutationQueueTests: SyncEngineTestBase { @@ -146,7 +146,7 @@ class OutgoingMutationQueueTests: SyncEngineTestBase { let mutationEventSaved = expectation(description: "Preloaded mutation event saved") mutationEventSaved.expectedFulfillmentCount = 2 - let posts = (1...2).map { Post( + let posts = (1 ... 2).map { Post( id: "pendingPost-\($0)", title: "pendingPost-\($0) title", content: "pendingPost-\($0) content", @@ -168,15 +168,16 @@ class OutgoingMutationQueueTests: SyncEngineTestBase { apiPlugin.responders[.mutateRequestResponse] = MutateRequestResponder> { request in if let variables = request.variables?["input"] as? [String: Any], let postId = variables["id"] as? String, - let post = posts.first(where: { $0.id == postId }) - { + let post = posts.first(where: { $0.id == postId }) { try? await Task.sleep(seconds: timeout + 1) let anyModel = try! post.eraseToAnyModel() - let remoteSyncMetadata = MutationSyncMetadata(modelId: post.id, - modelName: Post.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 2) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: post.id, + modelName: Post.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 2 + ) let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) return .success(remoteMutationSync) } @@ -184,7 +185,7 @@ class OutgoingMutationQueueTests: SyncEngineTestBase { } - postMutationEvents.forEach { event in + for event in postMutationEvents { storageAdapter.save(event) { result in switch result { case .failure(let dataStoreError): @@ -239,9 +240,11 @@ class OutgoingMutationQueueTests: SyncEngineTestBase { } await tryOrFail { - try setUpDataStore(mutationQueue: OutgoingMutationQueue(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy())) + try setUpDataStore(mutationQueue: OutgoingMutationQueue( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy() + )) try await startAmplify() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTestsWithMockStateMachine.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTestsWithMockStateMachine.swift index 722a3821c2..60936a7068 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTestsWithMockStateMachine.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTestsWithMockStateMachine.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class OutgoingMutationQueueMockStateTest: XCTestCase { var mutationQueue: OutgoingMutationQueue! @@ -29,13 +29,17 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { XCTFail(String(describing: "Unable to setup API category for unit tests")) } ModelRegistry.register(modelType: Post.self) - stateMachine = MockStateMachine(initialState: .notInitialized, - resolver: OutgoingMutationQueue.Resolver.resolve(currentState:action:)) + stateMachine = MockStateMachine( + initialState: .notInitialized, + resolver: OutgoingMutationQueue.Resolver.resolve(currentState:action:) + ) storageAdapter = MockSQLiteStorageEngineAdapter() - mutationQueue = OutgoingMutationQueue(stateMachine, - storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + mutationQueue = OutgoingMutationQueue( + stateMachine, + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy() + ) eventSource = MockMutationEventSource() publisher = AWSMutationEventPublisher(eventSource: eventSource) apiBehavior = MockAPICategoryPlugin() @@ -49,10 +53,12 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { expect.fulfill() } - mutationQueue = OutgoingMutationQueue(stateMachine, - storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + mutationQueue = OutgoingMutationQueue( + stateMachine, + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy() + ) await fulfillment(of: [expect], timeout: 1) XCTAssertEqual(stateMachine.state, OutgoingMutationQueue.State.notInitialized) @@ -79,10 +85,12 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { await fulfillment(of: [receivedSubscription], timeout: 1.0) let json = "{\"id\":\"1234\",\"title\":\"t\",\"content\":\"c\",\"createdAt\":\"2020-09-03T22:55:13.424Z\"}" - let futureResult = MutationEvent(modelId: "1", - modelName: "Post", - json: json, - mutationType: MutationEvent.MutationType.create) + let futureResult = MutationEvent( + modelId: "1", + modelName: "Post", + json: json, + mutationType: MutationEvent.MutationType.create + ) eventSource.pushMutationEvent(futureResult: .success(futureResult)) let enqueueEvent = expectation(description: "state requestingEvent, enqueueEvent") @@ -97,11 +105,13 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { try! await Task.sleep(seconds: 0.5) let model = MockSynced(id: "id-1") let anyModel = try! model.eraseToAnyModel() - let remoteSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: MockSynced.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 2) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: MockSynced.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 2 + ) let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) return .success(remoteMutationSync) } @@ -143,12 +153,16 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { await fulfillment(of: [receivedSubscription], timeout: 0.1) // Mock incoming mutation event - let post = Post(title: "title", - content: "content", - createdAt: .now()) - let futureResult = try MutationEvent(model: post, - modelSchema: post.schema, - mutationType: .create) + let post = Post( + title: "title", + content: "content", + createdAt: .now() + ) + let futureResult = try MutationEvent( + model: post, + modelSchema: post.schema, + mutationType: .create + ) eventSource.pushMutationEvent(futureResult: .success(futureResult)) let enqueueEvent = expectation(description: "state requestingEvent, enqueueEvent") @@ -163,11 +177,13 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { try! await Task.sleep(seconds: 0.3) let model = MockSynced(id: "id-1") let anyModel = try! model.eraseToAnyModel() - let remoteSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: MockSynced.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 2) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: MockSynced.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 2 + ) let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) return .success(remoteMutationSync) } @@ -191,15 +207,19 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { // Re-enable syncing let startReceivedAgain = expectation(description: "Start received again") stateMachine.pushExpectActionCriteria { action in - XCTAssertEqual(action, OutgoingMutationQueue.Action.receivedStart(self.apiBehavior, - self.publisher, - self.reconciliationQueue)) + XCTAssertEqual(action, OutgoingMutationQueue.Action.receivedStart( + self.apiBehavior, + self.publisher, + self.reconciliationQueue + )) startReceivedAgain.fulfill() } - mutationQueue.startSyncingToCloud(api: apiBehavior, - mutationEventPublisher: publisher, - reconciliationQueue: reconciliationQueue) + mutationQueue.startSyncingToCloud( + api: apiBehavior, + mutationEventPublisher: publisher, + reconciliationQueue: reconciliationQueue + ) await fulfillment(of: [startReceivedAgain], timeout: 1) @@ -281,11 +301,13 @@ extension OutgoingMutationQueueMockStateTest { await Amplify.reset() let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: "MockAPICategoryPlugin", - validAuthPluginKey: "MockAuthCategoryPlugin") + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: "MockAPICategoryPlugin", + validAuthPluginKey: "MockAuthCategoryPlugin" + ) try Amplify.add(plugin: dataStorePlugin) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift index fc2133fa69..5adb099cdd 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore // swiftlint:disable type_body_length // swiftlint:disable type_name @@ -73,12 +73,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - apiError: apiError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + apiError: apiError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -116,12 +118,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - apiError: apiError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + apiError: apiError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -159,12 +163,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -203,12 +209,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -248,12 +256,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -299,12 +309,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectHubEvent, expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) Amplify.Hub.removeListener(hubListener) @@ -339,12 +351,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -378,12 +392,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -417,12 +433,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -434,8 +452,10 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { /// - Unexpected scenario, there should never be an conflict unhandled error without error.data func testConflictUnhandledReturnsErrorForMissingRemoteModel() throws { let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .create) - let graphQLError = GraphQLError(message: "conflict unhandled", - extensions: ["errorType": .string(AppSyncErrorType.conflictUnhandled.rawValue)]) + let graphQLError = GraphQLError( + message: "conflict unhandled", + extensions: ["errorType": .string(AppSyncErrorType.conflictUnhandled.rawValue)] + ) let graphQLResponseError = GraphQLResponseError>.error([graphQLError]) let expectCompletion = expectation(description: "Expect to complete error processing") let completion: (Result) -> Void = { result in @@ -449,12 +469,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { XCTAssertEqual(dataStoreError.errorDescription, "Missing remote model from the response from AppSync.") expectCompletion.fulfill() } - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: .testDefault(), - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: .testDefault(), + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -467,9 +489,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { func testConflictUnhandledReturnsErrorForCreateMutation() throws { let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .create) let remotePost = Post(title: "remoteTitle", content: "remoteContent", createdAt: .now()) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: false, - version: 1) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: false, + version: 1 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -485,12 +509,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { XCTAssertEqual(dataStoreError.errorDescription, "Should never get conflict unhandled for create mutation") expectCompletion.fulfill() } - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: .testDefault(), - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: .testDefault(), + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -504,9 +530,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let localPost = Post(title: "localTitle", content: "localContent", createdAt: .now()) let remotePost = Post(id: localPost.id, title: "remoteTitle", content: "remoteContent", createdAt: .now()) let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .delete) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: true, - version: 1) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: true, + version: 1 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -515,12 +543,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { self.assertSuccessfulNil(result) expectCompletion.fulfill() } - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: .testDefault(), - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: .testDefault(), + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -534,9 +564,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let localPost = Post(title: "localTitle", content: "localContent", createdAt: .now()) let remotePost = Post(id: localPost.id, title: "remoteTitle", content: "remoteContent", createdAt: .now()) let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .delete) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: false, - version: 2) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: false, + version: 2 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -548,11 +580,13 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let apiMutateCalled = expectation(description: "API was called") mockAPIPlugin.responders[.mutateRequestResponse] = MutateRequestResponder> { request in - let updatedMetadata = MutationSyncMetadata(modelId: remotePost.id, - modelName: remotePost.modelName, - deleted: true, - lastChangedAt: 0, - version: 3) + let updatedMetadata = MutationSyncMetadata( + modelId: remotePost.id, + modelName: remotePost.modelName, + deleted: true, + lastChangedAt: 0, + version: 3 + ) guard let variables = request.variables, let input = variables["input"] as? [String: Any] @@ -566,7 +600,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { guard let mockResponse = ( try? localPost.eraseToAnyModel() - ).map({ MutationSync(model:$0 , syncMetadata: updatedMetadata) }) + ).map({ MutationSync(model: $0, syncMetadata: updatedMetadata) }) else { XCTFail("Failed to wrap to AnyModel") return .failure(.unknown("", "", nil)) @@ -587,14 +621,16 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectConflicthandlerCalled.fulfill() resolve(.retryLocal) }) - - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - reconciliationQueue: reconciliationQueue, - completion: completion) + + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + reconciliationQueue: reconciliationQueue, + completion: completion + ) queue.addOperation(operation) @@ -612,9 +648,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let localPost = Post(title: "localTitle", content: "localContent", createdAt: .now()) let remotePost = Post(id: localPost.id, title: "remoteTitle", content: "remoteContent", createdAt: .now()) let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .delete) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: false, - version: 2) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: false, + version: 2 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -636,11 +674,13 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { XCTAssertTrue(request.document.contains("UpdatePost")) apiMutateCalled.fulfill() - let updatedMetadata = MutationSyncMetadata(modelId: remotePost.id, - modelName: remotePost.modelName, - deleted: false, - lastChangedAt: 0, - version: 3) + let updatedMetadata = MutationSyncMetadata( + modelId: remotePost.id, + modelName: remotePost.modelName, + deleted: false, + lastChangedAt: 0, + version: 3 + ) guard let mockResponse = (try? localPost.eraseToAnyModel()).map({ MutationSync(model: $0, syncMetadata: updatedMetadata) }) else { XCTFail("Failed to wrap to AnyModel") return .failure(.unknown("Failed to wrap to AnyModel", "", nil)) @@ -663,13 +703,15 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { resolve(.retry(retryModel)) }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - reconciliationQueue: reconciliationQueue, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + reconciliationQueue: reconciliationQueue, + completion: completion + ) queue.addOperation(operation) @@ -687,9 +729,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let localPost = Post(title: "localTitle", content: "localContent", createdAt: .now()) let remotePost = Post(id: localPost.id, title: "remoteTitle", content: "remoteContent", createdAt: .now()) let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .delete) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: false, - version: 2) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: false, + version: 2 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -732,12 +776,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectHubEvent.fulfill() } } - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: .testDefault(), - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: .testDefault(), + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) await fulfillment(of: [modelSavedEvent], timeout: defaultAsyncWaitTimeout) @@ -1002,9 +1048,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let localPost = Post(title: "localTitle", content: "localContent", createdAt: .now()) let remotePost = Post(id: localPost.id, title: "remoteTitle", content: "remoteContent", createdAt: .now()) let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .update) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: false, - version: 2) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: false, + version: 2 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -1086,9 +1134,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let localPost = Post(title: "localTitle", content: "localContent", createdAt: .now()) let remotePost = Post(id: localPost.id, title: "remoteTitle", content: "remoteContent", createdAt: .now()) let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .update) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: false, - version: 2) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: false, + version: 2 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -1132,12 +1182,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectConflicthandlerCalled.fulfill() resolve(.retryLocal) }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) await fulfillment(of: [ @@ -1166,10 +1218,12 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { XCTFail("Should have been successful") } - let graphQLError = try getGraphQLResponseError(withRemote: post, - deleted: false, - version: 0, - errorType: .operationDisabled) + let graphQLError = try getGraphQLResponseError( + withRemote: post, + deleted: false, + version: 0, + errorType: .operationDisabled + ) let operation = ProcessMutationErrorFromCloudOperation( dataStoreConfiguration: DataStoreConfiguration.testDefault(), @@ -1177,7 +1231,8 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { api: mockAPIPlugin, storageAdapter: storageAdapter, graphQLResponseError: graphQLError, - completion: completion) + completion: completion + ) queue.addOperation(operation) await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) @@ -1189,11 +1244,13 @@ extension ProcessMutationErrorFromCloudOperationTests { await Amplify.reset() let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: "MockAPICategoryPlugin", - validAuthPluginKey: "MockAuthCategoryPlugin") + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: "MockAPICategoryPlugin", + validAuthPluginKey: "MockAuthCategoryPlugin" + ) try Amplify.add(plugin: dataStorePlugin) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true @@ -1229,14 +1286,18 @@ extension ProcessMutationErrorFromCloudOperationTests { XCTAssertNil(mutationEventOptional) } - private func getGraphQLResponseError(withRemote post: Post = Post(title: "remoteTitle", - content: "remoteContent", - createdAt: .now()), - deleted: Bool = false, - version: Int = 1, - errorType: AppSyncErrorType? = .conflictUnhandled) + private func getGraphQLResponseError( + withRemote post: Post = Post( + title: "remoteTitle", + content: "remoteContent", + createdAt: .now() + ), + deleted: Bool = false, + version: Int = 1, + errorType: AppSyncErrorType? = .conflictUnhandled + ) throws -> GraphQLResponseError>? { - let data = Data(try post.toJSON().utf8) + let data = try Data(post.toJSON().utf8) let decoder = JSONDecoder() decoder.dateDecodingStrategy = ModelDateFormatting.decodingStrategy let remoteData = try decoder.decode(JSONValue.self, from: data) @@ -1247,10 +1308,14 @@ extension ProcessMutationErrorFromCloudOperationTests { remoteDataObject["_lastChangedAt"] = .number(123) remoteDataObject["_version"] = .number(Double(version)) remoteDataObject["__typename"] = .string(post.modelName) - if let errorType = errorType { - let graphQLError = GraphQLError(message: "error message", - extensions: ["errorType": .string(errorType.rawValue), - "data": .object(remoteDataObject)]) + if let errorType { + let graphQLError = GraphQLError( + message: "error message", + extensions: [ + "errorType": .string(errorType.rawValue), + "data": .object(remoteDataObject) + ] + ) return GraphQLResponseError>.error([graphQLError]) } else { let graphQLError = GraphQLError(message: "error message") @@ -1259,34 +1324,46 @@ extension ProcessMutationErrorFromCloudOperationTests { } private func graphQLError(_ errorType: AppSyncErrorType) -> GraphQLError { - GraphQLError(message: "message", - locations: nil, - path: nil, - extensions: ["errorType": .string(errorType.rawValue)]) + GraphQLError( + message: "message", + locations: nil, + path: nil, + extensions: ["errorType": .string(errorType.rawValue)] + ) } - - private func custom(errorHandler: DataStoreErrorHandler? = nil, - conflictHandler: (DataStoreConflictHandler)? = nil) -> DataStoreConfiguration { - if let conflictHandler = conflictHandler, let errorHandler = errorHandler { + + private func custom( + errorHandler: DataStoreErrorHandler? = nil, + conflictHandler: DataStoreConflictHandler? = nil + ) -> DataStoreConfiguration { + if let conflictHandler, let errorHandler { #if os(watchOS) - return .custom(errorHandler: errorHandler, - conflictHandler: conflictHandler, - disableSubscriptions: { false }) + return .custom( + errorHandler: errorHandler, + conflictHandler: conflictHandler, + disableSubscriptions: { false } + ) #else - return .custom(errorHandler: errorHandler, - conflictHandler: conflictHandler) + return .custom( + errorHandler: errorHandler, + conflictHandler: conflictHandler + ) #endif - } else if let errorHandler = errorHandler { + } else if let errorHandler { #if os(watchOS) - return .custom(errorHandler: errorHandler, - disableSubscriptions: { false }) + return .custom( + errorHandler: errorHandler, + disableSubscriptions: { false } + ) #else return .custom(errorHandler: errorHandler) #endif - } else if let conflictHandler = conflictHandler { + } else if let conflictHandler { #if os(watchOS) - return .custom(conflictHandler: conflictHandler, - disableSubscriptions: { false }) + return .custom( + conflictHandler: conflictHandler, + disableSubscriptions: { false } + ) #else return .custom(conflictHandler: conflictHandler) #endif diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/SyncMutationToCloudOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/SyncMutationToCloudOperationTests.swift index dbe8220e59..cad0cbd414 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/SyncMutationToCloudOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/SyncMutationToCloudOperationTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class SyncMutationToCloudOperationTests: XCTestCase { let defaultAsyncWaitTimeout = 2.0 @@ -53,11 +53,13 @@ class SyncMutationToCloudOperationTests: XCTestCase { return .failure(.unknown("", "", APIError.networkError("mock NotConnectedToInternetError", nil, urlError))) } else if numberOfTimesEntered == 1, let anyModel = try? model.eraseToAnyModel() { expectSecondCallToAPIMutate.fulfill() - let remoteSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 2) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 2 + ) return .success(MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata)) } else { XCTFail("This should not be called more than once") @@ -117,11 +119,13 @@ class SyncMutationToCloudOperationTests: XCTestCase { return .failure(.unknown("", "", APIError.networkError("mock NotConnectedToInternetError", nil, urlError))) } else if numberOfTimesEntered == 1, let anyModel = try? model.eraseToAnyModel() { expectSecondCallToAPIMutate.fulfill() - let remoteSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 2) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 2 + ) let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) return .success(remoteMutationSync) } else { @@ -205,12 +209,12 @@ class SyncMutationToCloudOperationTests: XCTestCase { operation.cancel() await fulfillment(of: [expectMutationRequestFailed], timeout: defaultAsyncWaitTimeout) } - + // MARK: - GetRetryAdviceIfRetryableTests - + func testGetRetryAdvice_NetworkError_RetryTrue() async throws { - let operation = await SyncMutationToCloudOperation( - mutationEvent: try createMutationEvent(), + let operation = try await SyncMutationToCloudOperation( + mutationEvent: createMutationEvent(), getLatestSyncMetadata: { nil }, api: mockAPIPlugin, authModeStrategy: AWSDefaultAuthModeStrategy(), @@ -218,15 +222,15 @@ class SyncMutationToCloudOperationTests: XCTestCase { currentAttemptNumber: 1, completion: { _ in } ) - + let error = APIError.networkError("", nil, URLError(.userAuthenticationRequired)) let advice = operation.getRetryAdviceIfRetryable(error: error) XCTAssertTrue(advice.shouldRetry) } - + func testGetRetryAdvice_HTTPStatusError401WithMultiAuth_RetryTrue() async throws { - let operation = await SyncMutationToCloudOperation( - mutationEvent: try createMutationEvent(), + let operation = try await SyncMutationToCloudOperation( + mutationEvent: createMutationEvent(), getLatestSyncMetadata: { nil }, api: mockAPIPlugin, authModeStrategy: MockMultiAuthModeStrategy(), @@ -234,15 +238,17 @@ class SyncMutationToCloudOperationTests: XCTestCase { currentAttemptNumber: 1, completion: { _ in } ) - let response = HTTPURLResponse(url: URL(string: "http://localhost")!, - statusCode: 401, - httpVersion: nil, - headerFields: nil)! + let response = HTTPURLResponse( + url: URL(string: "http://localhost")!, + statusCode: 401, + httpVersion: nil, + headerFields: nil + )! let error = APIError.httpStatusError(401, response) let advice = operation.getRetryAdviceIfRetryable(error: error) XCTAssertTrue(advice.shouldRetry) } - + /// Given: Model with multiple auth types. Mutation requests always fail with 401 error code /// When: Mutating model fails with 401 /// Then: DataStore will try again with each auth type and eventually fails @@ -251,15 +257,17 @@ class SyncMutationToCloudOperationTests: XCTestCase { let mutationEvent = try createMutationEvent() let authStrategy = MockMultiAuthModeStrategy() let expectedNumberOfTimesEntered = authStrategy.authTypesFor(schema: mutationEvent.schema, operation: .create).count - + let expectCalllToApiMutateNTimesAndFail = expectation(description: "Call API.mutate \(expectedNumberOfTimesEntered) times and then fail") - - let response = HTTPURLResponse(url: URL(string: "http://localhost")!, - statusCode: 401, - httpVersion: nil, - headerFields: nil)! + + let response = HTTPURLResponse( + url: URL(string: "http://localhost")!, + statusCode: 401, + httpVersion: nil, + headerFields: nil + )! let error = APIError.httpStatusError(401, response) - + let operation = await SyncMutationToCloudOperation( mutationEvent: mutationEvent, getLatestSyncMetadata: { nil }, @@ -270,29 +278,29 @@ class SyncMutationToCloudOperationTests: XCTestCase { completion: { result in if numberOfTimesEntered == expectedNumberOfTimesEntered { expectCalllToApiMutateNTimesAndFail.fulfill() - + } else { XCTFail("API.mutate was called incorrect amount of times, expected: \(expectedNumberOfTimesEntered), was : \(numberOfTimesEntered)") } } ) - + let responder = MutateRequestResponder> { request in defer { numberOfTimesEntered += 1 } return .failure(.unknown("", "", error)) } - + mockAPIPlugin.responders[.mutateRequestResponse] = responder let queue = OperationQueue() queue.addOperation(operation) - + await fulfillment(of: [expectCalllToApiMutateNTimesAndFail], timeout: defaultAsyncWaitTimeout) } - + func testGetRetryAdvice_OperationErrorAuthErrorWithMultiAuth_RetryTrue() async throws { - let operation = await SyncMutationToCloudOperation( - mutationEvent: try createMutationEvent(), + let operation = try await SyncMutationToCloudOperation( + mutationEvent: createMutationEvent(), getLatestSyncMetadata: { nil }, api: mockAPIPlugin, authModeStrategy: MockMultiAuthModeStrategy(), @@ -300,19 +308,19 @@ class SyncMutationToCloudOperationTests: XCTestCase { currentAttemptNumber: 1, completion: { _ in } ) - + let authError = AuthError.notAuthorized("", "", nil) let error = APIError.operationError("", "", authError) let advice = operation.getRetryAdviceIfRetryable(error: error) XCTAssertTrue(advice.shouldRetry) } - + func testGetRetryAdvice_OperationErrorAuthErrorWithSingleAuth_RetryFalse() async throws { let expectation = expectation(description: "operation completed") var numberOfTimesEntered = 0 var error: APIError? - let operation = await SyncMutationToCloudOperation( - mutationEvent: try createMutationEvent(), + let operation = try await SyncMutationToCloudOperation( + mutationEvent: createMutationEvent(), getLatestSyncMetadata: { nil }, api: mockAPIPlugin, authModeStrategy: AWSDefaultAuthModeStrategy(), @@ -343,10 +351,10 @@ class SyncMutationToCloudOperationTests: XCTestCase { await fulfillment(of: [expectation]) XCTAssertEqual(false, operation.getRetryAdviceIfRetryable(error: error!).shouldRetry) } - + func testGetRetryAdvice_OperationErrorAuthErrorSessionExpired_RetryTrue() async throws { - let operation = await SyncMutationToCloudOperation( - mutationEvent: try createMutationEvent(), + let operation = try await SyncMutationToCloudOperation( + mutationEvent: createMutationEvent(), getLatestSyncMetadata: { nil }, api: mockAPIPlugin, authModeStrategy: AWSDefaultAuthModeStrategy(), @@ -354,16 +362,16 @@ class SyncMutationToCloudOperationTests: XCTestCase { currentAttemptNumber: 1, completion: { _ in } ) - + let authError = AuthError.sessionExpired("", "", nil) let error = APIError.operationError("", "", authError) let advice = operation.getRetryAdviceIfRetryable(error: error) XCTAssertTrue(advice.shouldRetry) } - + func testGetRetryAdvice_OperationErrorAuthErrorSignedOut_RetryTrue() async throws { - let operation = await SyncMutationToCloudOperation( - mutationEvent: try createMutationEvent(), + let operation = try await SyncMutationToCloudOperation( + mutationEvent: createMutationEvent(), getLatestSyncMetadata: { nil }, api: mockAPIPlugin, authModeStrategy: AWSDefaultAuthModeStrategy(), @@ -371,34 +379,38 @@ class SyncMutationToCloudOperationTests: XCTestCase { currentAttemptNumber: 1, completion: { _ in } ) - + let authError = AuthError.signedOut("", "", nil) let error = APIError.operationError("", "", authError) let advice = operation.getRetryAdviceIfRetryable(error: error) XCTAssertTrue(advice.shouldRetry) } - + private func createMutationEvent() throws -> MutationEvent { let post1 = Post(title: "post1", content: "content1", createdAt: .now()) return try MutationEvent(model: post1, modelSchema: post1.schema, mutationType: .create) } - + } public class MockMultiAuthModeStrategy: AuthModeStrategy { public weak var authDelegate: AuthModeStrategyDelegate? - required public init() {} + public required init() {} - public func authTypesFor(schema: ModelSchema, - operation: ModelOperation) -> AWSAuthorizationTypeIterator { + public func authTypesFor( + schema: ModelSchema, + operation: ModelOperation + ) -> AWSAuthorizationTypeIterator { return AWSAuthorizationTypeIterator(withValues: [ .designated(.amazonCognitoUserPools), .designated(.apiKey) ]) } - public func authTypesFor(schema: ModelSchema, - operations: [ModelOperation]) -> AWSAuthorizationTypeIterator { + public func authTypesFor( + schema: ModelSchema, + operations: [ModelOperation] + ) -> AWSAuthorizationTypeIterator { return AWSAuthorizationTypeIterator(withValues: [ .designated(.amazonCognitoUserPools), .designated(.apiKey) @@ -411,11 +423,13 @@ extension SyncMutationToCloudOperationTests { await Amplify.reset() let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: "MockAPICategoryPlugin", - validAuthPluginKey: "MockAuthCategoryPlugin") + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: "MockAPICategoryPlugin", + validAuthPluginKey: "MockAuthCategoryPlugin" + ) try Amplify.add(plugin: dataStorePlugin) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSync/RemoteSyncAPIInvocationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSync/RemoteSyncAPIInvocationTests.swift index 0192e13ed3..60b63cbf79 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSync/RemoteSyncAPIInvocationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSync/RemoteSyncAPIInvocationTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest +@_implementationOnly import AmplifyAsyncTesting import Combine @testable import Amplify @testable import AmplifyTestCommon @testable import AWSDataStorePlugin -@_implementationOnly import AmplifyAsyncTesting /// Tests that DataStore invokes proper API methods to fulfill remote sync class RemoteSyncAPIInvocationTests: XCTestCase { @@ -40,13 +40,17 @@ class RemoteSyncAPIInvocationTests: XCTestCase { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) - let syncEngine = try RemoteSyncEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault()) - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let syncEngine = try RemoteSyncEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault() + ) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) } catch { XCTFail(String(describing: error)) return @@ -55,11 +59,13 @@ class RemoteSyncAPIInvocationTests: XCTestCase { return storageEngine } let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let apiConfig = APICategoryConfiguration(plugins: [apiPlugin.key: true]) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [dataStorePlugin.key: true]) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSyncEngineTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSyncEngineTests.swift index b12a1b9dca..ebb2a86bf1 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSyncEngineTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSyncEngineTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest import Combine @testable import Amplify @@ -46,7 +46,7 @@ class RemoteSyncEngineTests: XCTestCase { } func testErrorOnNilStorageAdapter() throws { - guard let remoteSyncEngine = remoteSyncEngine else { + guard let remoteSyncEngine else { XCTFail("Failed to initialize remoteSyncEngine") return } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RequestRetryablePolicyTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RequestRetryablePolicyTests.swift index bf4e51baa7..190c7861d5 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RequestRetryablePolicyTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RequestRetryablePolicyTests.swift @@ -18,9 +18,11 @@ class RequestRetryablePolicyTests: XCTestCase { } func testNoErrorNoHttpURLResponse() { - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssertFalse(retryAdvice.shouldRetry) XCTAssertEqual(retryAdvice.retryInterval, defaultTimeout) @@ -29,70 +31,90 @@ class RequestRetryablePolicyTests: XCTestCase { func testNoErrorWithHttpURLResponseWithRetryAfterInHeader() { let headerFields = ["Retry-After": "42"] let url = URL(string: "http://www.amazon.com")! - let httpURLResponse = HTTPURLResponse(url: url, - statusCode: 429, - httpVersion: "HTTP/1.1", - headerFields: headerFields)! - - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: httpURLResponse, - attemptNumber: 1) + let httpURLResponse = HTTPURLResponse( + url: url, + statusCode: 429, + httpVersion: "HTTP/1.1", + headerFields: headerFields + )! + + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: httpURLResponse, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertSeconds(retryAdvice.retryInterval, seconds: 42) } func testNoErrorWithHttpURLResponseWithoutRetryAfterInHeader_attempt1() { let url = URL(string: "http://www.amazon.com")! - let httpURLResponse = HTTPURLResponse(url: url, - statusCode: 429, - httpVersion: "HTTP/1.1", - headerFields: nil)! - - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: httpURLResponse, - attemptNumber: 1) + let httpURLResponse = HTTPURLResponse( + url: url, + statusCode: 429, + httpVersion: "HTTP/1.1", + headerFields: nil + )! + + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: httpURLResponse, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) } func testNoErrorWithHttpURLResponseWithoutRetryAfterInHeader_attempt2() { let url = URL(string: "http://www.amazon.com")! - let httpURLResponse = HTTPURLResponse(url: url, - statusCode: 429, - httpVersion: "HTTP/1.1", - headerFields: nil)! - - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: httpURLResponse, - attemptNumber: 2) + let httpURLResponse = HTTPURLResponse( + url: url, + statusCode: 429, + httpVersion: "HTTP/1.1", + headerFields: nil + )! + + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: httpURLResponse, + attemptNumber: 2 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 400, lessThan: 500) } func testNoErrorWithHttpURLResponseBeyondMaxWaitTime() { let url = URL(string: "http://www.amazon.com")! - let httpURLResponse = HTTPURLResponse(url: url, - statusCode: 429, - httpVersion: "HTTP/1.1", - headerFields: nil)! - - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: httpURLResponse, - attemptNumber: 12) + let httpURLResponse = HTTPURLResponse( + url: url, + statusCode: 429, + httpVersion: "HTTP/1.1", + headerFields: nil + )! + + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: httpURLResponse, + attemptNumber: 12 + ) XCTAssertFalse(retryAdvice.shouldRetry) XCTAssertEqual(retryAdvice.retryInterval, defaultTimeout) } func testNoErrorWithHttpURLResponseNotRetryable() { let url = URL(string: "http://www.amazon.com")! - let httpURLResponse = HTTPURLResponse(url: url, - statusCode: 204, - httpVersion: "HTTP/1.1", - headerFields: nil)! - - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: httpURLResponse, - attemptNumber: 1) + let httpURLResponse = HTTPURLResponse( + url: url, + statusCode: 204, + httpVersion: "HTTP/1.1", + headerFields: nil + )! + + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: httpURLResponse, + attemptNumber: 1 + ) XCTAssertFalse(retryAdvice.shouldRetry) XCTAssertEqual(retryAdvice.retryInterval, defaultTimeout) } @@ -101,9 +123,11 @@ class RequestRetryablePolicyTests: XCTestCase { let retryableErrorCode = URLError.init(.notConnectedToInternet) let attemptNumber = 1 - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: attemptNumber) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: attemptNumber + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -113,9 +137,11 @@ class RequestRetryablePolicyTests: XCTestCase { let retryableErrorCode = URLError.init(.notConnectedToInternet) let attemptNumber = 2 - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: attemptNumber) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: attemptNumber + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 400, lessThan: 500) @@ -125,9 +151,11 @@ class RequestRetryablePolicyTests: XCTestCase { let retryableErrorCode = URLError.init(.notConnectedToInternet) let attemptNumber = 3 - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: attemptNumber) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: attemptNumber + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 800, lessThan: 900) @@ -136,9 +164,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testDNSLookupFailedError() { let retryableErrorCode = URLError.init(.dnsLookupFailed) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -147,9 +177,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testCannotConnectToHostError() { let retryableErrorCode = URLError.init(.cannotConnectToHost) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -158,9 +190,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testCannotFindHostError() { let retryableErrorCode = URLError.init(.cannotFindHost) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -169,9 +203,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testTimedOutError() { let retryableErrorCode = URLError.init(.timedOut) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -180,20 +216,24 @@ class RequestRetryablePolicyTests: XCTestCase { func testCannotParseResponseError() { let retryableErrorCode = URLError.init(.cannotParseResponse) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) } - + func testNetworkConnectionLostError() { let retryableErrorCode = URLError.init(.networkConnectionLost) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -202,9 +242,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testUserAuthenticationRequiredError() { let retryableErrorCode = URLError.init(.userAuthenticationRequired) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -213,9 +255,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testHTTPTooManyRedirectsError() { let nonRetryableErrorCode = URLError.init(.httpTooManyRedirects) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nonRetryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nonRetryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssertFalse(retryAdvice.shouldRetry) XCTAssertEqual(retryAdvice.retryInterval, defaultTimeout) @@ -224,9 +268,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testSecureConnectionFailedError() { let retryableErrorCode = URLError.init(.secureConnectionFailed) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -235,9 +281,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testMaxValueRetryDelay() { let retryableErrorCode = URLError.init(.timedOut) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 31) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 31 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 214_748_364_800, lessThan: 214_748_364_900) @@ -246,9 +294,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testBeyondMaxValueRetryDelay() { let retryableErrorCode = URLError.init(.timedOut) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 32) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 32 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 214_748_364_800, lessThan: 214_748_364_900) @@ -257,16 +307,18 @@ class RequestRetryablePolicyTests: XCTestCase { func testOverflowCase() { let retryableErrorCode = URLError.init(.timedOut) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 58) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 58 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 214_748_364_800, lessThan: 214_748_364_900) } func assertMilliseconds(_ retryInterval: DispatchTimeInterval?, greaterThan: Int, lessThan: Int) { - guard let retryInterval = retryInterval else { + guard let retryInterval else { XCTFail("retryInterval is nil") return } @@ -281,7 +333,7 @@ class RequestRetryablePolicyTests: XCTestCase { } func assertSeconds(_ retryInterval: DispatchTimeInterval?, seconds expectedSeconds: Int) { - guard let retryInterval = retryInterval else { + guard let retryInterval else { XCTFail("retryInterval is nil") return } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/StorageEngineSyncRequirementsTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/StorageEngineSyncRequirementsTests.swift index 917616005f..97629cb299 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/StorageEngineSyncRequirementsTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/StorageEngineSyncRequirementsTests.swift @@ -113,38 +113,58 @@ class StorageEngineSyncRequirementsTests: XCTestCase { XCTAssertFalse(StorageEngine.requiresAuthPlugin(apiPlugin, authRules: authRules, authModeStrategy: .default)) XCTAssertFalse(StorageEngine.requiresAuthPlugin(apiPlugin, authRules: authRules, authModeStrategy: .multiAuth)) } - + func testRequiresAuthPluginOIDCProvider_MultiAuthRules() { // OIDC requires an auth provider on the API, this is added below - let authRules = [AuthRule(allow: .owner, provider: .oidc), - AuthRule(allow: .private, provider: .iam)] + let authRules = [ + AuthRule(allow: .owner, provider: .oidc), + AuthRule(allow: .private, provider: .iam) + ] let apiPlugin = MockAPIAuthInformationPlugin() apiPlugin.defaultAuthTypeError = APIError.unknown("Could not get default auth type", "", nil) let oidcProvider = MockOIDCAuthProvider() apiPlugin.authProviderFactory = MockAPIAuthProviderFactory(oidcProvider: oidcProvider) - XCTAssertFalse(StorageEngine.requiresAuthPlugin(apiPlugin, - authRules: authRules, - authModeStrategy: .default), - "Should be false since OIDC is the default auth type on the API.") - XCTAssertTrue(StorageEngine.requiresAuthPlugin(apiPlugin, - authRules: authRules, - authModeStrategy: .multiAuth), - "Should be true since IAM requires auth plugin.") - } - + XCTAssertFalse( + StorageEngine.requiresAuthPlugin( + apiPlugin, + authRules: authRules, + authModeStrategy: .default + ), + "Should be false since OIDC is the default auth type on the API." + ) + XCTAssertTrue( + StorageEngine.requiresAuthPlugin( + apiPlugin, + authRules: authRules, + authModeStrategy: .multiAuth + ), + "Should be true since IAM requires auth plugin." + ) + } + func testRequiresAuthPluginUserPoolProvider_MultiAuthRules() { - let authRules = [AuthRule(allow: .owner, provider: .userPools), - AuthRule(allow: .private, provider: .iam)] + let authRules = [ + AuthRule(allow: .owner, provider: .userPools), + AuthRule(allow: .private, provider: .iam) + ] let apiPlugin = MockAPIAuthInformationPlugin() apiPlugin.authType = AWSAuthorizationType.amazonCognitoUserPools - XCTAssertTrue(StorageEngine.requiresAuthPlugin(apiPlugin, - authRules: authRules, - authModeStrategy: .default), - "Should be true since UserPool is the default auth type on the API.") - XCTAssertTrue(StorageEngine.requiresAuthPlugin(apiPlugin, - authRules: authRules, - authModeStrategy: .multiAuth), - "Should be true since both UserPool and IAM requires auth plugin.") + XCTAssertTrue( + StorageEngine.requiresAuthPlugin( + apiPlugin, + authRules: authRules, + authModeStrategy: .default + ), + "Should be true since UserPool is the default auth type on the API." + ) + XCTAssertTrue( + StorageEngine.requiresAuthPlugin( + apiPlugin, + authRules: authRules, + authModeStrategy: .multiAuth + ), + "Should be true since both UserPool and IAM requires auth plugin." + ) } func testRequiresAuthPluginFunctionProvider() { @@ -238,7 +258,7 @@ class StorageEngineSyncRequirementsTests: XCTestCase { func defaultAuthType(for apiName: String?) throws -> AWSAuthorizationType { if let error = defaultAuthTypeError { throw error - } else if let authType = authType { + } else if let authType { return authType } else { return .amazonCognitoUserPools diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueueTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueueTests.swift index 7969b27416..255b1221bb 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueueTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueueTests.swift @@ -10,8 +10,8 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class AWSIncomingEventReconciliationQueueTests: XCTestCase { var storageAdapter: MockSQLiteStorageEngineAdapter! @@ -42,7 +42,8 @@ class AWSIncomingEventReconciliationQueueTests: XCTestCase { storageAdapter: storageAdapter, syncExpressions: [], authModeStrategy: AWSDefaultAuthModeStrategy(), - modelReconciliationQueueFactory: modelReconciliationQueueFactory) + modelReconciliationQueueFactory: modelReconciliationQueueFactory + ) } // This test case attempts to hit a race condition, and may be required to execute multiple times @@ -216,7 +217,7 @@ class AWSIncomingEventReconciliationQueueTests: XCTestCase { XCTFail("Should not expect any other state, received: \(event)") } }) - + let reconciliationQueues = MockModelReconciliationQueue.mockModelReconciliationQueues for (queueName, queue) in reconciliationQueues { let cancellableOperation = CancelAwareBlockOperation { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisherTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisherTests.swift index 3adb5410c2..f9ec503fc6 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisherTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisherTests.swift @@ -8,8 +8,8 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore final class IncomingAsyncSubscriptionEventPublisherTests: XCTestCase { var apiPlugin: MockAPICategoryPlugin! @@ -41,7 +41,8 @@ final class IncomingAsyncSubscriptionEventPublisherTests: XCTestCase { modelPredicate: nil, auth: nil, authModeStrategy: AWSDefaultAuthModeStrategy(), - awsAuthService: nil) + awsAuthService: nil + ) let mapper = IncomingAsyncSubscriptionEventToAnyModelMapper() asyncEvents.subscribe(subscriber: mapper) let sink = mapper @@ -74,7 +75,8 @@ final class IncomingAsyncSubscriptionEventPublisherTests: XCTestCase { modelPredicate: nil, auth: nil, authModeStrategy: AWSDefaultAuthModeStrategy(), - awsAuthService: nil) + awsAuthService: nil + ) let mapper = IncomingAsyncSubscriptionEventToAnyModelMapper() asyncEvents.subscribe(subscriber: mapper) let sink = mapper @@ -92,15 +94,19 @@ final class IncomingAsyncSubscriptionEventPublisherTests: XCTestCase { } ) - for index in 0..>.InProcessListener @@ -31,11 +31,13 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { } let model = MockSynced(id: "id-1") - let localSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: MockSynced.modelName, - deleted: true, - lastChangedAt: Date().unixSeconds, - version: 2) + let localSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: MockSynced.modelName, + deleted: true, + lastChangedAt: Date().unixSeconds, + version: 2 + ) let localMetadataSaved = expectation(description: "Local metadata saved") storageAdapter.save(localSyncMetadata) { _ in localMetadataSaved.fulfill() } await fulfillment(of: [localMetadataSaved], timeout: 1) @@ -67,11 +69,13 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { } let anyModel = try model.eraseToAnyModel() - let remoteSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: MockSynced.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: MockSynced.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) asyncSequence.send(.data(.success(remoteMutationSync))) @@ -79,8 +83,10 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { // we have to brute-force this wait try await Task.sleep(seconds: 1.0) - let finalLocalMetadata = try storageAdapter.queryMutationSyncMetadata(for: model.id, - modelName: MockSynced.modelName) + let finalLocalMetadata = try storageAdapter.queryMutationSyncMetadata( + for: model.id, + modelName: MockSynced.modelName + ) XCTAssertEqual(finalLocalMetadata?.version, 2) XCTAssertEqual(finalLocalMetadata?.deleted, true) @@ -97,8 +103,9 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { func mockRemoteSyncEngineFor_testUpdateAfterDelete() { remoteSyncEngineSink = syncEngine .publisher - .sink(receiveCompletion: {_ in }, - receiveValue: { (event: RemoteSyncEngineEvent) in + .sink( + receiveCompletion: {_ in }, + receiveValue: { (event: RemoteSyncEngineEvent) in switch event { case .mutationsPaused: // Assume AWSIncomingEventReconciliationQueue succeeds in establishing connections @@ -120,7 +127,8 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { default: break } - }) + } + ) } /// - Given: @@ -155,7 +163,7 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { mockRemoteSyncEngineFor_testDeleteWithNoLocalModel() try await startAmplifyAndWaitForSync() } - + await fulfillment(of: [expectationListener], timeout: 1) guard let asyncSequence else { XCTFail("Incoming responder didn't set up listener") @@ -163,8 +171,10 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { } let syncReceivedNotification = expectation(description: "Received 'syncReceived' update from Hub") - let syncReceivedToken = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { _ in + let syncReceivedToken = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { _ in syncReceivedNotification.fulfill() } guard try await HubListenerTestUtilities.waitForListener(with: syncReceivedToken, timeout: 5.0) else { @@ -174,17 +184,21 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { let model = MockSynced(id: "id-1") let anyModel = try model.eraseToAnyModel() - let remoteSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: MockSynced.modelName, - deleted: true, - lastChangedAt: Date().unixSeconds, - version: 2) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: MockSynced.modelName, + deleted: true, + lastChangedAt: Date().unixSeconds, + version: 2 + ) let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) asyncSequence.send(.data(.success(remoteMutationSync))) await fulfillment(of: [syncReceivedNotification], timeout: 1) - let finalLocalMetadata = try storageAdapter.queryMutationSyncMetadata(for: model.id, - modelName: MockSynced.modelName) + let finalLocalMetadata = try storageAdapter.queryMutationSyncMetadata( + for: model.id, + modelName: MockSynced.modelName + ) XCTAssertEqual(finalLocalMetadata?.version, 2) XCTAssertEqual(finalLocalMetadata?.deleted, true) @@ -203,8 +217,9 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { func mockRemoteSyncEngineFor_testDeleteWithNoLocalModel() { remoteSyncEngineSink = syncEngine .publisher - .sink(receiveCompletion: {_ in }, - receiveValue: { (event: RemoteSyncEngineEvent) in + .sink( + receiveCompletion: {_ in }, + receiveValue: { (event: RemoteSyncEngineEvent) in switch event { case .mutationsPaused: // Assume AWSIncomingEventReconciliationQueue succeeds in establishing connections @@ -242,6 +257,7 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { default: break } - }) + } + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationQueueBehaviorTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationQueueBehaviorTests.swift index 34e381fba5..53e6ac0c3a 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationQueueBehaviorTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationQueueBehaviorTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Combine +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -27,14 +27,16 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { eventsNotSaved.fulfill() } - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) // We know this won't be nil, but we need to keep a reference to the queue in memory for the duration of the // test, and since we don't act on it otherwise, Swift warns about queue never being used. @@ -42,11 +44,13 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { for iteration in 1 ... 3 { let model = try MockSynced(id: "id-\(iteration)").eraseToAnyModel() - let syncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let syncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) } @@ -78,22 +82,26 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { completion(.success(model)) } - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) for iteration in 1 ... 3 { let model = try MockSynced(id: "id-\(iteration)").eraseToAnyModel() - let syncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let syncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) } @@ -159,22 +167,26 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { let syncExpression = DataStoreSyncExpression.syncExpression(MockSynced.schema, where: { MockSynced.keys.id == "id-1" || MockSynced.keys.id == "id-3" }) - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: syncExpression.modelPredicate(), - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: syncExpression.modelPredicate(), + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) for iteration in 1 ... 3 { let model = try MockSynced(id: "id-\(iteration)").eraseToAnyModel() - let syncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let syncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) } @@ -259,21 +271,25 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { completion(.success(mutationSyncMetadata)) } - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) for iteration in 1 ... 3 { let model = try MockSynced(id: "id-\(iteration)").eraseToAnyModel() - let syncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let syncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) } @@ -339,21 +355,25 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { completion(.success(mutationSyncMetadata)) } - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) for iteration in 1 ... 2 { let model = try MockSynced(id: "id-\(iteration)").eraseToAnyModel() - let syncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let syncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) } @@ -419,11 +439,13 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { }) let model = try MockSynced(id: "id-3").eraseToAnyModel() - let syncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let syncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) @@ -444,11 +466,14 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { extension ModelReconciliationQueueBehaviorTests { private func completionSignalWithAppSyncError(_ error: AppSyncErrorType) -> Subscribers.Completion { let appSyncJSONValue: JSONValue = .string(error.rawValue) - let graphqlError = GraphQLError.init(message: "", - locations: nil, - path: nil, - extensions: [ - "errorType": appSyncJSONValue]) + let graphqlError = GraphQLError.init( + message: "", + locations: nil, + path: nil, + extensions: [ + "errorType": appSyncJSONValue + ] + ) let graphqlResponseError = GraphQLResponseError>.error([graphqlError]) let apiError = APIError.operationError("error message", "recovery message", graphqlResponseError) let dataStoreError = DataStoreError.api(apiError, nil) @@ -457,14 +482,16 @@ extension ModelReconciliationQueueBehaviorTests { func testProcessingUnauthorizedError() async { let eventSentViaPublisher = expectation(description: "Sent via publisher") - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) let completion = completionSignalWithAppSyncError(AppSyncErrorType.unauthorized) let queueSink = queue.publisher.sink(receiveCompletion: { value in @@ -485,14 +512,16 @@ extension ModelReconciliationQueueBehaviorTests { func testProcessingOperationDisabledError() async { let eventSentViaPublisher = expectation(description: "Sent via publisher") - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) let completion = completionSignalWithAppSyncError(AppSyncErrorType.operationDisabled) let queueSink = queue.publisher.sink(receiveCompletion: { value in @@ -513,14 +542,16 @@ extension ModelReconciliationQueueBehaviorTests { func testProcessingUnhandledErrors() async { let eventSentViaPublisher = expectation(description: "Sent via publisher") - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) let completion = completionSignalWithAppSyncError(AppSyncErrorType.conflictUnhandled) let queueSink = queue.publisher.sink(receiveCompletion: { _ in diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndLocalSaveOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndLocalSaveOperationTests.swift index 0b83465e7e..152232ed8f 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndLocalSaveOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndLocalSaveOperationTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -36,36 +36,46 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) - anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: testPost.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: testPost.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) let testDelete = Post(id: "2", title: "post2", content: "content2", createdAt: .now()) let anyPostDelete = AnyModel(testDelete) - let anyPostDeleteMetadata = MutationSyncMetadata(modelId: "2", - modelName: testPost.modelName, - deleted: true, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 2) + let anyPostDeleteMetadata = MutationSyncMetadata( + modelId: "2", + modelName: testPost.modelName, + deleted: true, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 2 + ) anyPostDeletedMutationSync = MutationSync(model: anyPostDelete, syncMetadata: anyPostDeleteMetadata) - anyPostMutationEvent = MutationEvent(id: "1", - modelId: "3", - modelName: testPost.modelName, - json: "", - mutationType: .create) + anyPostMutationEvent = MutationEvent( + id: "1", + modelId: "3", + modelName: testPost.modelName, + json: "", + mutationType: .create + ) storageAdapter = MockSQLiteStorageEngineAdapter() storageAdapter.returnOnQuery(dataStoreResult: .none) storageAdapter.returnOnSave(dataStoreResult: .none) - stateMachine = MockStateMachine(initialState: .waiting, - resolver: ReconcileAndLocalSaveOperation.Resolver.resolve(currentState:action:)) + stateMachine = MockStateMachine( + initialState: .waiting, + resolver: ReconcileAndLocalSaveOperation.Resolver.resolve(currentState:action:) + ) - operation = ReconcileAndLocalSaveOperation(modelSchema: anyPostMutationSync.model.schema, - remoteModels: [anyPostMutationSync], - storageAdapter: storageAdapter, - stateMachine: stateMachine) + operation = ReconcileAndLocalSaveOperation( + modelSchema: anyPostMutationSync.model.schema, + remoteModels: [anyPostMutationSync], + storageAdapter: storageAdapter, + stateMachine: stateMachine + ) cancellables = Set() } @@ -103,8 +113,10 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { }.store(in: &cancellables) stateMachine.pushExpectActionCriteria { action in - XCTAssertEqual(action, - ReconcileAndLocalSaveOperation.Action.errored(DataStoreError.nilStorageAdapter())) + XCTAssertEqual( + action, + ReconcileAndLocalSaveOperation.Action.errored(DataStoreError.nilStorageAdapter()) + ) expect.fulfill() } @@ -332,34 +344,42 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { XCTAssertEqual(remoteModelToApply.remoteModel.model.id, anyPostMutationSync.model.id) } - func testSeparateDispositions_notifyDropped () async { + func testSeparateDispositions_notifyDropped() async { let expect = expectation(description: "notify dropped twice") expect.expectedFulfillmentCount = 2 let model1 = AnyModel(Post(title: "post1", content: "content", createdAt: .now())) let model2 = AnyModel(Post(title: "post2", content: "content", createdAt: .now())) - let metadata1 = MutationSyncMetadata(modelId: model1.id, - modelName: model1.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) - let metadata2 = MutationSyncMetadata(modelId: model2.id, - modelName: model2.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let metadata1 = MutationSyncMetadata( + modelId: model1.id, + modelName: model1.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) + let metadata2 = MutationSyncMetadata( + modelId: model2.id, + modelName: model2.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let remoteModel1 = MutationSync(model: model1, syncMetadata: metadata1) let remoteModel2 = MutationSync(model: model2, syncMetadata: metadata2) - let mutationEvent1 = MutationEvent(id: "1", - modelId: remoteModel1.model.id, - modelName: remoteModel1.model.modelName, - json: "", - mutationType: .create) - let mutationEvent2 = MutationEvent(id: "2", - modelId: remoteModel2.model.id, - modelName: remoteModel2.model.modelName, - json: "", - mutationType: .create) + let mutationEvent1 = MutationEvent( + id: "1", + modelId: remoteModel1.model.id, + modelName: remoteModel1.model.modelName, + json: "", + mutationType: .create + ) + let mutationEvent2 = MutationEvent( + id: "2", + modelId: remoteModel2.model.id, + modelName: remoteModel2.model.modelName, + json: "", + mutationType: .create + ) operation.publisher .sink { completion in switch completion { @@ -494,29 +514,37 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { expect.expectedFulfillmentCount = 2 let model1 = AnyModel(Post(title: "post1", content: "content", createdAt: .now())) let model2 = AnyModel(Post(title: "post2", content: "content", createdAt: .now())) - let metadata1 = MutationSyncMetadata(modelId: model1.id, - modelName: model1.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) - let metadata2 = MutationSyncMetadata(modelId: model2.id, - modelName: model2.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let metadata1 = MutationSyncMetadata( + modelId: model1.id, + modelName: model1.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) + let metadata2 = MutationSyncMetadata( + modelId: model2.id, + modelName: model2.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let remoteModel1 = MutationSync(model: model1, syncMetadata: metadata1) let remoteModel2 = MutationSync(model: model2, syncMetadata: metadata2) - let localMetadata1 = MutationSyncMetadata(modelId: model1.id, - modelName: model1.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 3) - let localMetadata2 = MutationSyncMetadata(modelId: model2.id, - modelName: model2.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 4) + let localMetadata1 = MutationSyncMetadata( + modelId: model1.id, + modelName: model1.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 3 + ) + let localMetadata2 = MutationSyncMetadata( + modelId: model2.id, + modelName: model2.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 4 + ) operation.publisher .sink { completion in switch completion { @@ -536,8 +564,10 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { } }.store(in: &cancellables) - let result = operation.getDispositions(for: [remoteModel1, remoteModel2], - localMetadatas: [localMetadata1, localMetadata2]) + let result = operation.getDispositions( + for: [remoteModel1, remoteModel2], + localMetadatas: [localMetadata1, localMetadata2] + ) XCTAssertTrue(result.isEmpty) await fulfillment(of: [expect], timeout: 1) @@ -854,15 +884,17 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { } func testApplyRemoteModels_skipFailedOperations() async throws { - let dispositions: [RemoteSyncReconciler.Disposition] = [.create(anyPostMutationSync), - .create(anyPostMutationSync), - .update(anyPostMutationSync), - .update(anyPostMutationSync), - .delete(anyPostMutationSync), - .delete(anyPostMutationSync), - .create(anyPostMutationSync), - .update(anyPostMutationSync), - .delete(anyPostMutationSync)] + let dispositions: [RemoteSyncReconciler.Disposition] = [ + .create(anyPostMutationSync), + .create(anyPostMutationSync), + .update(anyPostMutationSync), + .update(anyPostMutationSync), + .delete(anyPostMutationSync), + .delete(anyPostMutationSync), + .create(anyPostMutationSync), + .update(anyPostMutationSync), + .delete(anyPostMutationSync) + ] let expect = expectation(description: "should complete") let expectedDeleteSuccess = expectation(description: "delete should be successful") expectedDeleteSuccess.expectedFulfillmentCount = 3 // 3 delete depositions @@ -916,15 +948,17 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { func testApplyRemoteModels_failWithConstraintViolationShouldBeSuccessful() async { let expect = expectation(description: "should complete successfully") expect.expectedFulfillmentCount = 2 - let dispositions: [RemoteSyncReconciler.Disposition] = [.create(anyPostMutationSync), - .create(anyPostMutationSync), - .update(anyPostMutationSync), - .update(anyPostMutationSync), - .delete(anyPostMutationSync), - .delete(anyPostMutationSync), - .create(anyPostMutationSync), - .update(anyPostMutationSync), - .delete(anyPostMutationSync)] + let dispositions: [RemoteSyncReconciler.Disposition] = [ + .create(anyPostMutationSync), + .create(anyPostMutationSync), + .update(anyPostMutationSync), + .update(anyPostMutationSync), + .delete(anyPostMutationSync), + .delete(anyPostMutationSync), + .create(anyPostMutationSync), + .update(anyPostMutationSync), + .delete(anyPostMutationSync) + ] let expectDropped = expectation(description: "should notify dropped") expectDropped.expectedFulfillmentCount = dispositions.count let dataStoreError = DataStoreError.internalOperation("Failed to save", "") @@ -1087,11 +1121,13 @@ extension ReconcileAndLocalSaveOperationTests { await Amplify.reset() let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: "MockAPICategoryPlugin", - validAuthPluginKey: "MockAuthCategoryPlugin") + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: "MockAPICategoryPlugin", + validAuthPluginKey: "MockAuthCategoryPlugin" + ) try Amplify.add(plugin: dataStorePlugin) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndSaveQueueTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndSaveQueueTests.swift index da06a88397..02783c8ce0 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndSaveQueueTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndSaveQueueTests.swift @@ -8,8 +8,8 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class ReconcileAndSaveQueueTests: XCTestCase { var storageAdapter: MockSQLiteStorageEngineAdapter! @@ -20,18 +20,22 @@ class ReconcileAndSaveQueueTests: XCTestCase { ModelRegistry.register(modelType: Post.self) let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) - anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: testPost.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: testPost.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) storageAdapter = MockSQLiteStorageEngineAdapter() storageAdapter.returnOnQuery(dataStoreResult: .none) storageAdapter.returnOnSave(dataStoreResult: .none) - stateMachine = MockStateMachine(initialState: .waiting, - resolver: ReconcileAndLocalSaveOperation.Resolver.resolve(currentState:action:)) + stateMachine = MockStateMachine( + initialState: .waiting, + resolver: ReconcileAndLocalSaveOperation.Resolver.resolve(currentState:action:) + ) } func testAddOperation() throws { @@ -50,10 +54,12 @@ class ReconcileAndSaveQueueTests: XCTestCase { return } } - let operation = ReconcileAndLocalSaveOperation(modelSchema: anyPostMutationSync.model.schema, - remoteModels: [anyPostMutationSync], - storageAdapter: storageAdapter, - stateMachine: stateMachine) + let operation = ReconcileAndLocalSaveOperation( + modelSchema: anyPostMutationSync.model.schema, + remoteModels: [anyPostMutationSync], + storageAdapter: storageAdapter, + stateMachine: stateMachine + ) queue.addOperation(operation, modelName: Post.modelName) XCTAssertEqual(stateMachine.state, ReconcileAndLocalSaveOperation.State.waiting) wait(for: [operationAdded], timeout: 1) @@ -79,10 +85,12 @@ class ReconcileAndSaveQueueTests: XCTestCase { return } } - let operation = ReconcileAndLocalSaveOperation(modelSchema: anyPostMutationSync.model.schema, - remoteModels: [anyPostMutationSync], - storageAdapter: storageAdapter, - stateMachine: stateMachine) + let operation = ReconcileAndLocalSaveOperation( + modelSchema: anyPostMutationSync.model.schema, + remoteModels: [anyPostMutationSync], + storageAdapter: storageAdapter, + stateMachine: stateMachine + ) queue.addOperation(operation, modelName: Post.modelName) XCTAssertEqual(stateMachine.state, ReconcileAndLocalSaveOperation.State.waiting) wait(for: [operationAdded], timeout: 1) @@ -109,10 +117,12 @@ class ReconcileAndSaveQueueTests: XCTestCase { return } } - let operation = ReconcileAndLocalSaveOperation(modelSchema: anyPostMutationSync.model.schema, - remoteModels: [anyPostMutationSync], - storageAdapter: storageAdapter, - stateMachine: stateMachine) + let operation = ReconcileAndLocalSaveOperation( + modelSchema: anyPostMutationSync.model.schema, + remoteModels: [anyPostMutationSync], + storageAdapter: storageAdapter, + stateMachine: stateMachine + ) queue.addOperation(operation, modelName: Post.modelName) XCTAssertEqual(stateMachine.state, ReconcileAndLocalSaveOperation.State.waiting) wait(for: [operationAdded], timeout: 1) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/RemoteSyncReconcilerTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/RemoteSyncReconcilerTests.swift index 3cac3f153d..51a16369de 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/RemoteSyncReconcilerTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/RemoteSyncReconcilerTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -26,8 +26,10 @@ class RemoteSyncReconcilerTests: XCTestCase { func testReconcileLocalMetadata_nilLocalMetadata() { let remoteModel = makeRemoteModel(deleted: false, version: 1) - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: nil) + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: nil + ) XCTAssertEqual(disposition, .create(remoteModel)) } @@ -35,60 +37,78 @@ class RemoteSyncReconcilerTests: XCTestCase { func testReconcileLocalMetadata_nilLocalMetadata_deletedModel() { let remoteModel = makeRemoteModel(deleted: true, version: 2) - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: nil) + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: nil + ) XCTAssertNil(disposition) } func testReconcileLocalMetadata_withLocalEqualVersion() { let remoteModel = makeRemoteModel(deleted: false, version: 1) - let localSyncMetadata = makeMutationSyncMetadata(modelId: remoteModel.model.id, - modelName: remoteModel.model.modelName, - deleted: false, - version: 1) - - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: localSyncMetadata) + let localSyncMetadata = makeMutationSyncMetadata( + modelId: remoteModel.model.id, + modelName: remoteModel.model.modelName, + deleted: false, + version: 1 + ) + + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: localSyncMetadata + ) XCTAssertEqual(disposition, nil) } func testReconcileLocalMetadata_withLocalLowerVersion() { let remoteModel = makeRemoteModel(deleted: false, version: 2) - let localSyncMetadata = makeMutationSyncMetadata(modelId: remoteModel.model.id, - modelName: remoteModel.model.modelName, - deleted: false, - version: 1) - - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: localSyncMetadata) + let localSyncMetadata = makeMutationSyncMetadata( + modelId: remoteModel.model.id, + modelName: remoteModel.model.modelName, + deleted: false, + version: 1 + ) + + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: localSyncMetadata + ) XCTAssertEqual(disposition, .update(remoteModel)) } func testReconcileLocalMetadata_withLocalLowerVersion_deletedModel() { let remoteModel = makeRemoteModel(deleted: true, version: 2) - let localSyncMetadata = makeMutationSyncMetadata(modelId: remoteModel.model.id, - modelName: remoteModel.model.modelName, - deleted: false, - version: 1) - - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: localSyncMetadata) + let localSyncMetadata = makeMutationSyncMetadata( + modelId: remoteModel.model.id, + modelName: remoteModel.model.modelName, + deleted: false, + version: 1 + ) + + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: localSyncMetadata + ) XCTAssertEqual(disposition, .delete(remoteModel)) } func testReconcileLocalMetadata_withLocalHigherVersion() { let remoteModel = makeRemoteModel(deleted: false, version: 1) - let localSyncMetadata = makeMutationSyncMetadata(modelId: remoteModel.model.id, - modelName: remoteModel.model.modelName, - deleted: false, - version: 2) - - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: localSyncMetadata) + let localSyncMetadata = makeMutationSyncMetadata( + modelId: remoteModel.model.id, + modelName: remoteModel.model.modelName, + deleted: false, + version: 2 + ) + + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: localSyncMetadata + ) XCTAssertNil(disposition) } @@ -97,13 +117,17 @@ class RemoteSyncReconcilerTests: XCTestCase { // conflict updating a deleted record, or the client is incorrectly manipulating the version func testReconcileLocalMetadata_withLocalHigherVersion_deletedModel() { let remoteModel = makeRemoteModel(deleted: true, version: 1) - let localSyncMetadata = makeMutationSyncMetadata(modelId: remoteModel.model.id, - modelName: remoteModel.model.modelName, - deleted: false, - version: 2) - - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: localSyncMetadata) + let localSyncMetadata = makeMutationSyncMetadata( + modelId: remoteModel.model.id, + modelName: remoteModel.model.modelName, + deleted: false, + version: 2 + ) + + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: localSyncMetadata + ) XCTAssertNil(disposition) } @@ -143,22 +167,28 @@ class RemoteSyncReconcilerTests: XCTestCase { // with local metadata, not deleted remote, should be update let updateModel = makeRemoteModel(deleted: false, version: 2) - let localUpdateMetadata = makeMutationSyncMetadata(modelId: updateModel.model.id, - modelName: updateModel.model.modelName, - deleted: false, - version: 1) + let localUpdateMetadata = makeMutationSyncMetadata( + modelId: updateModel.model.id, + modelName: updateModel.model.modelName, + deleted: false, + version: 1 + ) // with local metadata, deleted remote, should be delete let deleteModel = makeRemoteModel(deleted: true, version: 2) - let localDeleteMetadata = makeMutationSyncMetadata(modelId: deleteModel.model.id, - modelName: deleteModel.model.modelName, - deleted: false, - version: 1) + let localDeleteMetadata = makeMutationSyncMetadata( + modelId: deleteModel.model.id, + modelName: deleteModel.model.modelName, + deleted: false, + version: 1 + ) let remoteModels = [createModel, droppedModel, updateModel, deleteModel] let localMetadatas = [localUpdateMetadata, localDeleteMetadata] - let dispositions = RemoteSyncReconciler.getDispositions(remoteModels, - localMetadatas: localMetadatas) + let dispositions = RemoteSyncReconciler.getDispositions( + remoteModels, + localMetadatas: localMetadatas + ) XCTAssertEqual(dispositions.count, 3) let create = expectation(description: "exactly one create") @@ -179,10 +209,10 @@ class RemoteSyncReconcilerTests: XCTestCase { } await fulfillment(of: [create, update, delete], timeout: 1) } - + func testGetDispositions_emptyLocal_singleModelAddedAndDeleted() { let sameId = UUID().uuidString - + let remoteModels = [ makeRemoteModel(modelId: sameId, deleted: false, version: 1), makeRemoteModel(modelId: sameId, deleted: true, version: 2) @@ -192,10 +222,10 @@ class RemoteSyncReconcilerTests: XCTestCase { XCTAssertTrue(dispositions.isEmpty) } - + func testGetDispositions_emptyLocal_oneModelAdded_SecondModelAddedAndDeleted() { let sameId = UUID().uuidString - + let remoteModels = [ makeRemoteModel(deleted: false, version: 1), makeRemoteModel(modelId: sameId, deleted: false, version: 1), @@ -209,44 +239,56 @@ class RemoteSyncReconcilerTests: XCTestCase { // MARK: - Utilities - private func makeMutationSyncMetadata(modelId: String, - modelName: String, - deleted: Bool = false, - version: Int = 1) -> MutationSyncMetadata { - - let remoteSyncMetadata = MutationSyncMetadata(modelId: modelId, - modelName: modelName, - deleted: deleted, - lastChangedAt: Date().unixSeconds, - version: version) + private func makeMutationSyncMetadata( + modelId: String, + modelName: String, + deleted: Bool = false, + version: Int = 1 + ) -> MutationSyncMetadata { + + let remoteSyncMetadata = MutationSyncMetadata( + modelId: modelId, + modelName: modelName, + deleted: deleted, + lastChangedAt: Date().unixSeconds, + version: version + ) return remoteSyncMetadata } - private func makeRemoteModel(modelId: String = UUID().uuidString, - deleted: Bool = false, - version: Int = 1) -> ReconcileAndLocalSaveOperation.RemoteModel { + private func makeRemoteModel( + modelId: String = UUID().uuidString, + deleted: Bool = false, + version: Int = 1 + ) -> ReconcileAndLocalSaveOperation.RemoteModel { do { let remoteMockSynced = try MockSynced(id: modelId).eraseToAnyModel() - let remoteSyncMetadata = makeMutationSyncMetadata(modelId: remoteMockSynced.id, - modelName: remoteMockSynced.modelName, - deleted: deleted, - version: version) - return ReconcileAndLocalSaveOperation.RemoteModel(model: remoteMockSynced, - syncMetadata: remoteSyncMetadata) + let remoteSyncMetadata = makeMutationSyncMetadata( + modelId: remoteMockSynced.id, + modelName: remoteMockSynced.modelName, + deleted: deleted, + version: version + ) + return ReconcileAndLocalSaveOperation.RemoteModel( + model: remoteMockSynced, + syncMetadata: remoteSyncMetadata + ) } catch { fatalError("Failed to create remote model") } } private func makeMutationEvent(modelId: String = UUID().uuidString) -> MutationEvent { - return MutationEvent(id: "mutation-1", - modelId: modelId, - modelName: MockSynced.modelName, - json: "{}", - mutationType: .create, - createdAt: .now(), - version: 1, - inProcess: false) + return MutationEvent( + id: "mutation-1", + modelId: modelId, + modelName: MockSynced.modelName, + json: "{}", + mutationType: .create, + createdAt: .now(), + version: 1, + inProcess: false + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/EquatableExtensions.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/EquatableExtensions.swift index d182dd5903..92190989c6 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/EquatableExtensions.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/EquatableExtensions.swift @@ -10,8 +10,10 @@ import AWSPluginsCore @testable import AWSDataStorePlugin extension RemoteSyncReconciler.Disposition: Equatable { - public static func == (lhs: RemoteSyncReconciler.Disposition, - rhs: RemoteSyncReconciler.Disposition) -> Bool { + public static func == ( + lhs: RemoteSyncReconciler.Disposition, + rhs: RemoteSyncReconciler.Disposition + ) -> Bool { switch (lhs, rhs) { case (.create(let model1), .create(let model2)): return model1.model.id == model2.model.id && @@ -29,8 +31,10 @@ extension RemoteSyncReconciler.Disposition: Equatable { } extension ReconcileAndLocalSaveOperation.Action: Equatable { - public static func == (lhs: ReconcileAndLocalSaveOperation.Action, - rhs: ReconcileAndLocalSaveOperation.Action) -> Bool { + public static func == ( + lhs: ReconcileAndLocalSaveOperation.Action, + rhs: ReconcileAndLocalSaveOperation.Action + ) -> Bool { switch (lhs, rhs) { case (.started(let models1), .started(let models2)): return models1.count == models2.count @@ -47,8 +51,10 @@ extension ReconcileAndLocalSaveOperation.Action: Equatable { } extension ReconcileAndLocalSaveOperation.State: Equatable { - public static func == (lhs: ReconcileAndLocalSaveOperation.State, - rhs: ReconcileAndLocalSaveOperation.State) -> Bool { + public static func == ( + lhs: ReconcileAndLocalSaveOperation.State, + rhs: ReconcileAndLocalSaveOperation.State + ) -> Bool { switch (lhs, rhs) { case (.waiting, .waiting): return true diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockModelReconciliationQueue.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockModelReconciliationQueue.swift index 251a13daf1..fc7b0924c7 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockModelReconciliationQueue.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockModelReconciliationQueue.swift @@ -5,13 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore + class MockModelReconciliationQueue: ModelReconciliationQueue { public static var mockModelReconciliationQueues: [String: MockModelReconciliationQueue] = [:] @@ -22,14 +23,16 @@ class MockModelReconciliationQueue: ModelReconciliationQueue { return modelReconciliationQueueSubject.eraseToAnyPublisher() } - init(modelSchema: ModelSchema, - storageAdapter: StorageEngineAdapter?, - api: APICategoryGraphQLBehavior, - reconcileAndSaveQueue: ReconcileAndSaveOperationQueue, - modelPredicate: QueryPredicate?, - auth: AuthCategoryBehavior?, - authModeStrategy: AuthModeStrategy, - incomingSubscriptionEvents: IncomingSubscriptionEventPublisher? = nil) { + init( + modelSchema: ModelSchema, + storageAdapter: StorageEngineAdapter?, + api: APICategoryGraphQLBehavior, + reconcileAndSaveQueue: ReconcileAndSaveOperationQueue, + modelPredicate: QueryPredicate?, + auth: AuthCategoryBehavior?, + authModeStrategy: AuthModeStrategy, + incomingSubscriptionEvents: IncomingSubscriptionEventPublisher? = nil + ) { self.modelReconciliationQueueSubject = PassthroughSubject() self.modelSchema = modelSchema MockModelReconciliationQueue.mockModelReconciliationQueues[modelSchema.name] = self diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockSQLiteStorageEngineAdapter.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockSQLiteStorageEngineAdapter.swift index dbdfdbf2a2..459ba8e884 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockSQLiteStorageEngineAdapter.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockSQLiteStorageEngineAdapter.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore import Combine +import XCTest @testable import Amplify @testable import AWSDataStorePlugin @@ -81,66 +81,81 @@ class MockSQLiteStorageEngineAdapter: StorageEngineAdapter { // MARK: - StorageEngineAdapter - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withId id: String, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) { + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withId id: String, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) { XCTFail("Not expected to execute") } - - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - filter: QueryPredicate, - completion: @escaping DataStoreCallback<[M]>) { + + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + filter: QueryPredicate, + completion: @escaping DataStoreCallback<[M]> + ) { XCTFail("Not expected to execute") } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, completion: @escaping DataStoreCallback) where M: Model { + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) where M: Model { XCTFail("Not expected to execute") } - - func delete(untypedModelType modelType: Model.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, - completion: (DataStoreResult) -> Void) { + + func delete( + untypedModelType modelType: Model.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: (DataStoreResult) -> Void + ) { if let responder = responders[.deleteUntypedModel] as? DeleteUntypedModelCompletionResponder { let result = responder.callback((modelType, identifier.stringValue)) completion(result) return } - + return shouldReturnErrorOnDeleteMutation ? completion(.failure(causedBy: DataStoreError.invalidModelName("DelMutate"))) : completion(.emptyResult) } - func query(modelSchema: ModelSchema, - predicate: QueryPredicate?, - eagerLoad: Bool, - completion: DataStoreCallback<[Model]>) { + func query( + modelSchema: ModelSchema, + predicate: QueryPredicate?, + eagerLoad: Bool, + completion: DataStoreCallback<[Model]> + ) { let result = resultForQuery ?? .failure(DataStoreError.invalidOperation(causedBy: nil)) completion(result) } - func query(_ modelType: M.Type, - predicate: QueryPredicate?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: DataStoreCallback<[M]>) { + func query( + _ modelType: M.Type, + predicate: QueryPredicate?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: DataStoreCallback<[M]> + ) { XCTFail("Not expected to execute") } - func query(_ modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: (DataStoreResult<[M]>) -> Void) { + func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: (DataStoreResult<[M]>) -> Void + ) { XCTFail("Not expected to execute") } @@ -163,10 +178,12 @@ class MockSQLiteStorageEngineAdapter: StorageEngineAdapter { completion(resultForSave!) } - func save(_ model: M, - condition: QueryPredicate?, - eagerLoad: Bool, - completion: @escaping DataStoreCallback) { + func save( + _ model: M, + condition: QueryPredicate?, + eagerLoad: Bool, + completion: @escaping DataStoreCallback + ) { if let responder = responders[.saveModelCompletion] as? SaveModelCompletionResponder { responder.callback((model, completion)) return @@ -177,19 +194,23 @@ class MockSQLiteStorageEngineAdapter: StorageEngineAdapter { : completion(.success(model)) } - func save(_ model: M, - modelSchema: ModelSchema, - condition: QueryPredicate?, - eagerLoad: Bool) -> DataStoreResult { + func save( + _ model: M, + modelSchema: ModelSchema, + condition: QueryPredicate?, + eagerLoad: Bool + ) -> DataStoreResult { XCTFail("Not yet implemented") return .failure(.internalOperation("", "", nil)) } - func save(_ model: M, - modelSchema: ModelSchema, - condition where: QueryPredicate?, - eagerLoad: Bool, - completion: @escaping DataStoreCallback) { + func save( + _ model: M, + modelSchema: ModelSchema, + condition where: QueryPredicate?, + eagerLoad: Bool, + completion: @escaping DataStoreCallback + ) { if let responder = responders[.saveModelCompletion] as? SaveModelCompletionResponder { responder.callback((model, completion)) return @@ -205,12 +226,14 @@ class MockSQLiteStorageEngineAdapter: StorageEngineAdapter { return nil } - func query(_ modelType: M.Type, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: DataStoreCallback<[M]>) { + func query( + _ modelType: M.Type, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: DataStoreCallback<[M]> + ) { if let responder = responders[.queryModelTypePredicate] as? QueryModelTypePredicateResponder { let result = responder.callback((modelType, predicate)) @@ -297,12 +320,14 @@ class MockStorageEngineBehavior: StorageEngineBehavior { init() { } - init(isSyncEnabled: Bool, - dataStoreConfiguration: DataStoreConfiguration, - validAPIPluginKey: String = "awsAPIPlugin", - validAuthPluginKey: String = "awsCognitoAuthPlugin", - modelRegistryVersion: String, - userDefault: UserDefaults = UserDefaults.standard) throws { + init( + isSyncEnabled: Bool, + dataStoreConfiguration: DataStoreConfiguration, + validAPIPluginKey: String = "awsAPIPlugin", + validAuthPluginKey: String = "awsCognitoAuthPlugin", + modelRegistryVersion: String, + userDefault: UserDefaults = UserDefaults.standard + ) throws { } func setupPublisher() { @@ -355,50 +380,62 @@ class MockStorageEngineBehavior: StorageEngineBehavior { func applyModelMigrations(modelSchemas: [ModelSchema]) throws { } - func save(_ model: M, - condition: QueryPredicate?, - eagerLoad: Bool, - completion: @escaping DataStoreCallback) { + func save( + _ model: M, + condition: QueryPredicate?, + eagerLoad: Bool, + completion: @escaping DataStoreCallback + ) { XCTFail("Not expected to execute") } - func save(_ model: M, - modelSchema: ModelSchema, - condition where: QueryPredicate?, - eagerLoad: Bool, - completion: @escaping DataStoreCallback) { + func save( + _ model: M, + modelSchema: ModelSchema, + condition where: QueryPredicate?, + eagerLoad: Bool, + completion: @escaping DataStoreCallback + ) { XCTFail("Not expected to execute") } - - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withId id: String, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) { + + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withId id: String, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) { XCTFail("Not expected to execute") } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - filter: QueryPredicate, - completion: @escaping DataStoreCallback<[M]>) { + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + filter: QueryPredicate, + completion: @escaping DataStoreCallback<[M]> + ) { XCTFail("Not expected to execute") } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) where M: Model { + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) where M: Model { completion(.success(nil)) } - func query(_ modelType: M.Type, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: DataStoreCallback<[M]>) { + func query( + _ modelType: M.Type, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: DataStoreCallback<[M]> + ) { if let responder = responders[.query] as? QueryResponder { let result = responder.callback(()) completion(result) @@ -407,13 +444,15 @@ class MockStorageEngineBehavior: StorageEngineBehavior { } } - func query(_ modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: (DataStoreResult<[M]>) -> Void) { + func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: (DataStoreResult<[M]>) -> Void + ) { if let responder = responders[.query] as? QueryResponder { let result = responder.callback(()) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/AWSAuthorizationTypeIteratorTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/AWSAuthorizationTypeIteratorTests.swift index f07db70e2b..3e000ffc8a 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/AWSAuthorizationTypeIteratorTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/AWSAuthorizationTypeIteratorTests.swift @@ -5,27 +5,27 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore +import XCTest class AWSAuthorizationTypeIteratorTests: XCTestCase { - + func testEmptyIterator_hasNextValue_false() throws { var iterator = AWSAuthorizationTypeIterator(withValues: []) - + XCTAssertFalse(iterator.hasNext) XCTAssertNil(iterator.next()) } - + func testOneElementIterator_hasNextValue_once() throws { var iterator = AWSAuthorizationTypeIterator(withValues: [.designated(.amazonCognitoUserPools)]) XCTAssertTrue(iterator.hasNext) XCTAssertNotNil(iterator.next()) - + XCTAssertFalse(iterator.hasNext) } - + func testTwoElementsIterator_hasNextValue_twice() throws { var iterator = AWSAuthorizationTypeIterator(withValues: [ .designated(.amazonCognitoUserPools), @@ -34,10 +34,10 @@ class AWSAuthorizationTypeIteratorTests: XCTestCase { XCTAssertTrue(iterator.hasNext) XCTAssertNotNil(iterator.next()) - + XCTAssertTrue(iterator.hasNext) XCTAssertNotNil(iterator.next()) - + XCTAssertFalse(iterator.hasNext) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/ModelCompareTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/ModelCompareTests.swift index bac2f4e8ed..ec70db6641 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/ModelCompareTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/ModelCompareTests.swift @@ -25,20 +25,24 @@ class ModelCompareTests: BaseDataStoreTests { let draft = false let rating = 4.0 let status = PostStatus.published - let post1 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) - let post2 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) + let post1 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) + let post2 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) XCTAssertTrue(Post.schema.compare(post1, post2)) } @@ -50,20 +54,24 @@ class ModelCompareTests: BaseDataStoreTests { let draft = false let rating = 4.0 let status = PostStatus.published - var post1 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) - var post2 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) + var post1 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) + var post2 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) let commentId = UUID().uuidString let comment1 = Comment(id: commentId, content: "This is a comment.", createdAt: createdAt, post: post1) let comment2 = Comment(id: commentId, content: "This is a comment.", createdAt: createdAt, post: post2) @@ -81,20 +89,24 @@ class ModelCompareTests: BaseDataStoreTests { let status = PostStatus.published // creating posts with different id - var post1 = Post(id: UUID().uuidString, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) - var post2 = Post(id: UUID().uuidString, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) + var post1 = Post( + id: UUID().uuidString, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) + var post2 = Post( + id: UUID().uuidString, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) let id = UUID().uuidString let comment1 = Comment(id: id, content: "This is a comment.", createdAt: createdAt, post: post1) let comment2 = Comment(id: id, content: "This is a comment.", createdAt: createdAt, post: post2) @@ -111,22 +123,26 @@ class ModelCompareTests: BaseDataStoreTests { let draft = false let rating = 4.0 let status = PostStatus.published - let post1 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) + let post1 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) // rating is nil - let post2 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: nil, - status: status) + let post2 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: nil, + status: status + ) XCTAssertFalse(Post.schema.compare(post1, post2)) } @@ -137,20 +153,24 @@ class ModelCompareTests: BaseDataStoreTests { let draft = false let rating = 4.0 let status = PostStatus.published - let post1 = Post(id: UUID().uuidString, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) - let post2 = Post(id: UUID().uuidString, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) + let post1 = Post( + id: UUID().uuidString, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) + let post2 = Post( + id: UUID().uuidString, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) XCTAssertFalse(Post.schema.compare(post1, post2)) } @@ -163,20 +183,24 @@ class ModelCompareTests: BaseDataStoreTests { let draft = false let rating = 4.0 let status = PostStatus.published - let post1 = Post(id: id, - title: title1, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) - let post2 = Post(id: id, - title: title2, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) + let post1 = Post( + id: id, + title: title1, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) + let post2 = Post( + id: id, + title: title2, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) XCTAssertFalse(Post.schema.compare(post1, post2)) } @@ -189,20 +213,24 @@ class ModelCompareTests: BaseDataStoreTests { let rating1 = 4.0 let rating2 = 1.0 let status = PostStatus.published - let post1 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating1, - status: status) - let post2 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating2, - status: status) + let post1 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating1, + status: status + ) + let post2 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating2, + status: status + ) XCTAssertFalse(Post.schema.compare(post1, post2)) } @@ -247,20 +275,24 @@ class ModelCompareTests: BaseDataStoreTests { let rating = 4.0 let status1 = PostStatus.published let status2 = PostStatus.draft - let post1 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status1) - let post2 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status2) + let post1 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status1 + ) + let post2 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status2 + ) XCTAssertFalse(Post.schema.compare(post1, post2)) } @@ -273,20 +305,24 @@ class ModelCompareTests: BaseDataStoreTests { let draft2 = true let rating = 4.0 let status = PostStatus.published - let post1 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft1, - rating: rating, - status: status) - let post2 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft2, - rating: rating, - status: status) + let post1 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft1, + rating: rating, + status: status + ) + let post2 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft2, + rating: rating, + status: status + ) XCTAssertFalse(Post.schema.compare(post1, post2)) } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventExtensionsTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventExtensionsTests.swift index 0add6aebd1..99a064d935 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventExtensionsTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventExtensionsTests.swift @@ -24,22 +24,28 @@ class MutationEventExtensionsTest: BaseDataStoreTests { func testSentModelWithNilVersion_Reconciled() async throws { let modelId = UUID().uuidString let post = Post(id: modelId, title: "title", content: "content", createdAt: .now()) - let requestMutationEvent = try createMutationEvent(model: post, - mutationType: .create, - createdAt: .now(), - version: nil, - inProcess: true) - let pendingMutationEvent = try createMutationEvent(model: post, - mutationType: .update, - createdAt: .now().add(value: 1, to: .second), - version: nil) + let requestMutationEvent = try createMutationEvent( + model: post, + mutationType: .create, + createdAt: .now(), + version: nil, + inProcess: true + ) + let pendingMutationEvent = try createMutationEvent( + model: post, + mutationType: .update, + createdAt: .now().add(value: 1, to: .second), + version: nil + ) let responseMutationSync = createMutationSync(model: post, version: 1) setUpPendingMutationQueue(post, [requestMutationEvent, pendingMutationEvent], pendingMutationEvent) - let reconciledEvent = MutationEvent.reconcile(pendingMutationEvent: pendingMutationEvent, - with: requestMutationEvent, - responseMutationSync: responseMutationSync) + let reconciledEvent = MutationEvent.reconcile( + pendingMutationEvent: pendingMutationEvent, + with: requestMutationEvent, + responseMutationSync: responseMutationSync + ) XCTAssertNotNil(reconciledEvent) XCTAssertEqual(reconciledEvent?.version, responseMutationSync.syncMetadata.version) @@ -47,9 +53,11 @@ class MutationEventExtensionsTest: BaseDataStoreTests { let updatingVersionExpectation = expectation(description: "update latest mutation event with response version") // update the version of head of mutation event table for given model id to the version of `mutationSync` - MutationEvent.reconcilePendingMutationEventsVersion(sent: requestMutationEvent, - received: responseMutationSync, - storageAdapter: storageAdapter) { result in + MutationEvent.reconcilePendingMutationEventsVersion( + sent: requestMutationEvent, + received: responseMutationSync, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -60,8 +68,10 @@ class MutationEventExtensionsTest: BaseDataStoreTests { await fulfillment(of: [updatingVersionExpectation], timeout: 1) // query for head of mutation event table for given model id and check if it has the updated version - MutationEvent.pendingMutationEvents(forModel: post, - storageAdapter: storageAdapter) { result in + MutationEvent.pendingMutationEvents( + forModel: post, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -88,28 +98,38 @@ class MutationEventExtensionsTest: BaseDataStoreTests { func testSentModelWithNilVersion_SecondPendingEventNotReconciled() async throws { let modelId = UUID().uuidString let post = Post(id: modelId, title: "title", content: "content", createdAt: .now()) - let requestMutationEvent = try createMutationEvent(model: post, - mutationType: .create, - createdAt: .now(), - version: nil, - inProcess: true) - let pendingUpdateMutationEvent = try createMutationEvent(model: post, - mutationType: .update, - createdAt: .now().add(value: 1, to: .second), - version: nil) - let pendingDeleteMutationEvent = try createMutationEvent(model: post, - mutationType: .delete, - createdAt: .now().add(value: 2, to: .second), - version: nil) + let requestMutationEvent = try createMutationEvent( + model: post, + mutationType: .create, + createdAt: .now(), + version: nil, + inProcess: true + ) + let pendingUpdateMutationEvent = try createMutationEvent( + model: post, + mutationType: .update, + createdAt: .now().add(value: 1, to: .second), + version: nil + ) + let pendingDeleteMutationEvent = try createMutationEvent( + model: post, + mutationType: .delete, + createdAt: .now().add(value: 2, to: .second), + version: nil + ) let responseMutationSync = createMutationSync(model: post, version: 1) - setUpPendingMutationQueue(post, - [requestMutationEvent, pendingUpdateMutationEvent, pendingDeleteMutationEvent], - pendingUpdateMutationEvent) - - let reconciledEvent = MutationEvent.reconcile(pendingMutationEvent: pendingUpdateMutationEvent, - with: requestMutationEvent, - responseMutationSync: responseMutationSync) + setUpPendingMutationQueue( + post, + [requestMutationEvent, pendingUpdateMutationEvent, pendingDeleteMutationEvent], + pendingUpdateMutationEvent + ) + + let reconciledEvent = MutationEvent.reconcile( + pendingMutationEvent: pendingUpdateMutationEvent, + with: requestMutationEvent, + responseMutationSync: responseMutationSync + ) XCTAssertNotNil(reconciledEvent) XCTAssertEqual(reconciledEvent?.version, responseMutationSync.syncMetadata.version) @@ -117,9 +137,11 @@ class MutationEventExtensionsTest: BaseDataStoreTests { let updatingVersionExpectation = expectation(description: "update latest mutation event with response version") // update the version of head of mutation event table for given model id to the version of `mutationSync` - MutationEvent.reconcilePendingMutationEventsVersion(sent: requestMutationEvent, - received: responseMutationSync, - storageAdapter: storageAdapter) { result in + MutationEvent.reconcilePendingMutationEventsVersion( + sent: requestMutationEvent, + received: responseMutationSync, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -130,8 +152,10 @@ class MutationEventExtensionsTest: BaseDataStoreTests { await fulfillment(of: [updatingVersionExpectation], timeout: 1) // query for head of mutation event table for given model id and check if it has the updated version - MutationEvent.pendingMutationEvents(forModel: post, - storageAdapter: storageAdapter) { result in + MutationEvent.pendingMutationEvents( + forModel: post, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -158,31 +182,39 @@ class MutationEventExtensionsTest: BaseDataStoreTests { let modelId = UUID().uuidString let post1 = Post(id: modelId, title: "title1", content: "content1", createdAt: .now()) let post2 = Post(id: modelId, title: "title2", content: "content2", createdAt: .now()) - let requestMutationEvent = try createMutationEvent(model: post1, - mutationType: .create, - createdAt: .now(), - version: 2, - inProcess: true) - let pendingMutationEvent = try createMutationEvent(model: post2, - mutationType: .update, - createdAt: .now().add(value: 1, to: .second), - version: 2) + let requestMutationEvent = try createMutationEvent( + model: post1, + mutationType: .create, + createdAt: .now(), + version: 2, + inProcess: true + ) + let pendingMutationEvent = try createMutationEvent( + model: post2, + mutationType: .update, + createdAt: .now().add(value: 1, to: .second), + version: 2 + ) let responseMutationSync = createMutationSync(model: post1, version: 1) setUpPendingMutationQueue(post1, [requestMutationEvent, pendingMutationEvent], pendingMutationEvent) - let reconciledEvent = MutationEvent.reconcile(pendingMutationEvent: pendingMutationEvent, - with: requestMutationEvent, - responseMutationSync: responseMutationSync) + let reconciledEvent = MutationEvent.reconcile( + pendingMutationEvent: pendingMutationEvent, + with: requestMutationEvent, + responseMutationSync: responseMutationSync + ) XCTAssertNil(reconciledEvent) let queryAfterUpdatingVersionExpectation = expectation(description: "update mutation should have version 2") let updatingVersionExpectation = expectation(description: "don't update latest mutation event with response version") - MutationEvent.reconcilePendingMutationEventsVersion(sent: requestMutationEvent, - received: responseMutationSync, - storageAdapter: storageAdapter) { result in + MutationEvent.reconcilePendingMutationEventsVersion( + sent: requestMutationEvent, + received: responseMutationSync, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -193,8 +225,10 @@ class MutationEventExtensionsTest: BaseDataStoreTests { await fulfillment(of: [updatingVersionExpectation], timeout: 1) // query for head of mutation event table for given model id and check if it has the correct version - MutationEvent.pendingMutationEvents(forModel: post1, - storageAdapter: storageAdapter) { result in + MutationEvent.pendingMutationEvents( + forModel: post1, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -221,31 +255,39 @@ class MutationEventExtensionsTest: BaseDataStoreTests { let post1 = Post(id: modelId, title: "title1", content: "content1", createdAt: .now()) let post2 = Post(id: modelId, title: "title2", content: "content2", createdAt: .now()) let post3 = Post(id: modelId, title: "title3", content: "content3", createdAt: .now()) - let requestMutationEvent = try createMutationEvent(model: post1, - mutationType: .update, - createdAt: .now(), - version: 1, - inProcess: true) - let pendingMutationEvent = try createMutationEvent(model: post2, - mutationType: .update, - createdAt: .now().add(value: 1, to: .second), - version: 1) + let requestMutationEvent = try createMutationEvent( + model: post1, + mutationType: .update, + createdAt: .now(), + version: 1, + inProcess: true + ) + let pendingMutationEvent = try createMutationEvent( + model: post2, + mutationType: .update, + createdAt: .now().add(value: 1, to: .second), + version: 1 + ) let responseMutationSync = createMutationSync(model: post3, version: 2) setUpPendingMutationQueue(post1, [requestMutationEvent, pendingMutationEvent], pendingMutationEvent) - let reconciledEvent = MutationEvent.reconcile(pendingMutationEvent: pendingMutationEvent, - with: requestMutationEvent, - responseMutationSync: responseMutationSync) + let reconciledEvent = MutationEvent.reconcile( + pendingMutationEvent: pendingMutationEvent, + with: requestMutationEvent, + responseMutationSync: responseMutationSync + ) XCTAssertNil(reconciledEvent) let queryAfterUpdatingVersionExpectation = expectation(description: "update mutation should have version 1") let updatingVersionExpectation = expectation(description: "don't update latest mutation event with response version") - MutationEvent.reconcilePendingMutationEventsVersion(sent: requestMutationEvent, - received: responseMutationSync, - storageAdapter: storageAdapter) { result in + MutationEvent.reconcilePendingMutationEventsVersion( + sent: requestMutationEvent, + received: responseMutationSync, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -256,8 +298,10 @@ class MutationEventExtensionsTest: BaseDataStoreTests { await fulfillment(of: [updatingVersionExpectation], timeout: 1) // query for head of mutation event table for given model id and check if it has the correct version - MutationEvent.pendingMutationEvents(forModel: post1, - storageAdapter: storageAdapter) { result in + MutationEvent.pendingMutationEvents( + forModel: post1, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -283,31 +327,39 @@ class MutationEventExtensionsTest: BaseDataStoreTests { let modelId = UUID().uuidString let post1 = Post(id: modelId, title: "title1", content: "content1", createdAt: .now()) let post2 = Post(id: modelId, title: "title2", content: "content2", createdAt: .now()) - let requestMutationEvent = try createMutationEvent(model: post1, - mutationType: .update, - createdAt: .now(), - version: 1, - inProcess: true) - let pendingMutationEvent = try createMutationEvent(model: post2, - mutationType: .update, - createdAt: .now().add(value: 1, to: .second), - version: 1) + let requestMutationEvent = try createMutationEvent( + model: post1, + mutationType: .update, + createdAt: .now(), + version: 1, + inProcess: true + ) + let pendingMutationEvent = try createMutationEvent( + model: post2, + mutationType: .update, + createdAt: .now().add(value: 1, to: .second), + version: 1 + ) let responseMutationSync = createMutationSync(model: post1, version: 2) setUpPendingMutationQueue(post1, [requestMutationEvent, pendingMutationEvent], pendingMutationEvent) - let reconciledEvent = MutationEvent.reconcile(pendingMutationEvent: pendingMutationEvent, - with: requestMutationEvent, - responseMutationSync: responseMutationSync) + let reconciledEvent = MutationEvent.reconcile( + pendingMutationEvent: pendingMutationEvent, + with: requestMutationEvent, + responseMutationSync: responseMutationSync + ) XCTAssertNotNil(reconciledEvent) XCTAssertEqual(reconciledEvent?.version, responseMutationSync.syncMetadata.version) let queryAfterUpdatingVersionExpectation = expectation(description: "update mutation should have version 2") let updatingVersionExpectation = expectation(description: "update latest mutation event with response version") - MutationEvent.reconcilePendingMutationEventsVersion(sent: requestMutationEvent, - received: responseMutationSync, - storageAdapter: storageAdapter) { result in + MutationEvent.reconcilePendingMutationEventsVersion( + sent: requestMutationEvent, + received: responseMutationSync, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -318,8 +370,10 @@ class MutationEventExtensionsTest: BaseDataStoreTests { await fulfillment(of: [updatingVersionExpectation], timeout: 1) // query for head of mutation event table for given model id and check if it has the correct version - MutationEvent.pendingMutationEvents(forModel: post1, - storageAdapter: storageAdapter) { result in + MutationEvent.pendingMutationEvents( + forModel: post1, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -336,33 +390,41 @@ class MutationEventExtensionsTest: BaseDataStoreTests { await fulfillment(of: [queryAfterUpdatingVersionExpectation], timeout: 1) } - private func createMutationEvent(model: Model, - mutationType: MutationEvent.MutationType, - createdAt: Temporal.DateTime, - version: Int? = nil, - inProcess: Bool = false) throws -> MutationEvent { - return MutationEvent(id: UUID().uuidString, - modelId: model.identifier(schema: MutationEvent.schema).stringValue, - modelName: model.modelName, - json: try model.toJSON(), - mutationType: mutationType, - createdAt: createdAt, - version: version, - inProcess: inProcess) + private func createMutationEvent( + model: Model, + mutationType: MutationEvent.MutationType, + createdAt: Temporal.DateTime, + version: Int? = nil, + inProcess: Bool = false + ) throws -> MutationEvent { + return try MutationEvent( + id: UUID().uuidString, + modelId: model.identifier(schema: MutationEvent.schema).stringValue, + modelName: model.modelName, + json: model.toJSON(), + mutationType: mutationType, + createdAt: createdAt, + version: version, + inProcess: inProcess + ) } private func createMutationSync(model: Model, version: Int = 1) -> MutationSync { - let metadata = MutationSyncMetadata(modelId: model.identifier(schema: MutationEvent.schema).stringValue, - modelName: model.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: version) + let metadata = MutationSyncMetadata( + modelId: model.identifier(schema: MutationEvent.schema).stringValue, + modelName: model.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: version + ) return MutationSync(model: AnyModel(model), syncMetadata: metadata) } - private func setUpPendingMutationQueue(_ model: Model, - _ mutationEvents: [MutationEvent], - _ expectedHeadOfQueue: MutationEvent) { + private func setUpPendingMutationQueue( + _ model: Model, + _ mutationEvents: [MutationEvent], + _ expectedHeadOfQueue: MutationEvent + ) { for mutationEvent in mutationEvents { let mutationEventSaveExpectation = expectation(description: "save mutation event success") storageAdapter.save(mutationEvent) { result in diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/BaseDataStoreTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/BaseDataStoreTests.swift index 2d91bccd89..d8a882c8ad 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/BaseDataStoreTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/BaseDataStoreTests.swift @@ -35,13 +35,17 @@ class BaseDataStoreTests: XCTestCase { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) - let syncEngine = try RemoteSyncEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault()) - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let syncEngine = try RemoteSyncEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault() + ) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) } catch { XCTFail(String(describing: error)) return @@ -50,11 +54,13 @@ class BaseDataStoreTests: XCTestCase { return self.storageEngine } let dataStorePublisher = DataStorePublisher() - dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/LocalStoreIntegrationTestBase.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/LocalStoreIntegrationTestBase.swift index 217db3315e..8eaaf9703c 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/LocalStoreIntegrationTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/LocalStoreIntegrationTestBase.swift @@ -15,15 +15,17 @@ class LocalStoreIntegrationTestBase: XCTestCase { override func setUp() async throws { await Amplify.reset() } - + func setUp(withModels models: AmplifyModelRegistration) { continueAfterFailure = false do { #if os(watchOS) - try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, - configuration: .subscriptionsDisabled)) + try Amplify.add(plugin: AWSDataStorePlugin( + modelRegistration: models, + configuration: .subscriptionsDisabled + )) #else try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models)) #endif @@ -36,7 +38,7 @@ class LocalStoreIntegrationTestBase: XCTestCase { override func tearDown() async throws { let clearComplete = expectation(description: "clear completed") - + Task { try await Amplify.DataStore.clear() clearComplete.fulfill() diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSIncomingEventReconciliationQueue.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSIncomingEventReconciliationQueue.swift index 05b5750b8a..e165686fe0 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSIncomingEventReconciliationQueue.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSIncomingEventReconciliationQueue.swift @@ -14,11 +14,13 @@ import Combine class MockAWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueue { static let factory: IncomingEventReconciliationQueueFactory = { modelSchemas, api, storageAdapter, syncExpressions, auth, _, _, _ in - MockAWSIncomingEventReconciliationQueue(modelSchemas: modelSchemas, - api: api, - storageAdapter: storageAdapter, - syncExpressions: syncExpressions, - auth: auth) + MockAWSIncomingEventReconciliationQueue( + modelSchemas: modelSchemas, + api: api, + storageAdapter: storageAdapter, + syncExpressions: syncExpressions, + auth: auth + ) } let incomingEventSubject: PassthroughSubject var publisher: AnyPublisher { @@ -26,11 +28,13 @@ class MockAWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueue } static var lastInstance = AtomicValue(initialValue: nil) - init(modelSchemas: [ModelSchema], - api: APICategoryGraphQLBehavior?, - storageAdapter: StorageEngineAdapter?, - syncExpressions: [DataStoreSyncExpression], - auth: AuthCategoryBehavior?) { + init( + modelSchemas: [ModelSchema], + api: APICategoryGraphQLBehavior?, + storageAdapter: StorageEngineAdapter?, + syncExpressions: [DataStoreSyncExpression], + auth: AuthCategoryBehavior? + ) { self.incomingEventSubject = PassthroughSubject() updateLastInstance(instance: self) } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSInitialSyncOrchestrator.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSInitialSyncOrchestrator.swift index 665938ce29..8954545c93 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSInitialSyncOrchestrator.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSInitialSyncOrchestrator.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore import Combine +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -16,10 +16,12 @@ import Combine class MockAWSInitialSyncOrchestrator: InitialSyncOrchestrator { static let factory: InitialSyncOrchestratorFactory = { dataStoreConfiguration, _, api, reconciliationQueue, storageAdapter in - MockAWSInitialSyncOrchestrator(dataStoreConfiguration: dataStoreConfiguration, - api: api, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) + MockAWSInitialSyncOrchestrator( + dataStoreConfiguration: dataStoreConfiguration, + api: api, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) } typealias SyncOperationResult = Result @@ -33,10 +35,12 @@ class MockAWSInitialSyncOrchestrator: InitialSyncOrchestrator { return initialSyncOrchestratorTopic.eraseToAnyPublisher() } - init(dataStoreConfiguration: DataStoreConfiguration, - api: APICategoryGraphQLBehavior?, - reconciliationQueue: IncomingEventReconciliationQueue?, - storageAdapter: StorageEngineAdapter?) { + init( + dataStoreConfiguration: DataStoreConfiguration, + api: APICategoryGraphQLBehavior?, + reconciliationQueue: IncomingEventReconciliationQueue?, + storageAdapter: StorageEngineAdapter? + ) { self.initialSyncOrchestratorTopic = PassthroughSubject() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockFileManager.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockFileManager.swift index 50b4903aa7..bcf65bf1b4 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockFileManager.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockFileManager.swift @@ -24,7 +24,7 @@ class MockFileManager: FileManager { if hasError { throw MockFileManagerError.removeItemError } - if let removeItem = removeItem { + if let removeItem { removeItem(URL) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockOutgoingMutationQueue.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockOutgoingMutationQueue.swift index e0223bac2b..105b8c8f04 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockOutgoingMutationQueue.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockOutgoingMutationQueue.swift @@ -17,9 +17,11 @@ class MockOutgoingMutationQueue: OutgoingMutationQueueBehavior { completion() } - func startSyncingToCloud(api: APICategoryGraphQLBehavior, - mutationEventPublisher: MutationEventPublisher, - reconciliationQueue: IncomingEventReconciliationQueue?) { + func startSyncingToCloud( + api: APICategoryGraphQLBehavior, + mutationEventPublisher: MutationEventPublisher, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { // no-op } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRemoteSyncEngine.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRemoteSyncEngine.swift index 1f2036784e..a3d9facc25 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRemoteSyncEngine.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRemoteSyncEngine.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore import Combine +import Foundation @testable import Amplify @testable import AmplifyTestCommon diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRequestRetryablePolicy.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRequestRetryablePolicy.swift index d8db743605..9f07e23116 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRequestRetryablePolicy.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRequestRetryablePolicy.swift @@ -9,8 +9,8 @@ import Foundation @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class MockRequestRetryablePolicy: RequestRetryablePolicy { @@ -25,9 +25,11 @@ class MockRequestRetryablePolicy: RequestRetryablePolicy { self.onRetryRequestAdvice = onRetryRequestAdvice } - override func retryRequestAdvice(urlError: URLError?, - httpURLResponse: HTTPURLResponse?, - attemptNumber: Int) -> RequestRetryAdvice { + override func retryRequestAdvice( + urlError: URLError?, + httpURLResponse: HTTPURLResponse?, + attemptNumber: Int + ) -> RequestRetryAdvice { onRetryRequestAdvice?(urlError, httpURLResponse, attemptNumber) // If this breaks, you didn't push anything onto the queue return !responseQueue.isEmpty ? responseQueue.removeFirst() : .init(shouldRetry: false) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockStateMachine.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockStateMachine.swift index c663505694..d975194840 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockStateMachine.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockStateMachine.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation @testable import AWSDataStorePlugin class MockStateMachine: StateMachine { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/NoOpMutationQueue.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/NoOpMutationQueue.swift index 82c9b031af..d6a85e624c 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/NoOpMutationQueue.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/NoOpMutationQueue.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import Amplify -@testable import AWSDataStorePlugin import AWSPluginsCore import Combine +@testable import Amplify +@testable import AWSDataStorePlugin /// A mutation queue that takes no action on either pause or start, to let these unit tests operate on the /// mutation queue without interference from the mutation queue polling for events and marking them in-process. @@ -17,9 +17,11 @@ class NoOpMutationQueue: OutgoingMutationQueueBehavior { completion() } - func startSyncingToCloud(api: APICategoryGraphQLBehavior, - mutationEventPublisher: MutationEventPublisher, - reconciliationQueue: IncomingEventReconciliationQueue?) { + func startSyncingToCloud( + api: APICategoryGraphQLBehavior, + mutationEventPublisher: MutationEventPublisher, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { // do nothing } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/TestModelRegistration.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/TestModelRegistration.swift index 27e60a7ff2..21ca7256dc 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/TestModelRegistration.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/TestModelRegistration.swift @@ -50,25 +50,33 @@ struct TestJsonModelRegistration: AmplifyModelRegistration { let draft = ModelField(name: "draft", type: .bool, isRequired: false) let rating = ModelField(name: "rating", type: .double, isRequired: false) let status = ModelField(name: "status", type: .string, isRequired: false) - let comments = ModelField(name: "comments", - type: .collection(of: "Comment"), - isRequired: false, - association: .hasMany(associatedFieldName: "post")) - let postSchema = ModelSchema(name: "Post", - listPluralName: "Posts", - syncPluralName: "Posts", - fields: [id.name: id, - title.name: title, - content.name: content, - createdAt.name: createdAt, - updatedAt.name: updatedAt, - draft.name: draft, - rating.name: rating, - status.name: status, - comments.name: comments]) - - ModelRegistry.register(modelType: DynamicModel.self, - modelSchema: postSchema) { (jsonString, decoder) -> Model in + let comments = ModelField( + name: "comments", + type: .collection(of: "Comment"), + isRequired: false, + association: .hasMany(associatedFieldName: "post") + ) + let postSchema = ModelSchema( + name: "Post", + listPluralName: "Posts", + syncPluralName: "Posts", + fields: [ + id.name: id, + title.name: title, + content.name: content, + createdAt.name: createdAt, + updatedAt.name: updatedAt, + draft.name: draft, + rating.name: rating, + status.name: status, + comments.name: comments + ] + ) + + ModelRegistry.register( + modelType: DynamicModel.self, + modelSchema: postSchema + ) { jsonString, decoder -> Model in try DynamicModel.from(json: jsonString, decoder: decoder) } @@ -77,20 +85,27 @@ struct TestJsonModelRegistration: AmplifyModelRegistration { let commentId = ModelFieldDefinition.id().modelField let commentContent = ModelField(name: "content", type: .string, isRequired: true) let commentCreatedAt = ModelField(name: "createdAt", type: .dateTime, isRequired: true) - let belongsTo = ModelField(name: "post", - type: .model(name: "Post"), - isRequired: true, - association: .belongsTo(associatedWith: nil, targetNames: ["postId"])) - let commentSchema = ModelSchema(name: "Comment", - listPluralName: "Comments", - syncPluralName: "Comments", - fields: [ - commentId.name: commentId, - commentContent.name: commentContent, - commentCreatedAt.name: commentCreatedAt, - belongsTo.name: belongsTo]) - ModelRegistry.register(modelType: DynamicModel.self, - modelSchema: commentSchema) { (jsonString, decoder) -> Model in + let belongsTo = ModelField( + name: "post", + type: .model(name: "Post"), + isRequired: true, + association: .belongsTo(associatedWith: nil, targetNames: ["postId"]) + ) + let commentSchema = ModelSchema( + name: "Comment", + listPluralName: "Comments", + syncPluralName: "Comments", + fields: [ + commentId.name: commentId, + commentContent.name: commentContent, + commentCreatedAt.name: commentCreatedAt, + belongsTo.name: belongsTo + ] + ) + ModelRegistry.register( + modelType: DynamicModel.self, + modelSchema: commentSchema + ) { jsonString, decoder -> Model in try DynamicModel.from(json: jsonString, decoder: decoder) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/SyncEngineTestBase.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/SyncEngineTestBase.swift index d86b8ba8a4..9967b65333 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/SyncEngineTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/SyncEngineTestBase.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import SQLite import XCTest -import Combine @testable import Amplify -@testable import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSDataStorePlugin +@testable import AWSPluginsCore /// Base class for SyncEngine and sync-enabled DataStore tests class SyncEngineTestBase: XCTestCase { @@ -38,7 +38,7 @@ class SyncEngineTestBase: XCTestCase { var remoteSyncEngineSink: AnyCancellable! var requestRetryablePolicy: MockRequestRetryablePolicy! - + var token: UnsubscribeToken! // MARK: - Setup @@ -64,7 +64,7 @@ class SyncEngineTestBase: XCTestCase { amplifyConfig = AmplifyConfiguration(api: apiConfig, auth: authConfig, dataStore: dataStoreConfig) - if let reachabilityPublisher = reachabilityPublisher { + if let reachabilityPublisher { apiPlugin = MockAPICategoryPlugin( reachabilityPublisher: reachabilityPublisher ) @@ -76,7 +76,7 @@ class SyncEngineTestBase: XCTestCase { try Amplify.add(plugin: apiPlugin) try Amplify.add(plugin: authPlugin) } - + override func tearDown() async throws { amplifyConfig = nil apiPlugin = nil @@ -102,7 +102,7 @@ class SyncEngineTestBase: XCTestCase { ) throws { models.forEach { ModelRegistry.register(modelType: $0) } let resolvedConnection: Connection - if let connection = connection { + if let connection { resolvedConnection = connection } else { resolvedConnection = try Connection(.inMemory) @@ -122,24 +122,29 @@ class SyncEngineTestBase: XCTestCase { ) throws { let mutationDatabaseAdapter = try AWSMutationDatabaseAdapter(storageAdapter: storageAdapter) let awsMutationEventPublisher = AWSMutationEventPublisher(eventSource: mutationDatabaseAdapter) - stateMachine = StateMachine(initialState: .notStarted, - resolver: RemoteSyncEngine.Resolver.resolve(currentState:action:)) - - syncEngine = RemoteSyncEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - outgoingMutationQueue: mutationQueue, - mutationEventIngester: mutationDatabaseAdapter, - mutationEventPublisher: awsMutationEventPublisher, - initialSyncOrchestratorFactory: initialSyncOrchestratorFactory, - reconciliationQueueFactory: MockAWSIncomingEventReconciliationQueue.factory, - stateMachine: stateMachine, - networkReachabilityPublisher: reachabilityPublisher, - requestRetryablePolicy: requestRetryablePolicy) + stateMachine = StateMachine( + initialState: .notStarted, + resolver: RemoteSyncEngine.Resolver.resolve(currentState:action:) + ) + + syncEngine = RemoteSyncEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + outgoingMutationQueue: mutationQueue, + mutationEventIngester: mutationDatabaseAdapter, + mutationEventPublisher: awsMutationEventPublisher, + initialSyncOrchestratorFactory: initialSyncOrchestratorFactory, + reconciliationQueueFactory: MockAWSIncomingEventReconciliationQueue.factory, + stateMachine: stateMachine, + networkReachabilityPublisher: reachabilityPublisher, + requestRetryablePolicy: requestRetryablePolicy + ) remoteSyncEngineSink = syncEngine .publisher - .sink(receiveCompletion: {_ in }, - receiveValue: { (event: RemoteSyncEngineEvent) in + .sink( + receiveCompletion: {_ in }, + receiveValue: { (event: RemoteSyncEngineEvent) in switch event { case .mutationsPaused: // Assume AWSIncomingEventReconciliationQueue succeeds in establishing connections @@ -149,25 +154,30 @@ class SyncEngineTestBase: XCTestCase { default: break } - }) + } + ) let validAPIPluginKey = "MockAPICategoryPlugin" let validAuthPluginKey = "MockAuthCategoryPlugin" - let storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let storageEngineBehaviorFactory: StorageEngineBehaviorFactory = {_, _, _, _, _, _ throws in return storageEngine } let publisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: modelRegistration, - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: publisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: modelRegistration, + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: publisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) try Amplify.add(plugin: dataStorePlugin) } @@ -177,10 +187,10 @@ class SyncEngineTestBase: XCTestCase { try Amplify.configure(amplifyConfig) try await Amplify.DataStore.start() } - + /// Starts amplify by invoking `Amplify.configure(amplifyConfig)`, and waits to receive a `syncStarted` Hub message /// before returning. - private func startAmplifyAndWaitForSync(completion: @escaping (Swift.Result)->Void) { + private func startAmplifyAndWaitForSync(completion: @escaping (Swift.Result) -> Void) { token = Amplify.Hub.listen(to: .dataStore) { [weak self] payload in if payload.eventName == "DataStore.syncStarted" { if let token = self?.token { @@ -189,14 +199,14 @@ class SyncEngineTestBase: XCTestCase { } } } - - + + Task { guard try await HubListenerTestUtilities.waitForListener(with: token, timeout: 5.0) else { XCTFail("Never registered listener for sync started") return } - + do { try await startAmplify() } catch { @@ -204,7 +214,7 @@ class SyncEngineTestBase: XCTestCase { completion(.failure(error)) } } - + } /// Starts amplify by invoking `Amplify.configure(amplifyConfig)`, and waits to receive a `syncStarted` Hub message @@ -216,20 +226,24 @@ class SyncEngineTestBase: XCTestCase { } } } - + // MARK: - Data methods /// Saves a mutation event directly to StorageAdapter. Used for pre-populating database before tests - func saveMutationEvent(of mutationType: MutationEvent.MutationType, - for post: Post, - inProcess: Bool = false) throws { - let mutationEvent = try MutationEvent(id: SyncEngineTestBase.mutationEventId(for: post), - modelId: post.id, - modelName: post.modelName, - json: post.toJSON(), - mutationType: mutationType, - createdAt: .now(), - inProcess: inProcess) + func saveMutationEvent( + of mutationType: MutationEvent.MutationType, + for post: Post, + inProcess: Bool = false + ) throws { + let mutationEvent = try MutationEvent( + id: SyncEngineTestBase.mutationEventId(for: post), + modelId: post.id, + modelName: post.modelName, + json: post.toJSON(), + mutationType: mutationType, + createdAt: .now(), + inProcess: inProcess + ) let mutationEventSaved = expectation(description: "Preloaded mutation event saved") storageAdapter.save(mutationEvent) { result in diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreAuthBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreAuthBaseTest.swift index 13e860d851..0ca4e79566 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreAuthBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreAuthBaseTest.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import XCTest -import Combine -import AWSDataStorePlugin -import AWSPluginsCore import AWSAPIPlugin import AWSCognitoAuthPlugin +import AWSDataStorePlugin +import AWSPluginsCore +import Combine +import Foundation +import XCTest #if !os(watchOS) @testable import DataStoreHostApp #endif @@ -24,7 +24,7 @@ struct TestUser { } class AuthRecorderInterceptor: URLRequestInterceptor { - let awsAuthService: AWSAuthService = AWSAuthService() + let awsAuthService: AWSAuthService = .init() var consumedAuthTypes: Set = [] private let accessQueue = DispatchQueue(label: "com.amazon.AuthRecorderInterceptor.consumedAuthTypes") @@ -46,13 +46,13 @@ class AuthRecorderInterceptor: URLRequestInterceptor { recordAuthType(.apiKey) } - if let authHeaderValue = authHeaderValue, + if let authHeaderValue, case let .success(claims) = awsAuthService.getTokenClaims(tokenString: authHeaderValue), let cognitoIss = claims["iss"] as? String, cognitoIss.contains("cognito") { recordAuthType(.amazonCognitoUserPools) } - if let authHeaderValue = authHeaderValue, + if let authHeaderValue, authHeaderValue.starts(with: "AWS4-HMAC-SHA256") { recordAuthType(.awsIAM) } @@ -128,7 +128,8 @@ class AWSDataStoreAuthBaseTest: XCTestCase { guard let user1 = credentials["user1"], let user2 = credentials["user2"], let passwordUser1 = credentials["passwordUser1"], - let passwordUser2 = credentials["passwordUser2"] else { + let passwordUser2 = credentials["passwordUser2"] + else { XCTFail("Invalid \(credentialsFile).json data") return } @@ -148,7 +149,8 @@ class AWSDataStoreAuthBaseTest: XCTestCase { func apiEndpointName() throws -> String { guard let apiPlugin = amplifyConfig.api?.plugins["awsAPIPlugin"], - case .object(let value) = apiPlugin else { + case .object(let value) = apiPlugin + else { throw APIError.invalidConfiguration("API endpoint not found.", "Check the provided configuration") } return value.keys.first! @@ -176,8 +178,10 @@ class AWSDataStoreAuthBaseTest: XCTestCase { authModeStrategy: testType.authStrategy ) #endif - try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, - configuration: datastoreConfig)) + try Amplify.add(plugin: AWSDataStorePlugin( + modelRegistration: models, + configuration: datastoreConfig + )) let apiPlugin = apiPluginFactory() @@ -207,16 +211,21 @@ class AWSDataStoreAuthBaseTest: XCTestCase { extension AWSDataStoreAuthBaseTest { /// Signin given user /// - Parameter user - func signIn(user: TestUser?, - file: StaticString = #file, - line: UInt = #line) async throws { - guard let user = user else { + func signIn( + user: TestUser?, + file: StaticString = #file, + line: UInt = #line + ) async throws { + guard let user else { XCTFail("Invalid user", file: file, line: line) return } do { - let response = try await Amplify.Auth.signIn(username: user.username, - password: user.password, options: nil) + let response = try await Amplify.Auth.signIn( + username: user.username, + password: user.password, + options: nil + ) print("received response for signIn \(response)") let isSignedIn = try await isSignedIn() XCTAssert(isSignedIn) @@ -227,8 +236,10 @@ extension AWSDataStoreAuthBaseTest { } /// Signout current signed-in user - func signOut(file: StaticString = #file, - line: UInt = #line) async throws { + func signOut( + file: StaticString = #file, + line: UInt = #line + ) async throws { do { _ = await Amplify.Auth.signOut() print("signOut successfull") @@ -249,7 +260,7 @@ extension AWSDataStoreAuthBaseTest { throw error } } - + func getUserSub() async throws -> String { do { let authSession = try await Amplify.Auth.fetchAuthSession() @@ -264,7 +275,7 @@ extension AWSDataStoreAuthBaseTest { throw error } } - + func getIdentityId() async throws -> String! { do { let authSession = try await Amplify.Auth.fetchAuthSession() @@ -280,10 +291,12 @@ extension AWSDataStoreAuthBaseTest { } } - func queryModel(_ model: M.Type, - byId id: String, - file: StaticString = #file, - line: UInt = #line) async throws -> M? { + func queryModel( + _ model: M.Type, + byId id: String, + file: StaticString = #file, + line: UInt = #line + ) async throws -> M? { return try await Amplify.DataStore.query(M.self, byId: id) } } @@ -295,9 +308,11 @@ extension AWSDataStoreAuthBaseTest { /// - modelType: model type /// - expectation: success XCTestExpectation /// - onFailure: on failure callback - func assertQuerySuccess(modelType: M.Type, - _ expectations: AuthTestExpectations, - onFailure: @escaping (_ error: DataStoreError) -> Void) async throws { + func assertQuerySuccess( + modelType: (some Model).Type, + _ expectations: AuthTestExpectations, + onFailure: @escaping (_ error: DataStoreError) -> Void + ) async throws { Task { do { let posts = try await Amplify.DataStore.query(modelType) @@ -309,7 +324,7 @@ extension AWSDataStoreAuthBaseTest { } await fulfillment(of: [expectations.query], timeout: 60) } - + /// Asserts that DataStore is in a ready state and subscriptions are established /// - Parameter events: DataStore Hub events func assertDataStoreReady( @@ -334,28 +349,32 @@ extension AWSDataStoreAuthBaseTest { expectations.modelsSynced.fulfill() } } - + if event.eventName == dataStoreEvents.ready { expectations.ready.fulfill() } } .store(in: &requests) - + try await Amplify.DataStore.start() - - await fulfillment(of: [expectations.subscriptionsEstablished, - expectations.modelsSynced, - expectations.ready], - timeout: 60) + + await fulfillment( + of: [ + expectations.subscriptionsEstablished, + expectations.modelsSynced, + expectations.ready + ], + timeout: 60 + ) } - + /// Assert that a save and a delete mutation complete successfully. /// - Parameters: /// - model: model instance saved and then deleted /// - expectations: test expectations /// - onFailure: failure callback - func assertMutations( - model: M, + func assertMutations( + model: some Model, _ expectations: AuthTestExpectations, onFailure: @escaping (_ error: DataStoreError) -> Void ) async throws { @@ -366,7 +385,8 @@ extension AWSDataStoreAuthBaseTest { .filter { $0.eventName == HubPayload.EventName.DataStore.syncReceived } .sink { payload in guard let mutationEvent = payload.data as? MutationEvent, - mutationEvent.modelId == model.identifier else { + mutationEvent.modelId == model.identifier + else { return } @@ -390,8 +410,10 @@ extension AWSDataStoreAuthBaseTest { onFailure(error) } } - await fulfillment(of: [expectations.mutationSave, - expectations.mutationSaveProcessed], timeout: 60) + await fulfillment(of: [ + expectations.mutationSave, + expectations.mutationSaveProcessed + ], timeout: 60) Task { do { let deletedposts: () = try await Amplify.DataStore.delete(model) @@ -401,17 +423,23 @@ extension AWSDataStoreAuthBaseTest { onFailure(error) } } - await fulfillment(of: [expectations.mutationDelete, - expectations.mutationDeleteProcessed], timeout: 60) + await fulfillment(of: [ + expectations.mutationDelete, + expectations.mutationDeleteProcessed + ], timeout: 60) } - func assertUsedAuthTypes(_ authTypes: [AWSAuthorizationType], - file: StaticString = #file, - line: UInt = #line) { - XCTAssertEqual(authRecorderInterceptor.consumedAuthTypes, - Set(authTypes), - file: file, - line: line) + func assertUsedAuthTypes( + _ authTypes: [AWSAuthorizationType], + file: StaticString = #file, + line: UInt = #line + ) { + XCTAssertEqual( + authRecorderInterceptor.consumedAuthTypes, + Set(authTypes), + file: file, + line: line + ) } } @@ -427,11 +455,12 @@ extension AWSDataStoreAuthBaseTest { var mutationDeleteProcessed: XCTestExpectation var ready: XCTestExpectation var expectations: [XCTestExpectation] { - return [subscriptionsEstablished, - modelsSynced, - query, - mutationSave, - mutationSaveProcessed + return [ + subscriptionsEstablished, + modelsSynced, + query, + mutationSave, + mutationSaveProcessed ] } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests+Support.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests+Support.swift index b2292f96ed..5343425336 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests+Support.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests+Support.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import AWSPluginsCore import Amplify +import AWSPluginsCore +import XCTest #if !os(watchOS) import DataStoreHostApp #endif extension AWSDataStoreCategoryPluginAuthIntegrationTests { - func saveModel(_ model: T) async throws { + func saveModel(_ model: some Model) async throws { let localSaveInvoked = expectation(description: "local model was saved") Task { do { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests.swift index 948a417295..70515e9d5b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSDataStorePlugin +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp @@ -44,7 +44,8 @@ class AWSDataStoreCategoryPluginAuthIntegrationTests: AWSDataStoreAuthBaseTest { var remoteTodoOptional: TodoExplicitOwnerField? let syncReceivedListener = Amplify.Hub.listen(to: .dataStore, eventName: syncReceived) { payload in guard let mutationEvent = payload.data as? MutationEvent, - let todo = try? mutationEvent.decodeModel() as? TodoExplicitOwnerField else { + let todo = try? mutationEvent.decodeModel() as? TodoExplicitOwnerField + else { print("Can't cast payload as mutation event") return } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthOwnerIntegrationTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthOwnerIntegrationTests.swift index aef8908f97..71b33a62c9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthOwnerIntegrationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthOwnerIntegrationTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore +import XCTest @testable import Amplify class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseTest { @@ -16,8 +16,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT /// Then: DataStore is successfully initialized, query returns a result, /// mutation is processed for an authenticated users func testImplicitCustomOwner() async throws { - try await setup(withModels: CustomOwnerImplicitModelRegistration(), - testType: .defaultAuthCognito) + try await setup( + withModels: CustomOwnerImplicitModelRegistration(), + testType: .defaultAuthCognito + ) try await signIn(user: user1) @@ -26,8 +28,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT try await assertDataStoreReady(expectations) // Query - try await assertQuerySuccess(modelType: TodoCustomOwnerImplicit.self, - expectations) { error in + try await assertQuerySuccess( + modelType: TodoCustomOwnerImplicit.self, + expectations + ) { error in XCTFail("Error query \(error)") } @@ -46,8 +50,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT /// Then: DataStore is successfully initialized, query returns a result, /// mutation is processed for an authenticated users func testExplicitCustomOwner() async throws { - try await setup(withModels: CustomOwnerExplicitModelRegistration(), - testType: .defaultAuthCognito) + try await setup( + withModels: CustomOwnerExplicitModelRegistration(), + testType: .defaultAuthCognito + ) try await signIn(user: user1) @@ -56,8 +62,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT try await assertDataStoreReady(expectations) // Query - try await assertQuerySuccess(modelType: TodoCustomOwnerExplicit.self, - expectations) { error in + try await assertQuerySuccess( + modelType: TodoCustomOwnerExplicit.self, + expectations + ) { error in XCTFail("Error query \(error)") } @@ -76,8 +84,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT /// Then: DataStore is successfully initialized, query returns a result, /// mutation is processed for an authenticated users func testExplicitOwner() async throws { - try await setup(withModels: ExplicitOwnerModelRegistration(), - testType: .defaultAuthCognito) + try await setup( + withModels: ExplicitOwnerModelRegistration(), + testType: .defaultAuthCognito + ) try await signIn(user: user1) @@ -86,60 +96,68 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT try await assertDataStoreReady(expectations) // Query - try await assertQuerySuccess(modelType: TodoExplicitOwnerField.self, - expectations) { error in + try await assertQuerySuccess( + modelType: TodoExplicitOwnerField.self, + expectations + ) { error in XCTFail("Error query \(error)") } let todo = TodoExplicitOwnerField(content: "content") - + // Mutations try await assertMutations(model: todo, expectations) { error in XCTFail("Error mutation \(error)") } - + assertUsedAuthTypes([.amazonCognitoUserPools]) } - + /// Given: a user signed in with CognitoUserPools, a model with multiple rules with /// explicit owner field /// When: DataStore query/mutation operations are sent with CognitoUserPools /// Then: DataStore is successfully initialized, query returns a result, /// mutation is processed for an authenticated users func testExplicitMultipleOwner() async throws { - try await setup(withModels: ExplicitMultipleOwnerModelRegistration(), - testType: .defaultAuthCognito) - + try await setup( + withModels: ExplicitMultipleOwnerModelRegistration(), + testType: .defaultAuthCognito + ) + try await signIn(user: user1) - + let expectations = makeExpectations() - + try await assertDataStoreReady(expectations) - + // Query - try await assertQuerySuccess(modelType: TodoCognitoMultiOwner.self, - expectations) { error in + try await assertQuerySuccess( + modelType: TodoCognitoMultiOwner.self, + expectations + ) { error in XCTFail("Error query \(error)") } - + let post = TodoCognitoMultiOwner(title: "title") - + // Mutations try await assertMutations(model: post, expectations) { error in XCTFail("Error mutation \(error)") } - + assertUsedAuthTypes([.amazonCognitoUserPools]) } - + /// Given: a user signed in with CognitoUserPools, a model with an implicit owner field /// When: DataStore query/mutation operations are sent with CognitoUserPools /// Then: DataStore is successfully initialized, query returns a result, /// mutation is processed for an authenticated users func testImplicitOwner() async throws { - try await setup(withModels: ImplicitOwnerModelRegistration(), - testType: .defaultAuthCognito) + try await setup( + withModels: ImplicitOwnerModelRegistration(), + testType: .defaultAuthCognito + ) try await signIn(user: user1) @@ -148,8 +166,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT try await assertDataStoreReady(expectations) // Query - try await assertQuerySuccess(modelType: TodoImplicitOwnerField.self, - expectations) { error in + try await assertQuerySuccess( + modelType: TodoImplicitOwnerField.self, + expectations + ) { error in XCTFail("Error query \(error)") } @@ -168,8 +188,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT /// Then: DataStore is successfully initialized, query returns a result, /// mutation is processed for an authenticated users func testAllowPrivate() async throws { - try await setup(withModels: AllowPrivateModelRegistration(), - testType: .defaultAuthCognito) + try await setup( + withModels: AllowPrivateModelRegistration(), + testType: .defaultAuthCognito + ) try await signIn(user: user1) @@ -178,8 +200,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT try await assertDataStoreReady(expectations) // Query - try await assertQuerySuccess(modelType: TodoCognitoPrivate.self, - expectations) { error in + try await assertQuerySuccess( + modelType: TodoCognitoPrivate.self, + expectations + ) { error in XCTFail("Error query \(error)") } @@ -225,7 +249,7 @@ extension AWSDataStoreCategoryPluginAuthOwnerIntegrationTests { ModelRegistry.register(modelType: TodoCognitoMultiOwner.self) } } - + struct ImplicitOwnerModelRegistration: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner+Schema.swift index a42c5ea85a..1d4ead4562 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension TodoCognitoMultiOwner { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension TodoCognitoMultiOwner { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case content @@ -20,25 +20,25 @@ extension TodoCognitoMultiOwner { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let todoCognitoMultiOwner = TodoCognitoMultiOwner.keys - + model.authRules = [ rule(allow: .owner, ownerField: "owner", identityClaim: "cognito:username", provider: .userPools, operations: [.create, .update, .delete, .read]), rule(allow: .owner, ownerField: "editors", identityClaim: "cognito:username", provider: .userPools, operations: [.update, .read]) ] - + model.listPluralName = "TodoCognitoMultiOwners" model.syncPluralName = "TodoCognitoMultiOwners" - + model.attributes( .primaryKey(fields: [todoCognitoMultiOwner.id]) ) - + model.fields( .field(todoCognitoMultiOwner.id, is: .required, ofType: .string), .field(todoCognitoMultiOwner.title, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner.swift index ad45c098b8..3042046b21 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner.swift @@ -17,27 +17,33 @@ public struct TodoCognitoMultiOwner: Model { public var editors: [String?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - content: String? = nil, - owner: String? = nil, - editors: [String?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + content: String? = nil, + owner: String? = nil, + editors: [String?]? = nil + ) { + self.init( + id: id, title: title, content: content, owner: owner, editors: editors, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - content: String? = nil, - owner: String? = nil, - editors: [String?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + content: String? = nil, + owner: String? = nil, + editors: [String?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate+Schema.swift index 27b73152a8..2e1435be6a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate+Schema.swift @@ -9,32 +9,32 @@ import Amplify import Foundation -extension TodoCognitoPrivate { +public extension TodoCognitoPrivate { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let todoCognitoPrivate = TodoCognitoPrivate.keys - + model.authRules = [ rule(allow: .private, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "TodoCognitoPrivates" model.syncPluralName = "TodoCognitoPrivates" - + model.attributes( .primaryKey(fields: [todoCognitoPrivate.id]) ) - + model.fields( .field(todoCognitoPrivate.id, is: .required, ofType: .string), .field(todoCognitoPrivate.title, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate.swift index a25e488232..efb65dc817 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate.swift @@ -15,17 +15,23 @@ public struct TodoCognitoPrivate: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String + ) { + self.init( + id: id, title: title, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit+Schema.swift index 3688748647..cd91d9eabf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit+Schema.swift @@ -9,33 +9,33 @@ import Amplify import Foundation -extension TodoCustomOwnerExplicit { +public extension TodoCustomOwnerExplicit { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case dominus case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let todoCustomOwnerExplicit = TodoCustomOwnerExplicit.keys - + model.authRules = [ rule(allow: .owner, ownerField: "dominus", identityClaim: "cognito:username", provider: .userPools, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "TodoCustomOwnerExplicits" model.syncPluralName = "TodoCustomOwnerExplicits" - + model.attributes( .primaryKey(fields: [todoCustomOwnerExplicit.id]) ) - + model.fields( .field(todoCustomOwnerExplicit.id, is: .required, ofType: .string), .field(todoCustomOwnerExplicit.title, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit.swift index b55124bbc1..dc848b009c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit.swift @@ -16,20 +16,26 @@ public struct TodoCustomOwnerExplicit: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - dominus: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + dominus: String? = nil + ) { + self.init( + id: id, title: title, dominus: dominus, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - dominus: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + dominus: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.dominus = dominus diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit+Schema.swift index 4aa97d8ab0..74061eda96 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit+Schema.swift @@ -9,32 +9,32 @@ import Amplify import Foundation -extension TodoCustomOwnerImplicit { +public extension TodoCustomOwnerImplicit { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let todoCustomOwnerImplicit = TodoCustomOwnerImplicit.keys - + model.authRules = [ rule(allow: .owner, ownerField: "dominus", identityClaim: "cognito:username", provider: .userPools, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "TodoCustomOwnerImplicits" model.syncPluralName = "TodoCustomOwnerImplicits" - + model.attributes( .primaryKey(fields: [todoCustomOwnerImplicit.id]) ) - + model.fields( .field(todoCustomOwnerImplicit.id, is: .required, ofType: .string), .field(todoCustomOwnerImplicit.title, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit.swift index 81e5db2f86..6e99122e71 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit.swift @@ -15,17 +15,23 @@ public struct TodoCustomOwnerImplicit: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String + ) { + self.init( + id: id, title: title, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField+Schema.swift index c31e9d89a0..f775d485cd 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField+Schema.swift @@ -9,33 +9,33 @@ import Amplify import Foundation -extension TodoExplicitOwnerField { +public extension TodoExplicitOwnerField { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case owner case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let todoExplicitOwnerField = TodoExplicitOwnerField.keys - + model.authRules = [ rule(allow: .owner, ownerField: "owner", identityClaim: "cognito:username", provider: .userPools, operations: [.read, .create, .update, .delete]) ] - + model.listPluralName = "TodoExplicitOwnerFields" model.syncPluralName = "TodoExplicitOwnerFields" - + model.attributes( .primaryKey(fields: [todoExplicitOwnerField.id]) ) - + model.fields( .field(todoExplicitOwnerField.id, is: .required, ofType: .string), .field(todoExplicitOwnerField.content, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField.swift index c5b207683c..898110f10c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField.swift @@ -16,20 +16,26 @@ public struct TodoExplicitOwnerField: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String, - owner: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String, + owner: String? = nil + ) { + self.init( + id: id, content: content, owner: owner, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - owner: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + owner: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.owner = owner diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField+Schema.swift index 4c4faa491f..07f5860aa4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField+Schema.swift @@ -9,32 +9,32 @@ import Amplify import Foundation -extension TodoImplicitOwnerField { +public extension TodoImplicitOwnerField { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let todoImplicitOwnerField = TodoImplicitOwnerField.keys - + model.authRules = [ rule(allow: .owner, ownerField: "owner", identityClaim: "cognito:username", provider: .userPools, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "TodoImplicitOwnerFields" model.syncPluralName = "TodoImplicitOwnerFields" - + model.attributes( .primaryKey(fields: [todoImplicitOwnerField.id]) ) - + model.fields( .field(todoImplicitOwnerField.id, is: .required, ofType: .string), .field(todoImplicitOwnerField.content, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField.swift index 9d74762f6b..805b2c8cfe 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField.swift @@ -15,17 +15,23 @@ public struct TodoImplicitOwnerField: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreAuthBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreAuthBaseTest.swift index 8f89a32442..98904d0573 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreAuthBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreAuthBaseTest.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import XCTest -import Combine -import AWSDataStorePlugin -import AWSPluginsCore import AWSAPIPlugin import AWSCognitoAuthPlugin +import AWSDataStorePlugin +import AWSPluginsCore +import Combine +import Foundation +import XCTest #if !os(watchOS) @testable import DataStoreHostApp @@ -47,13 +47,13 @@ class DataStoreAuthBaseTestURLSessionFactory: URLSessionBehaviorFactory { result.insert(.apiKey) } - if let authHeaderValue = authHeaderValue, + if let authHeaderValue, case let .success(claims) = AWSAuthService().getTokenClaims(tokenString: authHeaderValue), let cognitoIss = claims["iss"] as? String, cognitoIss.contains("cognito") { result.insert(.amazonCognitoUserPools) } - if let authHeaderValue = authHeaderValue, + if let authHeaderValue, authHeaderValue.starts(with: "AWS4-HMAC-SHA256") { result.insert(.awsIAM) } @@ -88,9 +88,11 @@ class DataStoreAuthBaseTestURLSessionFactory: URLSessionBehaviorFactory { configuration.tlsMaximumSupportedProtocolVersion = .TLSv13 configuration.protocolClasses?.insert(Sniffer.self, at: 0) - let session = URLSession(configuration: configuration, - delegate: urlSessionDelegate, - delegateQueue: nil) + let session = URLSession( + configuration: configuration, + delegate: urlSessionDelegate, + delegateQueue: nil + ) return AmplifyURLSession(session: session) } @@ -200,8 +202,10 @@ class AWSDataStoreAuthBaseTest: XCTestCase { #else let datastoreConfig = DataStoreConfiguration.custom(authModeStrategy: testType.authStrategy) #endif - try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, - configuration: datastoreConfig)) + try Amplify.add(plugin: AWSDataStorePlugin( + modelRegistration: models, + configuration: datastoreConfig + )) let apiPlugin = apiPluginFactory() @@ -234,40 +238,46 @@ class AWSDataStoreAuthBaseTest: XCTestCase { extension AWSDataStoreAuthBaseTest { /// Signin given user /// - Parameter user - func signIn(user: TestUser?, - file: StaticString = #file, - line: UInt = #line) async { - guard let user = user else { + func signIn( + user: TestUser?, + file: StaticString = #file, + line: UInt = #line + ) async { + guard let user else { XCTFail("Invalid user", file: file, line: line) return } let signInInvoked = expectation(description: "sign in completed") do { - _ = try await Amplify.Auth.signIn(username: user.username, - password: user.password, - options: nil) + _ = try await Amplify.Auth.signIn( + username: user.username, + password: user.password, + options: nil + ) signInInvoked.fulfill() - } catch(let error) { + } catch (let error) { XCTFail("Signin failure \(error)", file: file, line: line) signInInvoked.fulfill() // won't count as pass } await fulfillment(of: [signInInvoked], timeout: TestCommonConstants.networkTimeout) - + let signedIn = await isSignedIn() XCTAssert(signedIn, file: file, line: line) } /// Signout current signed-in user - func signOut(file: StaticString = #file, - line: UInt = #line) async { + func signOut( + file: StaticString = #file, + line: UInt = #line + ) async { let signoutInvoked = expectation(description: "sign out completed") Task { _ = await Amplify.Auth.signOut() signoutInvoked.fulfill() } - + await fulfillment(of: [signoutInvoked], timeout: TestCommonConstants.networkTimeout) - + let signedIn = await isSignedIn() XCTAssert(!signedIn, file: file, line: line) } @@ -279,10 +289,10 @@ extension AWSDataStoreAuthBaseTest { let authSession = try await Amplify.Auth.fetchAuthSession() resultOptional = authSession.isSignedIn checkIsSignedInCompleted.fulfill() - } catch(let error) { + } catch (let error) { fatalError("Failed to get auth session \(error)") } - + await fulfillment(of: [checkIsSignedInCompleted], timeout: TestCommonConstants.networkTimeout) guard let result = resultOptional else { XCTFail("Could not get isSignedIn for user") @@ -308,7 +318,7 @@ extension AWSDataStoreAuthBaseTest { case .failure(let error): XCTFail("Failed to get auth session \(error)") } - } catch(let error) { + } catch (let error) { XCTFail("Failed to get auth session \(error)") } @@ -337,7 +347,7 @@ extension AWSDataStoreAuthBaseTest { case .failure(let error): XCTFail("Failed to get auth session \(error)") } - } catch(let error) { + } catch (let error) { XCTFail("Failed to get auth session \(error)") } await fulfillment(of: [retrieveIdentityCompleted], timeout: TestCommonConstants.networkTimeout) @@ -349,10 +359,12 @@ extension AWSDataStoreAuthBaseTest { return result } - func queryModel(_ model: M.Type, - byId id: String, - file: StaticString = #file, - line: UInt = #line) async -> M? { + func queryModel( + _ model: M.Type, + byId id: String, + file: StaticString = #file, + line: UInt = #line + ) async -> M? { var queriedModel: M? let queriedInvoked = expectation(description: "Model queried") @@ -360,10 +372,10 @@ extension AWSDataStoreAuthBaseTest { let model = try await Amplify.DataStore.query(M.self, byId: id) queriedModel = model queriedInvoked.fulfill() - } catch(let error) { + } catch (let error) { XCTFail("Failed to query model \(error)", file: file, line: line) } - + await fulfillment(of: [queriedInvoked], timeout: TestCommonConstants.networkTimeout) return queriedModel } @@ -376,9 +388,11 @@ extension AWSDataStoreAuthBaseTest { /// - modelType: model type /// - expectation: success XCTestExpectation /// - onFailure: on failure callback - func assertQuerySuccess(modelType: M.Type, - _ expectations: AuthTestExpectations, - onFailure: @escaping (_ error: DataStoreError) -> Void) async { + func assertQuerySuccess( + modelType: (some Model).Type, + _ expectations: AuthTestExpectations, + onFailure: @escaping (_ error: DataStoreError) -> Void + ) async { Amplify.Publisher.create { try await Amplify.DataStore.query(modelType) }.sink { @@ -390,14 +404,18 @@ extension AWSDataStoreAuthBaseTest { XCTAssertNotNil(posts) expectations.query.fulfill() }.store(in: &requests) - await fulfillment(of: [expectations.query], - timeout: 60) + await fulfillment( + of: [expectations.query], + timeout: 60 + ) } /// Asserts that DataStore is in a ready state and subscriptions are established /// - Parameter events: DataStore Hub events - func assertDataStoreReady(_ expectations: AuthTestExpectations, - expectedModelSynced: Int = 1) async { + func assertDataStoreReady( + _ expectations: AuthTestExpectations, + expectedModelSynced: Int = 1 + ) async { var modelSyncedCount = 0 let dataStoreEvents = HubPayload.EventName.DataStore.self Amplify @@ -425,13 +443,17 @@ extension AWSDataStoreAuthBaseTest { do { try await Amplify.DataStore.start() - } catch(let error) { + } catch (let error) { XCTFail("Failure due to error: \(error)") } - await fulfillment(of: [expectations.subscriptionsEstablished, - expectations.modelsSynced, - expectations.ready], - timeout: 60) + await fulfillment( + of: [ + expectations.subscriptionsEstablished, + expectations.modelsSynced, + expectations.ready + ], + timeout: 60 + ) } /// Assert that a save and a delete mutation complete successfully. @@ -439,9 +461,11 @@ extension AWSDataStoreAuthBaseTest { /// - model: model instance saved and then deleted /// - expectations: test expectations /// - onFailure: failure callback - func assertMutations(model: M, - _ expectations: AuthTestExpectations, - onFailure: @escaping (_ error: DataStoreError) -> Void) async { + func assertMutations( + model: some Model, + _ expectations: AuthTestExpectations, + onFailure: @escaping (_ error: DataStoreError) -> Void + ) async { Amplify .Hub .publisher(for: .dataStore) @@ -504,7 +528,7 @@ extension AWSDataStoreAuthBaseTest { DataStoreAuthBaseTestURLSessionFactory.subject .filter { $0.0 == testId } .map { $0.1 } - .collect(.byTime(DispatchQueue.global(), .milliseconds(3500))) + .collect(.byTime(DispatchQueue.global(), .milliseconds(3_500))) .sink { let result = $0.reduce(Set()) { partialResult, data in partialResult.union(data) @@ -529,11 +553,12 @@ extension AWSDataStoreAuthBaseTest { var mutationDeleteProcessed: XCTestExpectation var ready: XCTestExpectation var expectations: [XCTestExpectation] { - return [subscriptionsEstablished, - modelsSynced, - query, - mutationSave, - mutationSaveProcessed + return [ + subscriptionsEstablished, + modelsSynced, + query, + mutationSave, + mutationSaveProcessed ] } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreCategoryPluginIAMAuthIntegrationTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreCategoryPluginIAMAuthIntegrationTests.swift index 9216c48bcb..03d994848c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreCategoryPluginIAMAuthIntegrationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreCategoryPluginIAMAuthIntegrationTests.swift @@ -17,9 +17,11 @@ class AWSDataStoreCategoryPluginIAMAuthIntegrationTests: AWSDataStoreAuthBaseTes /// mutation is processed for authenticated users func testIAMAllowPrivate() async { let testId = UUID().uuidString - await setup(withModels: IAMPrivateModelRegistration(), - testType: .defaultAuthIAM, - testId: testId) + await setup( + withModels: IAMPrivateModelRegistration(), + testType: .defaultAuthIAM, + testId: testId + ) await signIn(user: user1) @@ -30,8 +32,10 @@ class AWSDataStoreCategoryPluginIAMAuthIntegrationTests: AWSDataStoreAuthBaseTes let authTypeExpectation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: TodoIAMPrivate.self, - expectations) { error in + await assertQuerySuccess( + modelType: TodoIAMPrivate.self, + expectations + ) { error in XCTFail("Error query \(error)") } @@ -51,9 +55,11 @@ class AWSDataStoreCategoryPluginIAMAuthIntegrationTests: AWSDataStoreAuthBaseTes /// mutation is processed for unauthenticated users func testIAMAllowPublic() async { let testId = UUID().uuidString - await setup(withModels: IAMPublicModelRegistration(), - testType: .defaultAuthIAM, - testId: testId) + await setup( + withModels: IAMPublicModelRegistration(), + testType: .defaultAuthIAM, + testId: testId + ) let expectations = makeExpectations() @@ -62,8 +68,10 @@ class AWSDataStoreCategoryPluginIAMAuthIntegrationTests: AWSDataStoreAuthBaseTes let authTypeExpectation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: TodoIAMPublic.self, - expectations) { error in + await assertQuerySuccess( + modelType: TodoIAMPublic.self, + expectations + ) { error in XCTFail("Error query \(error)") } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate+Schema.swift index acb4dec219..9268b9fcd1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate+Schema.swift @@ -9,23 +9,23 @@ import Amplify import Foundation -extension TodoIAMPrivate { +public extension TodoIAMPrivate { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todoIAMPrivate = TodoIAMPrivate.keys model.authRules = [ - rule(allow: .private, provider: .iam, operations: [.create, .update, .delete, .read]) + rule(allow: .private, provider: .iam, operations: [.create, .update, .delete, .read]) ] model.pluralName = "TodoIAMPrivates" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate.swift index 767e06c1f4..b2323c498f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate.swift @@ -15,17 +15,23 @@ public struct TodoIAMPrivate: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String + ) { + self.init( + id: id, title: title, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic+Schema.swift index 325dc5d7e4..6cc7819287 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension TodoIAMPublic { +public extension TodoIAMPublic { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todoIAMPublic = TodoIAMPublic.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic.swift index ca128a8e1a..5bff04f220 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic.swift @@ -15,17 +15,23 @@ public struct TodoIAMPublic: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String + ) { + self.init( + id: id, title: title, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4+Schema.swift index 6e27468d61..9062744e8e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment4 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment4 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case commentId case content case createdAt @@ -12,20 +19,20 @@ extension Comment4 { case post4CommentsPostId case post4CommentsTitle } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment4 = Comment4.keys - + model.pluralName = "Comment4s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .primaryKey(fields: [comment4.commentId, comment4.content]) ) - + model.fields( .field(comment4.commentId, is: .required, ofType: .string), .field(comment4.content, is: .required, ofType: .string), @@ -42,9 +49,11 @@ extension Comment4: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment4.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment4.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4.swift index bf249d1211..593b1efc60 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Comment4: Model { public var updatedAt: Temporal.DateTime? public var post4CommentsPostId: String? public var post4CommentsTitle: String? - - public init(commentId: String, - content: String, - post4CommentsPostId: String? = nil, - post4CommentsTitle: String? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + post4CommentsPostId: String? = nil, + post4CommentsTitle: String? = nil + ) { + self.init( + commentId: commentId, content: content, createdAt: nil, updatedAt: nil, post4CommentsPostId: post4CommentsPostId, - post4CommentsTitle: post4CommentsTitle) + post4CommentsTitle: post4CommentsTitle + ) } - internal init(commentId: String, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - post4CommentsPostId: String? = nil, - post4CommentsTitle: String? = nil) { + init( + commentId: String, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + post4CommentsPostId: String? = nil, + post4CommentsTitle: String? = nil + ) { self.commentId = commentId self.content = content self.createdAt = createdAt @@ -34,4 +47,4 @@ public struct Comment4: Model { self.post4CommentsPostId = post4CommentsPostId self.post4CommentsTitle = post4CommentsTitle } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7+Schema.swift index 7f15cca8e7..b04296095a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment7 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment7 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case commentId case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment7 = Comment7.keys - + model.pluralName = "Comment7s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .index(fields: ["postId", "postTitle"], name: "byPost"), .primaryKey(fields: [comment7.commentId, comment7.content]) ) - + model.fields( .field(comment7.commentId, is: .required, ofType: .string), .field(comment7.content, is: .required, ofType: .string), @@ -41,9 +48,11 @@ extension Comment7: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment7.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment7.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7.swift index bdf2ed40ce..57b5b11bbd 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Comment7: Model { public var post: Post7? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(commentId: String, - content: String, - post: Post7? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + post: Post7? = nil + ) { + self.init( + commentId: commentId, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(commentId: String, - content: String, - post: Post7? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + commentId: String, + content: String, + post: Post7? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.commentId = commentId self.content = content self.post = post self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8+Schema.swift index 7bec3d9989..70d4be4f6e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case commentId case content case postId @@ -12,21 +19,21 @@ extension Comment8 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment8 = Comment8.keys - + model.pluralName = "Comment8s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .index(fields: ["postId", "postTitle"], name: "byPost"), .primaryKey(fields: [comment8.commentId, comment8.content]) ) - + model.fields( .field(comment8.commentId, is: .required, ofType: .string), .field(comment8.content, is: .required, ofType: .string), @@ -43,9 +50,11 @@ extension Comment8: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment8.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment8.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8.swift index 22fcd26a4b..0fc5456492 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Comment8: Model { public var postTitle: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(commentId: String, - content: String, - postId: String? = nil, - postTitle: String? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + postId: String? = nil, + postTitle: String? = nil + ) { + self.init( + commentId: commentId, content: content, postId: postId, postTitle: postTitle, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(commentId: String, - content: String, - postId: String? = nil, - postTitle: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + commentId: String, + content: String, + postId: String? = nil, + postTitle: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.commentId = commentId self.content = content self.postId = postId @@ -34,4 +47,4 @@ public struct Comment8: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex+Schema.swift index 777e8fe158..fae7029627 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CommentWithCompositeKeyAndIndex { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension CommentWithCompositeKeyAndIndex { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let commentWithCompositeKeyAndIndex = CommentWithCompositeKeyAndIndex.keys - + model.pluralName = "CommentWithCompositeKeyAndIndices" - + model.attributes( .index(fields: ["id", "content"], name: nil), .index(fields: ["postID", "postTitle"], name: "byPost"), .primaryKey(fields: [commentWithCompositeKeyAndIndex.id, commentWithCompositeKeyAndIndex.content]) ) - + model.fields( .field(commentWithCompositeKeyAndIndex.id, is: .required, ofType: .string), .field(commentWithCompositeKeyAndIndex.content, is: .required, ofType: .string), @@ -41,9 +48,11 @@ extension CommentWithCompositeKeyAndIndex: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CommentWithCompositeKeyAndIndex.IdentifierProtocol { - public static func identifier(id: String, - content: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "content", value: content)]) +public extension CommentWithCompositeKeyAndIndex.IdentifierProtocol { + static func identifier( + id: String, + content: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "content", value: content)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex.swift index 8f3562e1e0..595f98fa30 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct CommentWithCompositeKeyAndIndex: Model { public var post: PostWithCompositeKeyAndIndex? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKeyAndIndex? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKeyAndIndex? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKeyAndIndex? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKeyAndIndex? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional+Schema.swift index 91a30cf9de..4db364f449 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CommentWithCompositeKeyUnidirectional { +public extension CommentWithCompositeKeyUnidirectional { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt @@ -20,10 +20,10 @@ extension CommentWithCompositeKeyUnidirectional { case postWithCompositeKeyUnidirectionalCommentsTitle } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let commentWithCompositeKeyUnidirectional = CommentWithCompositeKeyUnidirectional.keys model.pluralName = "CommentWithCompositeKeyUnidirectionals" @@ -49,9 +49,11 @@ extension CommentWithCompositeKeyUnidirectional: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CommentWithCompositeKeyUnidirectional.IdentifierProtocol { - public static func identifier(id: String, - content: String) -> Self { +public extension CommentWithCompositeKeyUnidirectional.IdentifierProtocol { + static func identifier( + id: String, + content: String + ) -> Self { .make(fields: [(name: "id", value: id), (name: "content", value: content)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional.swift index 23617b6d3e..d3ea55a904 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional.swift @@ -17,23 +17,29 @@ public struct CommentWithCompositeKeyUnidirectional: Model { public var postWithCompositeKeyUnidirectionalCommentsId: String? public var postWithCompositeKeyUnidirectionalCommentsTitle: String? - public init(id: String = UUID().uuidString, - content: String, - post21CommentsId: String? = nil, - post21CommentsTitle: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String, + post21CommentsId: String? = nil, + post21CommentsTitle: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, updatedAt: nil, postWithCompositeKeyUnidirectionalCommentsId: post21CommentsId, - postWithCompositeKeyUnidirectionalCommentsTitle: post21CommentsTitle) + postWithCompositeKeyUnidirectionalCommentsTitle: post21CommentsTitle + ) } - internal init(id: String = UUID().uuidString, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - postWithCompositeKeyUnidirectionalCommentsId: String? = nil, - postWithCompositeKeyUnidirectionalCommentsTitle: String? = nil) { + init( + id: String = UUID().uuidString, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + postWithCompositeKeyUnidirectionalCommentsId: String? = nil, + postWithCompositeKeyUnidirectionalCommentsTitle: String? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk+Schema.swift index e754bac1c7..6cd83a593f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ModelCompositeIntPk { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ModelCompositeIntPk { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case serial case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let modelCompositeIntPk = ModelCompositeIntPk.keys - + model.pluralName = "ModelCompositeIntPks" - + model.attributes( .index(fields: ["id", "serial"], name: nil), .primaryKey(fields: [modelCompositeIntPk.id, modelCompositeIntPk.serial]) ) - + model.fields( .field(modelCompositeIntPk.id, is: .required, ofType: .string), .field(modelCompositeIntPk.serial, is: .required, ofType: .int), @@ -38,9 +45,11 @@ extension ModelCompositeIntPk: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelCompositeIntPk.IdentifierProtocol { - public static func identifier(id: String, - serial: Int) -> Self { - .make(fields:[(name: "id", value: id), (name: "serial", value: serial)]) +public extension ModelCompositeIntPk.IdentifierProtocol { + static func identifier( + id: String, + serial: Int + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "serial", value: serial)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk.swift index 35c6ea35ba..1af43fb97a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct ModelCompositeIntPk: Model { public let serial: Int public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - serial: Int) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + serial: Int + ) { + self.init( + id: id, serial: serial, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - serial: Int, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + serial: Int, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.serial = serial self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk+Schema.swift index 1a31fb3ce0..2106583e7c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ModelCompositeMultiplePk { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ModelCompositeMultiplePk { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case location case name @@ -12,20 +19,20 @@ extension ModelCompositeMultiplePk { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let modelCompositeMultiplePk = ModelCompositeMultiplePk.keys - + model.pluralName = "ModelCompositeMultiplePks" - + model.attributes( .index(fields: ["id", "location", "name"], name: nil), .primaryKey(fields: [modelCompositeMultiplePk.id, modelCompositeMultiplePk.location, modelCompositeMultiplePk.name]) ) - + model.fields( .field(modelCompositeMultiplePk.id, is: .required, ofType: .string), .field(modelCompositeMultiplePk.location, is: .required, ofType: .string), @@ -42,10 +49,12 @@ extension ModelCompositeMultiplePk: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelCompositeMultiplePk.IdentifierProtocol { - public static func identifier(id: String, - location: String, - name: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "location", value: location), (name: "name", value: name)]) +public extension ModelCompositeMultiplePk.IdentifierProtocol { + static func identifier( + id: String, + location: String, + name: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "location", value: location), (name: "name", value: name)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk.swift index 238c7b2ba6..e75bb7aed9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct ModelCompositeMultiplePk: Model { public var lastName: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - location: String, - name: String, - lastName: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + location: String, + name: String, + lastName: String? = nil + ) { + self.init( + id: id, location: location, name: name, lastName: lastName, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - location: String, - name: String, - lastName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + location: String, + name: String, + lastName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.location = location self.name = name @@ -34,4 +47,4 @@ public struct ModelCompositeMultiplePk: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk+Schema.swift index d166130aa2..db5b4bb923 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ModelCompositePk { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ModelCompositePk { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case dob case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let modelCompositePk = ModelCompositePk.keys - + model.pluralName = "ModelCompositePks" - + model.attributes( .index(fields: ["id", "dob"], name: nil), .primaryKey(fields: [modelCompositePk.id, modelCompositePk.dob]) ) - + model.fields( .field(modelCompositePk.id, is: .required, ofType: .string), .field(modelCompositePk.dob, is: .required, ofType: .dateTime), @@ -40,9 +47,11 @@ extension ModelCompositePk: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelCompositePk.IdentifierProtocol { - public static func identifier(id: String, - dob: Temporal.DateTime) -> Self { - .make(fields:[(name: "id", value: id), (name: "dob", value: dob)]) +public extension ModelCompositePk.IdentifierProtocol { + static func identifier( + id: String, + dob: Temporal.DateTime + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "dob", value: dob)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk.swift index 21766fab12..98ce1635fa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct ModelCompositePk: Model { public var name: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil + ) { + self.init( + id: id, dob: dob, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.dob = dob self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo+Schema.swift index 525ecc5ce5..15d8123b26 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension ModelCompositePkBelongsTo { +public extension ModelCompositePkBelongsTo { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case dob case owner @@ -20,10 +20,10 @@ extension ModelCompositePkBelongsTo { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let modelCompositePkBelongsTo = ModelCompositePkBelongsTo.keys model.pluralName = "ModelCompositePkBelongsTos" @@ -33,17 +33,20 @@ extension ModelCompositePkBelongsTo { ) model.fields( - .field(modelCompositePkBelongsTo.id, is: .required, ofType: .string), - .field(modelCompositePkBelongsTo.dob, is: .required, ofType: .dateTime), - .field(modelCompositePkBelongsTo.name, is: .optional, ofType: .string), - .belongsTo(modelCompositePkBelongsTo.owner, is: .optional, - ofType: ModelCompositePkWithAssociation.self, - targetNames: [ - "modelCompositePkWithAssociationOtherModelsId", - "modelCompositePkWithAssociationOtherModelsDob" - ]), - .field(modelCompositePkBelongsTo.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), - .field(modelCompositePkBelongsTo.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) + .field(modelCompositePkBelongsTo.id, is: .required, ofType: .string), + .field(modelCompositePkBelongsTo.dob, is: .required, ofType: .dateTime), + .field(modelCompositePkBelongsTo.name, is: .optional, ofType: .string), + .belongsTo( + modelCompositePkBelongsTo.owner, + is: .optional, + ofType: ModelCompositePkWithAssociation.self, + targetNames: [ + "modelCompositePkWithAssociationOtherModelsId", + "modelCompositePkWithAssociationOtherModelsDob" + ] + ), + .field(modelCompositePkBelongsTo.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), + .field(modelCompositePkBelongsTo.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } } @@ -53,8 +56,8 @@ extension ModelCompositePkBelongsTo: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelCompositePkBelongsTo.IdentifierProtocol { - public static func identifier(id: String, dob: Temporal.DateTime) -> Self { +public extension ModelCompositePkBelongsTo.IdentifierProtocol { + static func identifier(id: String, dob: Temporal.DateTime) -> Self { .make(fields: [(name: "id", value: id), (name: "dob", value: dob)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo.swift index 4d4817d0fc..8d9963a420 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo.swift @@ -17,23 +17,29 @@ public struct ModelCompositePkBelongsTo: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil, - owner: ModelCompositePkWithAssociation? = nil) { - self.init(id: id, - dob: dob, - name: name, - owner: owner, - createdAt: nil, - updatedAt: nil) + public init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil, + owner: ModelCompositePkWithAssociation? = nil + ) { + self.init( + id: id, + dob: dob, + name: name, + owner: owner, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil, - owner: ModelCompositePkWithAssociation? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil, + owner: ModelCompositePkWithAssociation? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.dob = dob self.name = name diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation+Schema.swift index cbb3bc7f85..0ad5807f7e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension ModelCompositePkWithAssociation { +public extension ModelCompositePkWithAssociation { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case dob case name @@ -20,10 +20,10 @@ extension ModelCompositePkWithAssociation { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let modelCompositePkWithAssociation = ModelCompositePkWithAssociation.keys model.pluralName = "ModelCompositePkWithAssociations" @@ -36,10 +36,12 @@ extension ModelCompositePkWithAssociation { .field(modelCompositePkWithAssociation.id, is: .required, ofType: .string), .field(modelCompositePkWithAssociation.dob, is: .required, ofType: .dateTime), .field(modelCompositePkWithAssociation.name, is: .optional, ofType: .string), - .hasMany(modelCompositePkWithAssociation.otherModels, - is: .optional, - ofType: ModelCompositePkBelongsTo.self, - associatedWith: ModelCompositePkBelongsTo.keys.owner), + .hasMany( + modelCompositePkWithAssociation.otherModels, + is: .optional, + ofType: ModelCompositePkBelongsTo.self, + associatedWith: ModelCompositePkBelongsTo.keys.owner + ), .field(modelCompositePkWithAssociation.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), .field(modelCompositePkWithAssociation.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) @@ -51,8 +53,8 @@ extension ModelCompositePkWithAssociation: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelCompositePkWithAssociation.IdentifierProtocol { - public static func identifier(id: String, dob: Temporal.DateTime) -> Self { +public extension ModelCompositePkWithAssociation.IdentifierProtocol { + static func identifier(id: String, dob: Temporal.DateTime) -> Self { .make(fields: [(name: "id", value: id), (name: "dob", value: dob)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation.swift index 810e0e9a3f..ece232844f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation.swift @@ -17,23 +17,29 @@ public struct ModelCompositePkWithAssociation: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil, - otherModels: List? = []) { - self.init(id: id, - dob: dob, - name: name, - otherModels: otherModels, - createdAt: nil, - updatedAt: nil) + public init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil, + otherModels: List? = [] + ) { + self.init( + id: id, + dob: dob, + name: name, + otherModels: otherModels, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil, - otherModels: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil, + otherModels: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.dob = dob self.name = name diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPKDefined.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPKDefined.swift index 651ae307db..e658cbc193 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPKDefined.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPKDefined.swift @@ -16,20 +16,26 @@ public struct ModelCustomPkDefined: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil + ) { + self.init( + id: id, dob: dob, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.dob = dob self.name = name diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPkDefined+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPkDefined+Schema.swift index 49c4b706a5..11809bb3f1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPkDefined+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPkDefined+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension ModelCustomPkDefined { +public extension ModelCustomPkDefined { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case dob case name @@ -19,10 +19,10 @@ extension ModelCustomPkDefined { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let modelCompositePk = ModelCustomPkDefined.keys model.pluralName = "ModelCustomPkDefined" @@ -48,8 +48,8 @@ extension ModelCustomPkDefined: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelCustomPkDefined.IdentifierProtocol { - public static func identifier(id: String, dob: Temporal.DateTime) -> Self { +public extension ModelCustomPkDefined.IdentifierProtocol { + static func identifier(id: String, dob: Temporal.DateTime) -> Self { .make(fields: [(name: "id", value: id), (name: "dob", value: dob)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk+Schema.swift index e01e1077e6..fe673e971b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ModelExplicitCustomPk { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ModelExplicitCustomPk { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case userId case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let modelExplicitCustomPk = ModelExplicitCustomPk.keys - + model.pluralName = "ModelExplicitCustomPks" - + model.attributes( .index(fields: ["userId"], name: nil), .primaryKey(fields: [modelExplicitCustomPk.userId]) ) - + model.fields( .field(modelExplicitCustomPk.userId, is: .required, ofType: .string), .field(modelExplicitCustomPk.name, is: .optional, ofType: .string), @@ -38,8 +45,8 @@ extension ModelExplicitCustomPk: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelExplicitCustomPk.IdentifierProtocol { - public static func identifier(userId: String) -> Self { - .make(fields:[(name: "userId", value: userId)]) +public extension ModelExplicitCustomPk.IdentifierProtocol { + static func identifier(userId: String) -> Self { + .make(fields: [(name: "userId", value: userId)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk.swift index 59b1dc1359..a7b95653a5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct ModelExplicitCustomPk: Model { public var name: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(userId: String, - name: String? = nil) { - self.init(userId: userId, + + public init( + userId: String, + name: String? = nil + ) { + self.init( + userId: userId, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(userId: String, - name: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + userId: String, + name: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.userId = userId self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk+Schema.swift index 6752864fc3..0e3a76938d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ModelExplicitDefaultPk { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ModelExplicitDefaultPk { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let modelExplicitDefaultPk = ModelExplicitDefaultPk.keys - + model.pluralName = "ModelExplicitDefaultPks" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [modelExplicitDefaultPk.id]) ) - + model.fields( .field(modelExplicitDefaultPk.id, is: .required, ofType: .string), .field(modelExplicitDefaultPk.name, is: .optional, ofType: .string), @@ -36,4 +43,4 @@ extension ModelExplicitDefaultPk { extension ModelExplicitDefaultPk: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk.swift index b44e5e9377..880c718eff 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct ModelExplicitDefaultPk: Model { public var name: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String? = nil + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk+Schema.swift index 0fe7bb7ae2..a3db3c0163 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk+Schema.swift @@ -1,28 +1,35 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ModelImplicitDefaultPk { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ModelImplicitDefaultPk { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let modelImplicitDefaultPk = ModelImplicitDefaultPk.keys - + model.pluralName = "ModelImplicitDefaultPks" - + model.attributes( .primaryKey(fields: [modelImplicitDefaultPk.id]) ) - + model.fields( .field(modelImplicitDefaultPk.id, is: .required, ofType: .string), .field(modelImplicitDefaultPk.name, is: .optional, ofType: .string), @@ -35,4 +42,4 @@ extension ModelImplicitDefaultPk { extension ModelImplicitDefaultPk: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk.swift index a476abedf9..69fa2b17dc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct ModelImplicitDefaultPk: Model { public var name: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String? = nil + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4+Schema.swift index 0f9b9f5740..d1b37b849a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post4 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post4 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post4 = Post4.keys - + model.pluralName = "Post4s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post4.postId, post4.title]) ) - + model.fields( .field(post4.postId, is: .required, ofType: .string), .field(post4.title, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension Post4: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post4.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post4.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4.swift index a50849704b..1d08640c37 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post4: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7+Schema.swift index 7700f9207a..44dac0b093 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post7 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post7 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post7 = Post7.keys - + model.pluralName = "Post7s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post7.postId, post7.title]) ) - + model.fields( .field(post7.postId, is: .required, ofType: .string), .field(post7.title, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension Post7: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post7.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post7.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7.swift index 8cb750a96d..c07fbc8320 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post7: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8+Schema.swift index 520236fa1e..9a11351d9d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post8 = Post8.keys - + model.pluralName = "Post8s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post8.postId, post8.title]) ) - + model.fields( .field(post8.postId, is: .required, ofType: .string), .field(post8.title, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension Post8: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post8.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post8.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8.swift index 440cd2b9d7..eb60ae8287 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post8: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey+Schema.swift index 172936f4e8..1d03fc790d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostTagsWithCompositeKey { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension PostTagsWithCompositeKey { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case postWithTagsCompositeKey case tagWithCompositeKey case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let postTagsWithCompositeKey = PostTagsWithCompositeKey.keys - + model.pluralName = "PostTagsWithCompositeKeys" - + model.attributes( .index(fields: ["postWithTagsCompositeKeyPostId", "postWithTagsCompositeKeytitle"], name: "byPostWithTagsCompositeKey"), .index(fields: ["tagWithCompositeKeyId", "tagWithCompositeKeyname"], name: "byTagWithCompositeKey"), .primaryKey(fields: [postTagsWithCompositeKey.id]) ) - + model.fields( .field(postTagsWithCompositeKey.id, is: .required, ofType: .string), .belongsTo(postTagsWithCompositeKey.postWithTagsCompositeKey, is: .required, ofType: PostWithTagsCompositeKey.self, targetNames: ["postWithTagsCompositeKeyPostId", "postWithTagsCompositeKeytitle"]), @@ -39,4 +46,4 @@ extension PostTagsWithCompositeKey { extension PostTagsWithCompositeKey: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey.swift index d03e2b5e42..9bf3f2b9e0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostTagsWithCompositeKey: Model { public var tagWithCompositeKey: TagWithCompositeKey public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - postWithTagsCompositeKey: PostWithTagsCompositeKey, - tagWithCompositeKey: TagWithCompositeKey) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + postWithTagsCompositeKey: PostWithTagsCompositeKey, + tagWithCompositeKey: TagWithCompositeKey + ) { + self.init( + id: id, postWithTagsCompositeKey: postWithTagsCompositeKey, tagWithCompositeKey: tagWithCompositeKey, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - postWithTagsCompositeKey: PostWithTagsCompositeKey, - tagWithCompositeKey: TagWithCompositeKey, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + postWithTagsCompositeKey: PostWithTagsCompositeKey, + tagWithCompositeKey: TagWithCompositeKey, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.postWithTagsCompositeKey = postWithTagsCompositeKey self.tagWithCompositeKey = tagWithCompositeKey self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex+Schema.swift index 0f13a541b9..16b1d5f5c1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithCompositeKeyAndIndex { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension PostWithCompositeKeyAndIndex { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let postWithCompositeKeyAndIndex = PostWithCompositeKeyAndIndex.keys - + model.pluralName = "PostWithCompositeKeyAndIndices" - + model.attributes( .index(fields: ["id", "title"], name: nil), .primaryKey(fields: [postWithCompositeKeyAndIndex.id, postWithCompositeKeyAndIndex.title]) ) - + model.fields( .field(postWithCompositeKeyAndIndex.id, is: .required, ofType: .string), .field(postWithCompositeKeyAndIndex.title, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension PostWithCompositeKeyAndIndex: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithCompositeKeyAndIndex.IdentifierProtocol { - public static func identifier(id: String, - title: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "title", value: title)]) +public extension PostWithCompositeKeyAndIndex.IdentifierProtocol { + static func identifier( + id: String, + title: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "title", value: title)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex.swift index 02bf0180d9..f190c30706 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithCompositeKeyAndIndex: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional+Schema.swift index 3148b8c002..644cc6a816 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension PostWithCompositeKeyUnidirectional { +public extension PostWithCompositeKeyUnidirectional { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension PostWithCompositeKeyUnidirectional { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let postWithCompositeKeyUnidirectional = PostWithCompositeKeyUnidirectional.keys model.pluralName = "PostWithCompositeKeyUnidirectionals" @@ -35,10 +35,12 @@ extension PostWithCompositeKeyUnidirectional { model.fields( .field(postWithCompositeKeyUnidirectional.id, is: .required, ofType: .string), .field(postWithCompositeKeyUnidirectional.title, is: .required, ofType: .string), - .hasMany(postWithCompositeKeyUnidirectional.comments, - is: .optional, - ofType: CommentWithCompositeKeyUnidirectional.self, - associatedWith: CommentWithCompositeKeyUnidirectional.keys.postWithCompositeKeyUnidirectionalCommentsId), + .hasMany( + postWithCompositeKeyUnidirectional.comments, + is: .optional, + ofType: CommentWithCompositeKeyUnidirectional.self, + associatedWith: CommentWithCompositeKeyUnidirectional.keys.postWithCompositeKeyUnidirectionalCommentsId + ), .field(postWithCompositeKeyUnidirectional.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), .field(postWithCompositeKeyUnidirectional.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) @@ -50,9 +52,11 @@ extension PostWithCompositeKeyUnidirectional: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithCompositeKeyUnidirectional.IdentifierProtocol { - public static func identifier(id: String, - title: String) -> Self { +public extension PostWithCompositeKeyUnidirectional.IdentifierProtocol { + static func identifier( + id: String, + title: String + ) -> Self { .make(fields: [(name: "id", value: id), (name: "title", value: title)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional.swift index 23bffde135..822c27b88e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional.swift @@ -16,20 +16,26 @@ public struct PostWithCompositeKeyUnidirectional: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey+Schema.swift index 2c0cd997e6..c2d50bd16a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithTagsCompositeKey { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension PostWithTagsCompositeKey { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case tags case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let postWithTagsCompositeKey = PostWithTagsCompositeKey.keys - + model.pluralName = "PostWithTagsCompositeKeys" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [postWithTagsCompositeKey.postId, postWithTagsCompositeKey.title]) ) - + model.fields( .field(postWithTagsCompositeKey.postId, is: .required, ofType: .string), .field(postWithTagsCompositeKey.title, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension PostWithTagsCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithTagsCompositeKey.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension PostWithTagsCompositeKey.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey.swift index c739bc9c22..73e3e3cd7c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithTagsCompositeKey: Model { public var tags: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - tags: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + tags: List? = [] + ) { + self.init( + postId: postId, title: title, tags: tags, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - tags: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + tags: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.tags = tags self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2+Schema.swift index 2ca9794b8d..aa67a3738d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Project2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project2 { case project2TeamTeamId case project2TeamName } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let project2 = Project2.keys - + model.pluralName = "Project2s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project2.projectId, project2.name]) ) - + model.fields( .field(project2.projectId, is: .required, ofType: .string), .field(project2.name, is: .required, ofType: .string), @@ -44,9 +51,11 @@ extension Project2: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project2.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project2.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2.swift index 29e0c614bb..3bf27c3b8a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -10,27 +17,33 @@ public struct Project2: Model { public var updatedAt: Temporal.DateTime? public var project2TeamTeamId: String? public var project2TeamName: String? - - public init(projectId: String, - name: String, - team: Team2? = nil, - project2TeamTeamId: String? = nil, - project2TeamName: String? = nil) { - self.init(projectId: projectId, + + public init( + projectId: String, + name: String, + team: Team2? = nil, + project2TeamTeamId: String? = nil, + project2TeamName: String? = nil + ) { + self.init( + projectId: projectId, name: name, team: team, createdAt: nil, updatedAt: nil, project2TeamTeamId: project2TeamTeamId, - project2TeamName: project2TeamName) + project2TeamName: project2TeamName + ) } - internal init(projectId: String, - name: String, - team: Team2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project2TeamTeamId: String? = nil, - project2TeamName: String? = nil) { + init( + projectId: String, + name: String, + team: Team2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project2TeamTeamId: String? = nil, + project2TeamName: String? = nil + ) { self.projectId = projectId self.name = name self.team = team @@ -39,4 +52,4 @@ public struct Project2: Model { self.project2TeamTeamId = project2TeamTeamId self.project2TeamName = project2TeamName } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6+Schema.swift index 6cda02ed54..cda9e71951 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project6 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Project6 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project6 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let project6 = Project6.keys - + model.pluralName = "Project6s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project6.projectId, project6.name]) ) - + model.fields( .field(project6.projectId, is: .required, ofType: .string), .field(project6.name, is: .required, ofType: .string), @@ -44,9 +51,11 @@ extension Project6: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project6.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project6.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6.swift index 346cb44d71..a7a386cbbf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -10,27 +17,33 @@ public struct Project6: Model { public var teamName: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(projectId: String, - name: String, - team: Team6? = nil, - teamId: String? = nil, - teamName: String? = nil) { - self.init(projectId: projectId, + + public init( + projectId: String, + name: String, + team: Team6? = nil, + teamId: String? = nil, + teamName: String? = nil + ) { + self.init( + projectId: projectId, name: name, team: team, teamId: teamId, teamName: teamName, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(projectId: String, - name: String, - team: Team6? = nil, - teamId: String? = nil, - teamName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + projectId: String, + name: String, + team: Team6? = nil, + teamId: String? = nil, + teamName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.projectId = projectId self.name = name self.team = team @@ -39,4 +52,4 @@ public struct Project6: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey+Schema.swift index dd535f584d..9332ae93d1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension TagWithCompositeKey { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension TagWithCompositeKey { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case posts case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let tagWithCompositeKey = TagWithCompositeKey.keys - + model.pluralName = "TagWithCompositeKeys" - + model.attributes( .index(fields: ["id", "name"], name: nil), .primaryKey(fields: [tagWithCompositeKey.id, tagWithCompositeKey.name]) ) - + model.fields( .field(tagWithCompositeKey.id, is: .required, ofType: .string), .field(tagWithCompositeKey.name, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension TagWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension TagWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - name: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "name", value: name)]) +public extension TagWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + name: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "name", value: name)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey.swift index 8d8bbf9f26..b913c944db 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct TagWithCompositeKey: Model { public var posts: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2+Schema.swift index 0f7353c4ab..cfe5a5dcfa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case teamId case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team2 = Team2.keys - + model.pluralName = "Team2s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team2.teamId, team2.name]) ) - + model.fields( .field(team2.teamId, is: .required, ofType: .string), .field(team2.name, is: .required, ofType: .string), @@ -38,9 +45,11 @@ extension Team2: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team2.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team2.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2.swift index 90d68caa79..f58e821d6e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Team2: Model { public let name: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String) { - self.init(teamId: teamId, + + public init( + teamId: String, + name: String + ) { + self.init( + teamId: teamId, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6+Schema.swift index 8556fdcbe1..c212b3c3e8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team6 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team6 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case teamId case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team6 = Team6.keys - + model.pluralName = "Team6s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team6.teamId, team6.name]) ) - + model.fields( .field(team6.teamId, is: .required, ofType: .string), .field(team6.name, is: .required, ofType: .string), @@ -38,9 +45,11 @@ extension Team6: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team6.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team6.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6.swift index 88da92235b..3a45fc3f04 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Team6: Model { public let name: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String) { - self.init(teamId: teamId, + + public init( + teamId: String, + name: String + ) { + self.init( + teamId: teamId, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/AWSDataStorePrimaryKeyPostComment4V2Test.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/AWSDataStorePrimaryKeyPostComment4V2Test.swift index 5e3d36095c..033add6cc8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/AWSDataStorePrimaryKeyPostComment4V2Test.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/AWSDataStorePrimaryKeyPostComment4V2Test.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation import XCTest -import Amplify /* ## iOS 10. bi-directional has-many PostComment4V2 @@ -44,10 +44,10 @@ final class AWSDataStorePrimaryKeyPostComment4V2Test: AWSDataStorePrimaryKeyBase setup(withModels: PostComment4V2()) try await assertDataStoreReady() try await assertQuerySuccess(modelType: Post4V2.self) - + let parent = Post4V2(title: "title") let child = Comment4V2(content: "content", post: parent) - + // Mutations try await assertMutationsParentChild(parent: parent, child: child) } @@ -67,13 +67,13 @@ final class AWSDataStorePrimaryKeyPostComment4V2Test: AWSDataStorePrimaryKeyBase func testSavePostAndLazyLoadComments() async throws { setup(withModels: PostComment4V2()) try await assertDataStoreReady() - + let parent = Post4V2(title: "title") let child = Comment4V2(content: "content", post: parent) - + // Mutations try await assertMutationsParentChild(parent: parent, child: child, shouldDeleteParent: false) - + guard let queriedPost = try await Amplify.DataStore.query(Post4V2.self, byId: parent.id) else { XCTFail("Failed to query post") return @@ -84,7 +84,7 @@ final class AWSDataStorePrimaryKeyPostComment4V2Test: AWSDataStorePrimaryKeyBase } try await comments.fetch() XCTAssertEqual(comments.count, 1) - + try await assertDeleteMutation(parent: parent, child: child) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2+Schema.swift index 600509e366..9e7d8246f4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment4V2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment4V2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment4V2 = Comment4V2.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Comment4V2s" - + model.attributes( .index(fields: ["postID", "content"], name: "byPost4"), .primaryKey(fields: [comment4V2.id]) ) - + model.fields( .field(comment4V2.id, is: .required, ofType: .string), .field(comment4V2.content, is: .required, ofType: .string), @@ -42,4 +49,4 @@ extension Comment4V2 { extension Comment4V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2.swift index 3de4f5acfa..0d4073d6b4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Comment4V2: Model { public var post: Post4V2? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2+Schema.swift index e8868bdb5d..dad03d65b6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post4V2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post4V2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post4V2 = Post4V2.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Post4V2s" - + model.attributes( .primaryKey(fields: [post4V2.id]) ) - + model.fields( .field(post4V2.id, is: .required, ofType: .string), .field(post4V2.title, is: .required, ofType: .string), @@ -41,4 +48,4 @@ extension Post4V2 { extension Post4V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2.swift index 08f3e4b429..9106744759 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post4V2: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/AWSDataStoreIntSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/AWSDataStoreIntSortKeyTest.swift index 937ec840b0..fb800973f8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/AWSDataStoreIntSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/AWSDataStoreIntSortKeyTest.swift @@ -12,18 +12,18 @@ type Post11 @model { } */ -import Foundation -import Combine -import XCTest import AWSAPIPlugin import AWSDataStorePlugin +import Combine +import Foundation +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp #endif -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post11.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11+Schema.swift index d051df3340..90282ad891 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post11 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post11 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post11 = Post11.keys - + model.pluralName = "Post11s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post11.postId, post11.sk]) ) - + model.fields( .field(post11.postId, is: .required, ofType: .string), .field(post11.sk, is: .required, ofType: .int), @@ -38,9 +45,11 @@ extension Post11: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post11.IdentifierProtocol { - public static func identifier(postId: String, - sk: Int) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post11.IdentifierProtocol { + static func identifier( + postId: String, + sk: Int + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11.swift index 4fb976c3b9..74ceea138b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post11: Model { public let sk: Int public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: Int) { - self.init(postId: postId, + + public init( + postId: String, + sk: Int + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: Int, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: Int, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/AWSDataStoreFloatSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/AWSDataStoreFloatSortKeyTest.swift index 2f9fe125f7..f2d48a7918 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/AWSDataStoreFloatSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/AWSDataStoreFloatSortKeyTest.swift @@ -12,18 +12,18 @@ type Post12 @model { } */ -import Foundation -import Combine -import XCTest import AWSAPIPlugin import AWSDataStorePlugin +import Combine +import Foundation +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp #endif -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post12.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12+Schema.swift index f1dd5b2f65..21cafc2922 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post12 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post12 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post12 = Post12.keys - + model.pluralName = "Post12s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post12.postId, post12.sk]) ) - + model.fields( .field(post12.postId, is: .required, ofType: .string), .field(post12.sk, is: .required, ofType: .double), @@ -38,9 +45,11 @@ extension Post12: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post12.IdentifierProtocol { - public static func identifier(postId: String, - sk: Double) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post12.IdentifierProtocol { + static func identifier( + postId: String, + sk: Double + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12.swift index 672a3f78fc..b9b5b7befb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post12: Model { public let sk: Double public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: Double) { - self.init(postId: postId, + + public init( + postId: String, + sk: Double + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: Double, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: Double, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/AWSDataStoreDateTimeSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/AWSDataStoreDateTimeSortKeyTest.swift index 3d3e3704c9..d5612393d8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/AWSDataStoreDateTimeSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/AWSDataStoreDateTimeSortKeyTest.swift @@ -12,18 +12,18 @@ type Post13 @model { } */ -import Foundation -import Combine -import XCTest import AWSAPIPlugin import AWSDataStorePlugin +import Combine +import Foundation +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp #endif -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post13.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13+Schema.swift index 157a720fd9..6f0ba94836 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post13 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post13 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post13 = Post13.keys - + model.pluralName = "Post13s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post13.postId, post13.sk]) ) - + model.fields( .field(post13.postId, is: .required, ofType: .string), .field(post13.sk, is: .required, ofType: .dateTime), @@ -38,9 +45,11 @@ extension Post13: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post13.IdentifierProtocol { - public static func identifier(postId: String, - sk: Temporal.DateTime) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post13.IdentifierProtocol { + static func identifier( + postId: String, + sk: Temporal.DateTime + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13.swift index b889d0582d..9057b054fb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post13: Model { public let sk: Temporal.DateTime public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: Temporal.DateTime) { - self.init(postId: postId, + + public init( + postId: String, + sk: Temporal.DateTime + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: Temporal.DateTime, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: Temporal.DateTime, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/AWSDataStoreDateSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/AWSDataStoreDateSortKeyTest.swift index 61303670f0..0e66cce839 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/AWSDataStoreDateSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/AWSDataStoreDateSortKeyTest.swift @@ -12,18 +12,18 @@ type Post14 @model { } */ -import Foundation -import Combine -import XCTest import AWSAPIPlugin import AWSDataStorePlugin +import Combine +import Foundation +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp #endif -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post14.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14+Schema.swift index f77f16fbf1..133032447d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post14 = Post14.keys - + model.pluralName = "Post14s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post14.postId, post14.sk]) ) - + model.fields( .field(post14.postId, is: .required, ofType: .string), .field(post14.sk, is: .required, ofType: .date), @@ -38,9 +45,11 @@ extension Post14: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post14.IdentifierProtocol { - public static func identifier(postId: String, - sk: Temporal.Date) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post14.IdentifierProtocol { + static func identifier( + postId: String, + sk: Temporal.Date + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14.swift index 85c25dad48..f9215fcbf7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post14: Model { public let sk: Temporal.Date public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: Temporal.Date) { - self.init(postId: postId, + + public init( + postId: String, + sk: Temporal.Date + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: Temporal.Date, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: Temporal.Date, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/AWSDataStoreTimeSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/AWSDataStoreTimeSortKeyTest.swift index 54cf724cee..a028d35f06 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/AWSDataStoreTimeSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/AWSDataStoreTimeSortKeyTest.swift @@ -12,18 +12,18 @@ type Post15 @model { } */ -import Foundation -import Combine -import XCTest import AWSAPIPlugin import AWSDataStorePlugin +import Combine +import Foundation +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp #endif -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post15.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15+Schema.swift index 03789c2f36..b20e0c903c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post15 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post15 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post15 = Post15.keys - + model.pluralName = "Post15s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post15.postId, post15.sk]) ) - + model.fields( .field(post15.postId, is: .required, ofType: .string), .field(post15.sk, is: .required, ofType: .time), @@ -38,9 +45,11 @@ extension Post15: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post15.IdentifierProtocol { - public static func identifier(postId: String, - sk: Temporal.Time) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post15.IdentifierProtocol { + static func identifier( + postId: String, + sk: Temporal.Time + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15.swift index d4b1d8639c..33d9fc2da2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post15: Model { public let sk: Temporal.Time public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: Temporal.Time) { - self.init(postId: postId, + + public init( + postId: String, + sk: Temporal.Time + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: Temporal.Time, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: Temporal.Time, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/AWSDataStoreAWSURLSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/AWSDataStoreAWSURLSortKeyTest.swift index 36bc5288fa..e7785430f2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/AWSDataStoreAWSURLSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/AWSDataStoreAWSURLSortKeyTest.swift @@ -13,12 +13,12 @@ type Post16 @model { */ -import Foundation import Combine +import Foundation import XCTest @testable import Amplify -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post16.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16+Schema.swift index 1831e017d4..f4d42c8d04 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post16 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post16 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post16 = Post16.keys - + model.pluralName = "Post16s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post16.postId, post16.sk]) ) - + model.fields( .field(post16.postId, is: .required, ofType: .string), .field(post16.sk, is: .required, ofType: .string), @@ -38,9 +45,11 @@ extension Post16: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post16.IdentifierProtocol { - public static func identifier(postId: String, - sk: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post16.IdentifierProtocol { + static func identifier( + postId: String, + sk: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16.swift index b7fc048f3b..6adcd658b0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post16: Model { public let sk: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: String) { - self.init(postId: postId, + + public init( + postId: String, + sk: String + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/AWSDataStoreAWSEmailSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/AWSDataStoreAWSEmailSortKeyTest.swift index fb1a1e78c6..53b650e780 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/AWSDataStoreAWSEmailSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/AWSDataStoreAWSEmailSortKeyTest.swift @@ -13,12 +13,12 @@ type Post17 @model { */ -import Foundation import Combine +import Foundation import XCTest @testable import Amplify -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post17.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17+Schema.swift index 73d0919c9b..226608e21a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post17 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post17 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post17 = Post17.keys - + model.pluralName = "Post17s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post17.postId, post17.sk]) ) - + model.fields( .field(post17.postId, is: .required, ofType: .string), .field(post17.sk, is: .required, ofType: .string), @@ -38,9 +45,11 @@ extension Post17: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post17.IdentifierProtocol { - public static func identifier(postId: String, - sk: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post17.IdentifierProtocol { + static func identifier( + postId: String, + sk: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17.swift index 269fb145f1..cbe271bf43 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post17: Model { public let sk: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: String) { - self.init(postId: postId, + + public init( + postId: String, + sk: String + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/AWSDataStoreAWSPhoneSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/AWSDataStoreAWSPhoneSortKeyTest.swift index 895ac21f0e..33b422b510 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/AWSDataStoreAWSPhoneSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/AWSDataStoreAWSPhoneSortKeyTest.swift @@ -13,12 +13,12 @@ type Post18 @model { */ -import Foundation import Combine +import Foundation import XCTest @testable import Amplify -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post18.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18+Schema.swift index 2e55573dff..4b72dbfb87 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post18 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post18 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post18 = Post18.keys - + model.pluralName = "Post18s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post18.postId, post18.sk]) ) - + model.fields( .field(post18.postId, is: .required, ofType: .string), .field(post18.sk, is: .required, ofType: .string), @@ -38,9 +45,11 @@ extension Post18: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post18.IdentifierProtocol { - public static func identifier(postId: String, - sk: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post18.IdentifierProtocol { + static func identifier( + postId: String, + sk: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18.swift index c83ab5b693..5c42bdc6cf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post18: Model { public let sk: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: String) { - self.init(postId: postId, + + public init( + postId: String, + sk: String + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/AWSDataStoreAWSIPAddressSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/AWSDataStoreAWSIPAddressSortKeyTest.swift index 12504a06c6..065042f783 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/AWSDataStoreAWSIPAddressSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/AWSDataStoreAWSIPAddressSortKeyTest.swift @@ -13,12 +13,12 @@ type Post19 @model { */ -import Foundation import Combine +import Foundation import XCTest @testable import Amplify -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post19.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19+Schema.swift index b1ab4b2583..29d76f98f3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post19 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post19 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post19 = Post19.keys - + model.pluralName = "Post19s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post19.postId, post19.sk]) ) - + model.fields( .field(post19.postId, is: .required, ofType: .string), .field(post19.sk, is: .required, ofType: .string), @@ -38,9 +45,11 @@ extension Post19: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post19.IdentifierProtocol { - public static func identifier(postId: String, - sk: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post19.IdentifierProtocol { + static func identifier( + postId: String, + sk: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19.swift index 8b7790fcfb..5c241b8554 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post19: Model { public let sk: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: String) { - self.init(postId: postId, + + public init( + postId: String, + sk: String + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/AWSDataStoreAWSTimestampSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/AWSDataStoreAWSTimestampSortKeyTest.swift index 0fc64bcfb8..12e981f542 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/AWSDataStoreAWSTimestampSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/AWSDataStoreAWSTimestampSortKeyTest.swift @@ -13,12 +13,12 @@ type Post20 @model { */ -import Foundation import Combine +import Foundation import XCTest @testable import Amplify -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post20.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20+Schema.swift index e6085a7f89..9f6bb3cfe5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post20 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post20 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post20 = Post20.keys - + model.pluralName = "Post20s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post20.postId, post20.sk]) ) - + model.fields( .field(post20.postId, is: .required, ofType: .string), .field(post20.sk, is: .required, ofType: .int), @@ -38,9 +45,11 @@ extension Post20: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post20.IdentifierProtocol { - public static func identifier(postId: String, - sk: Int) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post20.IdentifierProtocol { + static func identifier( + postId: String, + sk: Int + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20.swift index 283f641af2..e1eb3e5b98 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post20: Model { public let sk: Int public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: Int) { - self.init(postId: postId, + + public init( + postId: String, + sk: Int + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: Int, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: Int, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/AWSDataStorePrimaryKeyPostCommentCompositeKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/AWSDataStorePrimaryKeyPostCommentCompositeKeyTest.swift index 3ecaa6d733..1972003a89 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/AWSDataStorePrimaryKeyPostCommentCompositeKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/AWSDataStorePrimaryKeyPostCommentCompositeKeyTest.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - +import Amplify import Foundation import XCTest -import Amplify /* # iOS.7. A Has-Many/Belongs-To relationship, each with a composite key @@ -35,15 +34,17 @@ final class AWSDataStorePrimaryKeyPostCommentCompositeKeyTest: AWSDataStorePrima try await assertQuerySuccess(modelType: PostWithCompositeKey.self) let parent = PostWithCompositeKey(title: "Post22") let child = CommentWithCompositeKey(content: "Comment", post: parent) - + // Mutations try await assertMutationsParentChild(parent: parent, child: child) // Child should not exists as we've deleted the parent - try await assertModelDeleted(modelType: CommentWithCompositeKey.self, - identifier: .identifier(id: child.id, content: child.content)) + try await assertModelDeleted( + modelType: CommentWithCompositeKey.self, + identifier: .identifier(id: child.id, content: child.content) + ) } - + /// - Given: a set models with a belongs-to association and composite primary keys /// - When: /// - the parent model is saved @@ -55,7 +56,7 @@ final class AWSDataStorePrimaryKeyPostCommentCompositeKeyTest: AWSDataStorePrima setup(withModels: CompositeKeyWithAssociations()) try await assertDataStoreReady() - + let post = PostWithCompositeKey(title: "title") let comment = CommentWithCompositeKey(content: "content", post: post) _ = try await Amplify.DataStore.save(post) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey+Schema.swift index e267c86f93..669e370130 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CommentWithCompositeKey { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension CommentWithCompositeKey { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let commentWithCompositeKey = CommentWithCompositeKey.keys - + model.pluralName = "CommentWithCompositeKeys" - + model.attributes( .index(fields: ["id", "content"], name: nil), .primaryKey(fields: [commentWithCompositeKey.id, commentWithCompositeKey.content]) ) - + model.fields( .field(commentWithCompositeKey.id, is: .required, ofType: .string), .field(commentWithCompositeKey.content, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension CommentWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CommentWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - content: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "content", value: content)]) +public extension CommentWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + content: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "content", value: content)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey.swift index ab7db0012a..e634f7e71a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct CommentWithCompositeKey: Model { public var post: PostWithCompositeKey? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKey? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKey? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKey? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKey? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey+Schema.swift index e7a9c5e1f4..ee14b480cc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithCompositeKey { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension PostWithCompositeKey { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let postWithCompositeKey = PostWithCompositeKey.keys - + model.pluralName = "PostWithCompositeKeys" - + model.attributes( .index(fields: ["id", "title"], name: nil), .primaryKey(fields: [postWithCompositeKey.id, postWithCompositeKey.title]) ) - + model.fields( .field(postWithCompositeKey.id, is: .required, ofType: .string), .field(postWithCompositeKey.title, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension PostWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - title: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "title", value: title)]) +public extension PostWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + title: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "title", value: title)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey.swift index e9de7de986..ac441cae5d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithCompositeKey: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/AWSDataStoreCompositeSortKeyIdentifierTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/AWSDataStoreCompositeSortKeyIdentifierTest.swift index f107bc47bf..644b19e428 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/AWSDataStoreCompositeSortKeyIdentifierTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/AWSDataStoreCompositeSortKeyIdentifierTest.swift @@ -5,18 +5,17 @@ // SPDX-License-Identifier: Apache-2.0 // - -import XCTest -import Combine import AWSAPIPlugin import AWSDataStorePlugin +import Combine +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp #endif -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post9.self) ModelRegistry.register(modelType: Comment9.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9+Schema.swift index 3833a860c3..3a55bfcf85 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment9 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment9 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case commentId case postId case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment9 = Comment9.keys - + model.pluralName = "Comment9s" - + model.attributes( .index(fields: ["commentId", "postId"], name: nil), .index(fields: ["postId"], name: "byPost9"), .primaryKey(fields: [comment9.commentId, comment9.postId]) ) - + model.fields( .field(comment9.commentId, is: .required, ofType: .string), .field(comment9.postId, is: .required, ofType: .string), @@ -41,9 +48,11 @@ extension Comment9: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment9.IdentifierProtocol { - public static func identifier(commentId: String, - postId: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "postId", value: postId)]) +public extension Comment9.IdentifierProtocol { + static func identifier( + commentId: String, + postId: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "postId", value: postId)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9.swift index 8082abb929..b967bd4c0c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Comment9: Model { public var content: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(commentId: String, - postId: String, - content: String? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + postId: String, + content: String? = nil + ) { + self.init( + commentId: commentId, postId: postId, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(commentId: String, - postId: String, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + commentId: String, + postId: String, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.commentId = commentId self.postId = postId self.content = content self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9+Schema.swift index 4bf0b0c40c..dc75b370dd 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post9 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post9 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post9 = Post9.keys - + model.pluralName = "Post9s" - + model.attributes( .index(fields: ["postId"], name: nil), .primaryKey(fields: [post9.postId]) ) - + model.fields( .field(post9.postId, is: .required, ofType: .string), .field(post9.title, is: .optional, ofType: .string), @@ -40,8 +47,8 @@ extension Post9: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post9.IdentifierProtocol { - public static func identifier(postId: String) -> Self { - .make(fields:[(name: "postId", value: postId)]) +public extension Post9.IdentifierProtocol { + static func identifier(postId: String) -> Self { + .make(fields: [(name: "postId", value: postId)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9.swift index ac8e74970b..1da58b19c6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post9: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String? = nil, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String? = nil, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyBaseTest.swift index 6f22c32ed0..23087ef545 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyBaseTest.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSAPIPlugin +import AWSDataStorePlugin +import Combine import Foundation import XCTest -import Combine -import AWSDataStorePlugin -import AWSAPIPlugin #if !os(watchOS) @testable import DataStoreHostApp #endif @@ -79,7 +79,7 @@ extension AWSDataStorePrimaryKeyBaseTest { /// - modelType: model type /// - expectation: success XCTestExpectation /// - onFailure: on failure callback - func assertQuerySuccess(modelType: M.Type) async throws { + func assertQuerySuccess(modelType: (some Model).Type) async throws { let models = try await Amplify.DataStore.query(modelType) XCTAssertNotNil(models) } @@ -89,8 +89,10 @@ extension AWSDataStorePrimaryKeyBaseTest { /// - modelType: model type /// - expectation: success XCTestExpectation /// - onFailure: on failure callback - func assertModelDeleted(modelType: M.Type, - identifier: ModelIdentifier) async throws { + func assertModelDeleted( + modelType: M.Type, + identifier: ModelIdentifier + ) async throws { let model = try await Amplify.DataStore.query(modelType, byIdentifier: identifier) XCTAssertNil(model) } @@ -101,7 +103,7 @@ extension AWSDataStorePrimaryKeyBaseTest { let ready = expectation(description: "Ready") let subscriptionsEstablished = expectation(description: "Subscriptions established") let modelsSynced = expectation(description: "Models synced") - + var modelSyncedCount = 0 let dataStoreEvents = HubPayload.EventName.DataStore.self Amplify @@ -143,8 +145,8 @@ extension AWSDataStorePrimaryKeyBaseTest { /// - model: model instance saved and then deleted /// - expectations: test expectations /// - onFailure: failure callback - func assertMutations(model: M) async throws { - + func assertMutations(model: some Model & ModelIdentifiable) async throws { + let mutationSaveProcessed = expectation(description: "mutation save processed") Amplify .Hub @@ -152,7 +154,8 @@ extension AWSDataStorePrimaryKeyBaseTest { .filter { $0.eventName == HubPayload.EventName.DataStore.syncReceived } .sink { payload in guard let mutationEvent = payload.data as? MutationEvent, - mutationEvent.modelId == model.identifier else { + mutationEvent.modelId == model.identifier + else { return } @@ -177,7 +180,8 @@ extension AWSDataStorePrimaryKeyBaseTest { .filter { $0.eventName == HubPayload.EventName.DataStore.syncReceived } .sink { payload in guard let mutationEvent = payload.data as? MutationEvent, - mutationEvent.modelId == model.identifier else { + mutationEvent.modelId == model.identifier + else { return } @@ -187,7 +191,7 @@ extension AWSDataStorePrimaryKeyBaseTest { } } .store(in: &requests) - + try await Amplify.DataStore.delete(model) await fulfillment( of: [mutationDeleteProcessed], @@ -200,20 +204,22 @@ extension AWSDataStorePrimaryKeyBaseTest { /// - model: model instance saved and then deleted /// - expectations: test expectations /// - onFailure: failure callback - func assertMutationsParentChild(parent: P, - child: C, - shouldDeleteParent: Bool = true) async throws { + func assertMutationsParentChild( + parent: some Model & ModelIdentifiable, + child: some Model & ModelIdentifiable, + shouldDeleteParent: Bool = true + ) async throws { let mutationSaveProcessed = expectation(description: "mutation saved processed") mutationSaveProcessed.expectedFulfillmentCount = 2 - + Amplify .Hub .publisher(for: .dataStore) .filter { $0.eventName == HubPayload.EventName.DataStore.syncReceived } .sink { payload in guard let mutationEvent = payload.data as? MutationEvent, - mutationEvent.modelId == parent.identifier || mutationEvent.modelId == child.identifier else { + mutationEvent.modelId == parent.identifier || mutationEvent.modelId == child.identifier + else { return } @@ -226,7 +232,7 @@ extension AWSDataStorePrimaryKeyBaseTest { // save parent first _ = try await Amplify.DataStore.save(parent) - + // save child _ = try await Amplify.DataStore.save(child) @@ -235,12 +241,11 @@ extension AWSDataStorePrimaryKeyBaseTest { guard shouldDeleteParent else { return } - + try await assertDeleteMutation(parent: parent, child: child) } - - func assertDeleteMutation(parent: P, child: C) async throws { + + func assertDeleteMutation(parent: some Model & ModelIdentifiable, child: some Model & ModelIdentifiable) async throws { let mutationDeleteProcessed = expectation(description: "mutation delete processed") Amplify .Hub @@ -248,7 +253,8 @@ extension AWSDataStorePrimaryKeyBaseTest { .filter { $0.eventName == HubPayload.EventName.DataStore.syncReceived } .sink { payload in guard let mutationEvent = payload.data as? MutationEvent, - mutationEvent.modelId == parent.identifier || mutationEvent.modelId == child.identifier else { + mutationEvent.modelId == parent.identifier || mutationEvent.modelId == child.identifier + else { return } @@ -258,7 +264,7 @@ extension AWSDataStorePrimaryKeyBaseTest { } } .store(in: &requests) - + // delete parent try await Amplify.DataStore.delete(parent) await fulfillment(of: [mutationDeleteProcessed], timeout: 60) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyTests.swift index 6e367f892d..44b67a0a41 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation import XCTest -import Amplify class AWSDataStorePrimaryKeyIntegrationTests: AWSDataStorePrimaryKeyBaseTest { @@ -88,5 +88,5 @@ extension AWSDataStorePrimaryKeyIntegrationTests { } } - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStoreSortKeyBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStoreSortKeyBaseTest.swift index 1eeb5518ea..63cfc4c38c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStoreSortKeyBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStoreSortKeyBaseTest.swift @@ -5,9 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Combine +import Foundation import XCTest import AWSAPIPlugin diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/AWSDataStoreCategoryPluginFlutterIntegrationTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/AWSDataStoreCategoryPluginFlutterIntegrationTests.swift index 8ed02462c9..9d56615fe8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/AWSDataStoreCategoryPluginFlutterIntegrationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/AWSDataStoreCategoryPluginFlutterIntegrationTests.swift @@ -4,9 +4,10 @@ // // SPDX-License-Identifier: Apache-2.0 // -import XCTest + import Amplify import AWSDataStorePlugin +import XCTest class AWSDataStorePluginFlutterConfigurationTests: XCTestCase { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario1FlutterTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario1FlutterTests.swift index de1c6d6309..8a4fc2aaa4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario1FlutterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario1FlutterTests.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -34,8 +35,10 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest let project = try Project1Wrapper(team: team.model) let syncedTeamReceived = expectation(description: "received team from sync path") let syncProjectReceived = expectation(description: "received project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -103,8 +106,10 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest let expectedUpdatedProject = project.copy() as! Project1Wrapper try expectedUpdatedProject.setTeam(team: anotherTeam.model) let syncUpdatedProjectReceived = expectation(description: "received updated project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -182,7 +187,8 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let team = try saveTeam(name: "name"), - let project = try saveProject(team: team) else { + let project = try saveProject(team: team) + else { XCTFail("Could not save team and project") return } @@ -213,7 +219,8 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let team = try saveTeam(name: "name"), - let project = try saveProject(team: team) else { + let project = try saveProject(team: team) + else { XCTFail("Could not save team and project") return } @@ -240,7 +247,7 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest let queriedProjectExpect0 = queryProject(id: project.model.id) XCTAssertNotNil(queriedProjectExpect0) XCTAssertEqual(0, queriedProjectExpect0!.count) - if queriedProjectExpect0!.count == 0 { + if queriedProjectExpect0!.isEmpty { getProjectAfterDeleteCompleted.fulfill() } await fulfillment(of: [getProjectAfterDeleteCompleted], timeout: TestCommonConstants.networkTimeout) @@ -250,7 +257,8 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let team = try saveTeam(name: "name"), - let project = try saveProject(team: team) else { + let project = try saveProject(team: team) + else { XCTFail("Could not save team and project") return } @@ -334,8 +342,10 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest return TeamWrapper(model: result!) } - func saveProject(name: String = "project", - team: TeamWrapper) throws -> Project1Wrapper? { + func saveProject( + name: String = "project", + team: TeamWrapper + ) throws -> Project1Wrapper? { let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin let project = try Project1Wrapper(name: name, team: team.model) var result: FlutterSerializedModel? diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario2FlutterTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario2FlutterTests.swift index 36d7684b18..25a02a7b42 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario2FlutterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario2FlutterTests.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -36,8 +37,10 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest let project = try Project2Wrapper(name: "project1", team: team.model, teamID: team.idString()) let syncedTeamReceived = expectation(description: "received team from sync event") let syncProjectReceived = expectation(description: "received project from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -98,8 +101,10 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest try expectedUpdatedProject.setTeam(name: "project1", team: anotherTeam.model, teamID: anotherTeam.idString()) let syncUpdatedProjectReceived = expectation(description: "received updated project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -179,7 +184,8 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let team = try saveTeam(name: "name", plugin: plugin), - let project = try saveProject(teamID: team.idString(), team: team, plugin: plugin) else { + let project = try saveProject(teamID: team.idString(), team: team, plugin: plugin) + else { XCTFail("Could not save team and project") return @@ -240,7 +246,8 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let team = try saveTeam(name: "name", plugin: plugin), - let project = try saveProject(teamID: team.idString(), team: team, plugin: plugin) else { + let project = try saveProject(teamID: team.idString(), team: team, plugin: plugin) + else { XCTFail("Could not save team and project") return } @@ -275,7 +282,8 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let team = try saveTeam(name: "name", plugin: plugin), - let project = try saveProject(teamID: team.idString(), team: team, plugin: plugin) else { + let project = try saveProject(teamID: team.idString(), team: team, plugin: plugin) + else { XCTFail("Could not save team and project") return } @@ -358,9 +366,11 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest return result } - func saveProject(teamID: String, - team: TeamWrapper, - plugin: AWSDataStorePlugin) throws -> Project2Wrapper? { + func saveProject( + teamID: String, + team: TeamWrapper, + plugin: AWSDataStorePlugin + ) throws -> Project2Wrapper? { let project = try Project2Wrapper(name: name, team: team.model, teamID: teamID) var result: Project2Wrapper? let completeInvoked = expectation(description: "request completed") diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario3FlutterTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario3FlutterTests.swift index 05a9730c4e..b4f415746c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario3FlutterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario3FlutterTests.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -36,8 +37,10 @@ class DataStoreConnectionScenario3FlutterTests: SyncEngineFlutterIntegrationTest let comment = try Comment3Wrapper(postID: post.idString(), content: "content") let syncedPostReceived = expectation(description: "received post from sync event") let syncCommentReceived = expectation(description: "received comment from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -185,7 +188,8 @@ class DataStoreConnectionScenario3FlutterTests: SyncEngineFlutterIntegrationTest func savePost(id: String = UUID().uuidString, title: String, plugin: AWSDataStorePlugin) throws -> Post3Wrapper? { let post = try Post3Wrapper( id: id, - title: title) + title: title + ) var result: Post3Wrapper? let completeInvoked = expectation(description: "request completed") plugin.save(post.model, modelSchema: Post3.schema) { event in diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario4FlutterTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario4FlutterTests.swift index 93afce11cb..6bf7d178f7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario4FlutterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario4FlutterTests.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest @testable import Amplify @testable import AmplifyTestCommon diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario5FlutterTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario5FlutterTests.swift index 757cbdda17..1a9e695a52 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario5FlutterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario5FlutterTests.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest @testable import Amplify @testable import AmplifyTestCommon diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario6FlutterTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario6FlutterTests.swift index 6c9f84111a..9350a39658 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario6FlutterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario6FlutterTests.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -40,7 +41,8 @@ class DataStoreConnectionScenario6FlutterTests: SyncEngineFlutterIntegrationTest let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let blog = try saveBlog(name: "name", plugin: plugin), let post = try savePost(title: "title", blog: blog, plugin: plugin), - let comment = try saveComment(post: post, content: "content", plugin: plugin) else { + let comment = try saveComment(post: post, content: "content", plugin: plugin) + else { XCTFail("Could not create blog, post, and comment") return } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterConsecutiveUpdatesTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterConsecutiveUpdatesTests.swift index 1aac1aa85e..21181bd63a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterConsecutiveUpdatesTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterConsecutiveUpdatesTests.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import XCTest + import AWSPluginsCore +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -20,8 +21,10 @@ class DataStoreFlutterConsecutiveUpdatesTests: SyncEngineFlutterIntegrationTestB func testSaveAndImmediatelyUpdate() async throws { try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin - let newPost = try PostWrapper(title: "MyPost", - content: "This is my post.") + let newPost = try PostWrapper( + title: "MyPost", + content: "This is my post." + ) let updatedPost = newPost try updatedPost.updateRating(rating: 5) @@ -33,7 +36,8 @@ class DataStoreFlutterConsecutiveUpdatesTests: SyncEngineFlutterIntegrationTestB let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return @@ -135,17 +139,20 @@ class DataStoreFlutterConsecutiveUpdatesTests: SyncEngineFlutterIntegrationTestB func testSaveAndImmediatelyDelete() async throws { try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin - let newPost = try PostWrapper(title: "MyPost", - content: "This is my post.", - createdAt: Temporal.DateTime.now().iso8601String, - rating: 3) + let newPost = try PostWrapper( + title: "MyPost", + content: "This is my post.", + createdAt: Temporal.DateTime.now().iso8601String, + rating: 3 + ) let saveSyncReceived = expectation(description: "Received create mutation event on subscription for Post") let deleteSyncReceived = expectation(description: "Received delete mutation event on subscription for Post") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return @@ -241,10 +248,12 @@ class DataStoreFlutterConsecutiveUpdatesTests: SyncEngineFlutterIntegrationTestB try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin - let newPost = try PostWrapper(title: "MyPost", - content: "This is my post.", - createdAt: Temporal.DateTime.now().iso8601String, - rating: 3) + let newPost = try PostWrapper( + title: "MyPost", + content: "This is my post.", + createdAt: Temporal.DateTime.now().iso8601String, + rating: 3 + ) var updatedPost = newPost try updatedPost.updateRating(rating: 5) @@ -257,7 +266,8 @@ class DataStoreFlutterConsecutiveUpdatesTests: SyncEngineFlutterIntegrationTestB let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterEndToEndTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterEndToEndTests.swift index ce1a143e1e..81910c8889 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterEndToEndTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterEndToEndTests.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import XCTest + import AWSPluginsCore +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -22,12 +23,14 @@ class DataStoreEndToEndTests: SyncEngineFlutterIntegrationTestBase { let newPost = try PostWrapper( title: title, - content: "Original content from DataStoreEndToEndTests at \(date)") + content: "Original content from DataStoreEndToEndTests at \(date)" + ) let updatedPost = try PostWrapper( id: newPost.idString(), title: title, - content: "UPDATED CONTENT from DataStoreEndToEndTests at \(date)") + content: "UPDATED CONTENT from DataStoreEndToEndTests at \(date)" + ) let createReceived = expectation(description: "Create notification received") let updateReceived = expectation(description: "Update notification received") @@ -35,7 +38,8 @@ class DataStoreEndToEndTests: SyncEngineFlutterIntegrationTestBase { let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -102,7 +106,8 @@ class DataStoreEndToEndTests: SyncEngineFlutterIntegrationTestBase { let newPost = try PostWrapper( title: title, content: "Original content from DataStoreEndToEndTests at \(date)", - createdAt: date) + createdAt: date + ) let updatedPost = try PostWrapper( id: newPost.idString(), @@ -116,7 +121,8 @@ class DataStoreEndToEndTests: SyncEngineFlutterIntegrationTestBase { let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -259,11 +265,13 @@ class DataStoreEndToEndTests: SyncEngineFlutterIntegrationTestBase { let newPost = try PostWrapper( title: "This is a new post I created", content: "Original content from DataStoreEndToEndTests at \(date)", - createdAt: Temporal.DateTime.now().iso8601String) + createdAt: Temporal.DateTime.now().iso8601String + ) let createReceived = expectation(description: "Create notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterDataStoreRequestUtils.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterDataStoreRequestUtils.swift index 14af3a8385..03e3a4d431 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterDataStoreRequestUtils.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterDataStoreRequestUtils.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation public class FlutterDataStoreRequestUtils { @@ -13,8 +14,10 @@ public class FlutterDataStoreRequestUtils { 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/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterSerializedModel.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterSerializedModel.swift index e0f064c370..ea062d5236 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterSerializedModel.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterSerializedModel.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation /// `FlutterSerializedModel` assists in serializing and deserializing JSON when interacting with the amplify-ios DataStore API. /// Taken from [amplify-flutter DataStore category](https://github.com/aws-amplify/amplify-flutter/blob/main/packages/amplify_datastore/ios/Classes/types/model/FlutterSerializedModel.swift) @@ -22,7 +23,7 @@ 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"] @@ -30,9 +31,9 @@ struct FlutterSerializedModel: Model, JSONValueHolder { if case .object(var v) = modified { v["__typename"] = typeName - values = v + self.values = v } else { - values = [:] + self.values = [:] } } @@ -147,7 +148,7 @@ struct FlutterSerializedModel: Model, JSONValueHolder { private func generateSerializedData(modelSchema: ModelSchema) -> [String: Any] { var result = [String: Any]() - for(key, value) in values { + for (key, value) in values { let field = modelSchema.field(withName: key) if value == nil { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterTemporal.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterTemporal.swift index 8d852cba5e..fc4485c02e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterTemporal.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterTemporal.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify import Foundation diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Blog6Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Blog6Wrapper.swift index 1b58afcaa3..6a3c252ec5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Blog6Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Blog6Wrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Blog6 */ class Blog6Wrapper: NSCopying { @@ -21,7 +21,7 @@ class Blog6Wrapper: NSCopying { let map: [String: Any] = [ "name": name ] - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -29,19 +29,19 @@ class Blog6Wrapper: NSCopying { } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func name() -> JSONValue? { - return self.model.values["name"] + return model.values["name"] } func posts() -> JSONValue? { - return self.model.values["posts"] + return model.values["posts"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment3Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment3Wrapper.swift index c680e500ed..c3fe37bdf2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment3Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment3Wrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Comment3 */ @@ -23,11 +23,11 @@ class Comment3Wrapper: NSCopying { "postID": postID, "content": content ] - self.model = FlutterSerializedModel(id: id, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: id, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(id: String = UUID().uuidString, content: String, post: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["content": content, "team": post.toMap(modelSchema: Post3.schema)])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["content": content, "team": post.toMap(modelSchema: Post3.schema)])) } init(model: FlutterSerializedModel) { @@ -37,28 +37,28 @@ class Comment3Wrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } func setPostId(postId: String) throws { - self.model.values["postID"] = JSONValue.string(postId) + model.values["postID"] = JSONValue.string(postId) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func content() -> JSONValue? { - return self.model.values["content"] + return model.values["content"] } func postId() -> JSONValue? { - return self.model.values["postID"] + return model.values["postID"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment4Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment4Wrapper.swift index ca57fcb2cc..6597a0825d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment4Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment4Wrapper.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Comment4 */ class Comment4Wrapper: NSCopying { var model: FlutterSerializedModel init(id: String = UUID().uuidString, content: String, post: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["content": content, "post": post.toMap(modelSchema: Post4.schema)])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["content": content, "post": post.toMap(modelSchema: Post4.schema)])) } init(model: FlutterSerializedModel) { @@ -28,23 +28,23 @@ class Comment4Wrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } func setPost(post: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: self.model.id, map: try FlutterDataStoreRequestUtils.getJSONValue(["content": "content", "post": post.toMap(modelSchema: Post4.schema)])) + model = try FlutterSerializedModel(id: model.id, map: FlutterDataStoreRequestUtils.getJSONValue(["content": "content", "post": post.toMap(modelSchema: Post4.schema)])) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func post() -> JSONValue? { - return self.model.values["post"] + return model.values["post"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment6Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment6Wrapper.swift index a5c0a26f21..7cd87774a4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment6Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment6Wrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Comment6 */ class Comment6Wrapper: NSCopying { @@ -22,7 +22,7 @@ class Comment6Wrapper: NSCopying { "content": content, "post": post.toMap(modelSchema: Post6.schema) ] - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -30,18 +30,18 @@ class Comment6Wrapper: NSCopying { } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func content() -> JSONValue? { - return self.model.values["content"] + return model.values["content"] } func post() -> JSONValue? { - return self.model.values["post"] + return model.values["post"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post3Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post3Wrapper.swift index ad8b6e3c96..e9cfd95bb0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post3Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post3Wrapper.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. @@ -27,10 +27,10 @@ class Post3Wrapper: NSCopying { "title": title ] - if serializedComments.count > 0 { + if !serializedComments.isEmpty { map["comments"] = serializedComments } - self.model = FlutterSerializedModel(id: id, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: id, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -40,19 +40,19 @@ class Post3Wrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func title() -> JSONValue? { - return self.model.values["title"] + return model.values["title"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post4Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post4Wrapper.swift index a9ae659d5c..86cffa5a8e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post4Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post4Wrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Post4 */ class Post4Wrapper: NSCopying { @@ -28,10 +28,10 @@ class Post4Wrapper: NSCopying { "title": title ] - if serializedComments.count > 0 { + if !serializedComments.isEmpty { map["comments"] = serializedComments } - self.model = FlutterSerializedModel(id: id, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: id, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -41,19 +41,19 @@ class Post4Wrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func title() -> JSONValue? { - return self.model.values["title"] + return model.values["title"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post5Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post5Wrapper.swift index 44b3d51016..fa9b1afd43 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post5Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post5Wrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Post5 */ class Post5Wrapper: NSCopying { @@ -21,7 +21,7 @@ class Post5Wrapper: NSCopying { let map: [String: Any] = [ "title": title ] - self.model = FlutterSerializedModel(id: id, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: id, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -31,23 +31,23 @@ class Post5Wrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func title() -> JSONValue? { - return self.model.values["title"] + return model.values["title"] } func editors() -> JSONValue? { - return self.model.values["editors"] + return model.values["editors"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post6Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post6Wrapper.swift index 1a9951d7fe..42730f10f6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post6Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post6Wrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Post6 */ class Post6Wrapper: NSCopying { @@ -22,7 +22,7 @@ class Post6Wrapper: NSCopying { "title": title, "blog": blog.toMap(modelSchema: Blog6.schema) ] - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -32,23 +32,23 @@ class Post6Wrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func title() -> JSONValue? { - return self.model.values["title"] + return model.values["title"] } func blog() -> JSONValue? { - return self.model.values["blog"] + return model.values["blog"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostEditor5Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostEditor5Wrapper.swift index 00155aa33f..d070e93e98 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostEditor5Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostEditor5Wrapper.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: PostEditor5 */ class PostEditor5Wrapper: NSCopying { var model: FlutterSerializedModel init(post: FlutterSerializedModel, editor: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["post": post.toMap(modelSchema: Post5.schema), "editor": editor.toMap(modelSchema: User5.schema)])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["post": post.toMap(modelSchema: Post5.schema), "editor": editor.toMap(modelSchema: User5.schema)])) } init(model: FlutterSerializedModel) { @@ -26,11 +26,11 @@ class PostEditor5Wrapper: NSCopying { } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostWrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostWrapper.swift index b2a447858f..0bb22649f8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostWrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostWrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Post */ class PostWrapper: NSCopying { @@ -24,7 +24,7 @@ class PostWrapper: NSCopying { "createdAt": createdAt, "rating": rating ] - self.model = FlutterSerializedModel(id: id, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: id, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -34,7 +34,7 @@ class PostWrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } init(post: Post) throws { @@ -44,43 +44,43 @@ class PostWrapper: NSCopying { "createdAt": post.createdAt.iso8601String, "rating": post.rating ] - self.model = FlutterSerializedModel(id: post.id, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: post.id, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } func updateRating(rating: Double) throws { - var map = self.model.values + var map = model.values map["rating"] = JSONValue.init(floatLiteral: rating) - self.model = FlutterSerializedModel(id: self.model.id, map: map) + model = FlutterSerializedModel(id: model.id, map: map) } func updateStringProp(key: String, value: String) throws { - var map = self.model.values + var map = model.values map[key] = JSONValue.string(value) - self.model = FlutterSerializedModel(id: self.model.id, map: map) + model = FlutterSerializedModel(id: model.id, map: map) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func title() -> JSONValue? { - return self.model.values["title"] + return model.values["title"] } func rating() -> JSONValue? { - return self.model.values["rating"] + return model.values["rating"] } func content() -> JSONValue? { - return self.model.values["content"] + return model.values["content"] } func createdAt() -> JSONValue? { - return self.model.values["createdAt"] + return model.values["createdAt"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project1Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project1Wrapper.swift index c01e59f9a8..112d7d5df2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project1Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project1Wrapper.swift @@ -5,24 +5,24 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Project1 */ class Project1Wrapper: NSCopying { var model: FlutterSerializedModel init(team: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["team": team.toMap(modelSchema: Team1.schema)])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["team": team.toMap(modelSchema: Team1.schema)])) } init(name: String, team: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["name": name, "team": team.toMap(modelSchema: Team1.schema)])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["name": name, "team": team.toMap(modelSchema: Team1.schema)])) } init(model: FlutterSerializedModel) { @@ -30,23 +30,23 @@ class Project1Wrapper: NSCopying { } func setTeam(team: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: self.model.id, map: try FlutterDataStoreRequestUtils.getJSONValue(["team": team.toMap(modelSchema: Team1.schema)])) + model = try FlutterSerializedModel(id: model.id, map: FlutterDataStoreRequestUtils.getJSONValue(["team": team.toMap(modelSchema: Team1.schema)])) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func teamId() -> JSONValue? { - return self.model.values["team"]!["id"] + return model.values["team"]!["id"] } func teamName() -> JSONValue? { - return self.model.values["team"]!["name"] + return model.values["team"]!["name"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project2Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project2Wrapper.swift index a5f11f0928..5ee758da52 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project2Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project2Wrapper.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Project2 */ class Project2Wrapper: NSCopying { var model: FlutterSerializedModel init(name: String, team: FlutterSerializedModel, teamID: String) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["name": name, "team": team.toMap(modelSchema: Team2.schema), "teamID": teamID])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["name": name, "team": team.toMap(modelSchema: Team2.schema), "teamID": teamID])) } init(model: FlutterSerializedModel) { @@ -26,23 +26,23 @@ class Project2Wrapper: NSCopying { } func setTeam(name: String, team: FlutterSerializedModel, teamID: String) throws { - self.model = FlutterSerializedModel(id: self.model.id, map: try FlutterDataStoreRequestUtils.getJSONValue(["name": name, "team": team.toMap(modelSchema: Team2.schema), "teamID": teamID])) + model = try FlutterSerializedModel(id: model.id, map: FlutterDataStoreRequestUtils.getJSONValue(["name": name, "team": team.toMap(modelSchema: Team2.schema), "teamID": teamID])) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func teamID() -> JSONValue? { - return self.model.values["teamID"] + return model.values["teamID"] } func teamName() -> JSONValue? { - return self.model.values["team"]!["name"] + return model.values["team"]!["name"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/TeamWrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/TeamWrapper.swift index 167cb918b3..cbb2790907 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/TeamWrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/TeamWrapper.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Team1 and Team 2 */ class TeamWrapper: NSCopying { var model: FlutterSerializedModel init(name: String) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["name": name])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["name": name])) } init(model: FlutterSerializedModel) { @@ -26,15 +26,15 @@ class TeamWrapper: NSCopying { } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func teamName() -> JSONValue? { - return self.model.values["name"] + return model.values["name"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/User5Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/User5Wrapper.swift index af8e5e097a..79c5f9e928 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/User5Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/User5Wrapper.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: User5 */ class User5Wrapper: NSCopying { var model: FlutterSerializedModel init(id: String, username: String) throws { - self.model = FlutterSerializedModel(id: id, map: try FlutterDataStoreRequestUtils.getJSONValue(["username": username])) + self.model = try FlutterSerializedModel(id: id, map: FlutterDataStoreRequestUtils.getJSONValue(["username": username])) } init(model: FlutterSerializedModel) { @@ -26,15 +26,15 @@ class User5Wrapper: NSCopying { } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func username() -> JSONValue? { - return self.model.values["username"] + return model.values["username"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SyncEngineFlutterIntegrationTestBase.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SyncEngineFlutterIntegrationTestBase.swift index b60c5bdef7..e02112129e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SyncEngineFlutterIntegrationTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SyncEngineFlutterIntegrationTestBase.swift @@ -4,11 +4,12 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest -@testable import DataStoreHostApp @testable import Amplify @testable import AmplifyTestCommon @testable import AWSDataStorePlugin +@testable import DataStoreHostApp class SyncEngineFlutterIntegrationTestBase: XCTestCase { @@ -67,8 +68,10 @@ class SyncEngineFlutterIntegrationTestBase: XCTestCase { let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin var token: UnsubscribeToken! - token = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncStarted) { _ in + token = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncStarted + ) { _ in syncStarted.fulfill() Amplify.Hub.removeListener(token) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/TestFlutterModelRegistration.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/TestFlutterModelRegistration.swift index 3ca55b63cf..4583c39059 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/TestFlutterModelRegistration.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/TestFlutterModelRegistration.swift @@ -4,14 +4,15 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify import AmplifyTestCommon struct TestFlutterModelRegistration: AmplifyModelRegistration { var version: String = "1" - private let decoder: (String, JSONDecoder?) throws -> Model = { (jsonString, decoder) -> Model in + private let decoder: (String, JSONDecoder?) throws -> Model = { jsonString, decoder -> Model in let resolvedDecoder: JSONDecoder - if let decoder = decoder { + if let decoder { resolvedDecoder = decoder } else { resolvedDecoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy) @@ -26,7 +27,8 @@ struct TestFlutterModelRegistration: AmplifyModelRegistration { return model } throw DataStoreError.decodingError( - "Error in decoding \(jsonString)", "Please create an issue to amplify-flutter repo.") + "Error in decoding \(jsonString)", "Please create an issue to amplify-flutter repo." + ) } func registerModels(registry: ModelRegistry.Type) { registry.register(modelType: Post.self, modelSchema: Post.schema, jsonDecoder: decoder) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/AWSDataStorePluginConfigurationTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/AWSDataStorePluginConfigurationTests.swift index 1166319a9c..8600ec314b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/AWSDataStorePluginConfigurationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/AWSDataStorePluginConfigurationTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSDataStorePlugin import XCTest @testable import Amplify -import AWSDataStorePlugin class AWSDataStorePluginConfigurationTests: XCTestCase { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests+WatchOS.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests+WatchOS.swift index c2c3aeafb7..69b5e04186 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests+WatchOS.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests+WatchOS.swift @@ -8,24 +8,30 @@ import Foundation extension DataStoreConnectionScenario1Tests { - + #if os(watchOS) func testStartAndSync() async throws { - await setUp(withModels: TestModelRegistration(), - dataStoreConfiguration: .custom(syncMaxRecords: 100, disableSubscriptions: { true })) + await setUp( + withModels: TestModelRegistration(), + dataStoreConfiguration: .custom(syncMaxRecords: 100, disableSubscriptions: { true }) + ) try await startAmplifyAndWaitForSync() } func testSaveReconciled() async throws { - await setUp(withModels: TestModelRegistration(), - dataStoreConfiguration: .custom(syncMaxRecords: 100, disableSubscriptions: { true })) + await setUp( + withModels: TestModelRegistration(), + dataStoreConfiguration: .custom(syncMaxRecords: 100, disableSubscriptions: { true }) + ) try await startAmplifyAndWaitForSync() - + let team = Team1(name: "name1") let project = Project1(team: team) let syncedTeamReceived = expectation(description: "received team from sync path") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -43,10 +49,12 @@ extension DataStoreConnectionScenario1Tests { _ = try await Amplify.DataStore.save(team) await fulfillment(of: [syncedTeamReceived], timeout: networkTimeout) - + let syncProjectReceived = expectation(description: "received project from sync path") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -73,5 +81,5 @@ extension DataStoreConnectionScenario1Tests { XCTAssertEqual(queriedProject.team, team) } #endif - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests.swift index 49c5fb097e..46b8016f94 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests.swift @@ -32,24 +32,26 @@ import XCTest */ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { - + struct TestModelRegistration: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { registry.register(modelType: Team1.self) registry.register(modelType: Project1.self) } - + let version: String = "1" } - + func testSaveTeamAndProjectSyncToCloud() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() let team = Team1(name: "name1") let project = Project1(team: team) let syncedTeamReceived = expectation(description: "received team from sync path") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -67,10 +69,12 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { _ = try await Amplify.DataStore.save(team) await fulfillment(of: [syncedTeamReceived], timeout: networkTimeout) - + let syncProjectReceived = expectation(description: "received project from sync path") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -110,8 +114,10 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { _ = try await Amplify.DataStore.save(project) let syncUpdatedProjectReceived = expectation(description: "received updated project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -129,7 +135,7 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { project.team = anotherTeam _ = try await Amplify.DataStore.save(project) await fulfillment(of: [syncUpdatedProjectReceived], timeout: networkTimeout) - + let queriedProjectOptional = try await Amplify.DataStore.query(Project1.self, byId: project.id) XCTAssertNotNil(queriedProjectOptional) if let queriedProject = queriedProjectOptional { @@ -141,14 +147,16 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { func testDeleteAndGetProjectReturnsNilWithSync() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team1(name: "name") let project = Project1(team: team) - + let createReceived = expectation(description: "received created items from cloud") createReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -172,15 +180,17 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let deleteReceived = expectation(description: "Delete notification received") deleteReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -220,9 +230,9 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { let project = Project1(team: team) _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + _ = try await Amplify.DataStore.delete(project, where: Project1.keys.team.eq(team.id)) - + let queriedProject = try await Amplify.DataStore.query(Project1.self, byId: project.id) XCTAssertNil(queriedProject) } @@ -258,7 +268,7 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { let project = Project1(team: team) _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + let predicate = Project1.keys.team.eq(team.id) let projects = try await Amplify.DataStore.query(Project1.self, where: predicate) XCTAssertEqual(projects.count, 1) @@ -268,8 +278,10 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { } extension Team1: Equatable { - public static func == (lhs: Team1, - rhs: Team1) -> Bool { + public static func == ( + lhs: Team1, + rhs: Team1 + ) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario2Tests.swift index 820b191aaf..f36fd0149f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario2Tests.swift @@ -50,8 +50,10 @@ class DataStoreConnectionScenario2Tests: SyncEngineIntegrationTestBase { let project = Project2(teamID: team.id, team: team) let syncedTeamReceived = expectation(description: "received team from sync event") let syncProjectReceived = expectation(description: "received project from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -72,7 +74,7 @@ class DataStoreConnectionScenario2Tests: SyncEngineIntegrationTestBase { _ = try await Amplify.DataStore.save(team) await fulfillment(of: [syncedTeamReceived], timeout: networkTimeout) - + _ = try await Amplify.DataStore.save(project) await fulfillment(of: [syncProjectReceived], timeout: networkTimeout) @@ -89,8 +91,10 @@ class DataStoreConnectionScenario2Tests: SyncEngineIntegrationTestBase { var project = Project2(teamID: team.id, team: team) let expectedUpdatedProject = Project2(id: project.id, name: project.name, teamID: anotherTeam.id) let syncUpdatedProjectReceived = expectation(description: "received updated project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -132,8 +136,10 @@ class DataStoreConnectionScenario2Tests: SyncEngineIntegrationTestBase { createReceived.expectedFulfillmentCount = 2 // 1 project and 1 team let deleteReceived = expectation(description: "Delete notification received") deleteReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -202,7 +208,7 @@ class DataStoreConnectionScenario2Tests: SyncEngineIntegrationTestBase { return } } - + let project2 = try await Amplify.DataStore.query(Project2.self, byId: project.id) XCTAssertNotNil(project2) } @@ -235,18 +241,22 @@ class DataStoreConnectionScenario2Tests: SyncEngineIntegrationTestBase { return try await Amplify.DataStore.save(team) } - func saveProject(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2? = nil) async throws -> Project2 { + func saveProject( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2? = nil + ) async throws -> Project2 { let project = Project2(id: id, name: name, teamID: teamID, team: team) return try await Amplify.DataStore.save(project) } } extension Team2: Equatable { - public static func == (lhs: Team2, - rhs: Team2) -> Bool { + public static func == ( + lhs: Team2, + rhs: Team2 + ) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario3Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario3Tests.swift index 15fc8f9d1f..5b57f45ed9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario3Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario3Tests.swift @@ -50,8 +50,10 @@ class DataStoreConnectionScenario3Tests: SyncEngineIntegrationTestBase { let comment = Comment3(postID: post.id, content: "content") let syncedPostReceived = expectation(description: "received post from sync event") let syncCommentReceived = expectation(description: "received comment from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -73,7 +75,7 @@ class DataStoreConnectionScenario3Tests: SyncEngineIntegrationTestBase { await fulfillment(of: [syncedPostReceived], timeout: networkTimeout) _ = try await Amplify.DataStore.save(comment) await fulfillment(of: [syncCommentReceived], timeout: networkTimeout) - + let queriedComment = try await Amplify.DataStore.query(Comment3.self, byId: comment.id) XCTAssertEqual(queriedComment, comment) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario4Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario4Tests.swift index 864a870bf9..0eb828c579 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario4Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario4Tests.swift @@ -107,7 +107,7 @@ class DataStoreConnectionScenario4Tests: SyncEngineIntegrationTestBase { let queriedComments = try await Amplify.DataStore.query(Comment4.self, where: predicate) XCTAssertEqual(queriedComments.count, 1) } - + func savePost(id: String = UUID().uuidString, title: String) async throws -> Post4 { let post = Post4(id: id, title: title) return try await Amplify.DataStore.save(post) @@ -120,8 +120,10 @@ class DataStoreConnectionScenario4Tests: SyncEngineIntegrationTestBase { } extension Post4: Equatable { - public static func == (lhs: Post4, - rhs: Post4) -> Bool { + public static func == ( + lhs: Post4, + rhs: Post4 + ) -> Bool { return lhs.id == rhs.id && lhs.title == rhs.title } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario5Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario5Tests.swift index 416db4b75f..a408e7fd35 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario5Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario5Tests.swift @@ -101,7 +101,7 @@ class DataStoreConnectionScenario5Tests: SyncEngineIntegrationTestBase { let post = try await savePost(title: "title") let user = try await saveUser(username: "username") _ = try await savePostEditor(post: post, editor: user) - + let queriedUserOptional = try await Amplify.DataStore.query(User5.self, byId: user.id) guard let queriedUser = queriedUserOptional else { XCTFail("Missing queried user") diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario6Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario6Tests.swift index 23158fdfa9..de6accc50e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario6Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario6Tests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Combine +import XCTest @testable import Amplify @testable import AWSDataStorePlugin #if !os(watchOS) @@ -73,7 +73,7 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { } try await posts.fetch() XCTAssertEqual(posts.count, 2) - guard let fetchedPost = posts.first(where: { (post) -> Bool in + guard let fetchedPost = posts.first(where: { post -> Bool in post.id == post1.id }), let comments = fetchedPost.comments else { XCTFail("Could not set up - failed to get a post and its comments") @@ -81,10 +81,10 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { } try await comments.fetch() XCTAssertEqual(comments.count, 2) - XCTAssertTrue(comments.contains(where: { (comment) -> Bool in + XCTAssertTrue(comments.contains(where: { comment -> Bool in comment.id == comment1post1.id })) - XCTAssertTrue(comments.contains(where: { (comment) -> Bool in + XCTAssertTrue(comments.contains(where: { comment -> Bool in comment.id == comment2post1.id })) if let post = comments[0].post, let comments = post.comments { @@ -147,7 +147,7 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { if let postsInEagerlyLoadedBlog = eagerlyLoadedBlog.posts { try await postsInEagerlyLoadedBlog.fetch() XCTAssertEqual(postsInEagerlyLoadedBlog.count, 1) - XCTAssertTrue(postsInEagerlyLoadedBlog.contains(where: {(postIn) -> Bool in + XCTAssertTrue(postsInEagerlyLoadedBlog.contains(where: {postIn -> Bool in postIn.id == post.id })) XCTAssertEqual(postsInEagerlyLoadedBlog[0].id, post.id) @@ -183,7 +183,7 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { remoteEventReceived.expectedFulfillmentCount = 2 let commentId1 = UUID().uuidString let commentId2 = UUID().uuidString - + let task = Task { let mutationEvents = Amplify.DataStore.observe(Comment6.self) do { @@ -199,7 +199,7 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { XCTFail("Failed \(error)") } } - + let blog = try await saveBlog(name: "name") let post = try await savePost(title: "title", blog: blog) _ = try await saveComment(id: commentId1, post: post, content: "content") @@ -229,7 +229,7 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { model.id == commentId1 || model.id == commentId2 { processedSoFar += 1 } - + Amplify.Logging.verbose("Processed so far \(processedSoFar)/6") if processedSoFar == 6 { outboxMutationProcessed.fulfill() @@ -238,9 +238,9 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { break } }.store(in: &cancellables) - + try await Amplify.DataStore.delete(Blog6.self, where: QueryPredicateConstant.all) - + await fulfillment(of: [outboxMutationProcessed], timeout: 30) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreConsecutiveUpdatesTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreConsecutiveUpdatesTests.swift index eb21319b2e..9328f10c27 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreConsecutiveUpdatesTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreConsecutiveUpdatesTests.swift @@ -34,11 +34,13 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let newPost = Post(title: "MyPost", - content: "This is my post.", - createdAt: .now(), - rating: 3, - status: .published) + let newPost = Post( + title: "MyPost", + content: "This is my post.", + createdAt: .now(), + rating: 3, + status: .published + ) var updatedPost = newPost updatedPost.rating = 5 @@ -49,7 +51,8 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return @@ -98,7 +101,7 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { XCTFail("Failed to get data") return } - + XCTAssertEqual(post.model["title"] as? String, updatedPost.title) XCTAssertEqual(post.model["content"] as? String, updatedPost.content) XCTAssertEqual(post.model["rating"] as? Double, updatedPost.rating) @@ -115,17 +118,20 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let newPost = Post(title: "MyPost", - content: "This is my post.", - createdAt: .now(), - rating: 3, - status: .published) + let newPost = Post( + title: "MyPost", + content: "This is my post.", + createdAt: .now(), + rating: 3, + status: .published + ) let deleteSyncReceived = expectation(description: "Received delete mutation event on subscription for Post") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return @@ -173,7 +179,7 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { XCTFail("Failed to get data") return } - + XCTAssertEqual(post.model["title"] as? String, newPost.title) XCTAssertEqual(post.model["content"] as? String, newPost.content) XCTAssertEqual(post.model["rating"] as? Double, newPost.rating) @@ -191,11 +197,13 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let newPost = Post(title: "MyPost", - content: "This is my post.", - createdAt: .now(), - rating: 3, - status: .published) + let newPost = Post( + title: "MyPost", + content: "This is my post.", + createdAt: .now(), + rating: 3, + status: .published + ) var updatedPost = newPost updatedPost.rating = 5 @@ -279,11 +287,13 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let newPost = Post(title: "MyPost", - content: "This is my post.", - createdAt: .now(), - rating: 3, - status: .published) + let newPost = Post( + title: "MyPost", + content: "This is my post.", + createdAt: .now(), + rating: 3, + status: .published + ) var updatedPost = newPost let updatedPostDefaultTitle = "MyUpdatedPost" let updateCount = 10 @@ -293,7 +303,8 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return @@ -348,7 +359,7 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { XCTFail("Failed to get data") return } - + XCTAssertEqual(post.model["title"] as? String, updatedPost.title) XCTAssertEqual(post.model["content"] as? String, updatedPost.content) XCTAssertEqual(post.model["rating"] as? Double, updatedPost.rating) @@ -360,7 +371,7 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { XCTFail("Error: \(error)") } } - + func queryPost(byId id: String) async throws -> Post? { return try await Amplify.DataStore.query(Post.self, byId: id) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreCustomPrimaryKeyTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreCustomPrimaryKeyTests.swift index 1c89de647a..2728af6467 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreCustomPrimaryKeyTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreCustomPrimaryKeyTests.swift @@ -42,7 +42,8 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { updatedCustomerOrder.email = "testnew@abc.com" var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -50,7 +51,8 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { } guard let order = try? mutationEvent.decodeModel() as? CustomerOrder, - order.id == customerOrder.id else { + order.id == customerOrder.id + else { return } @@ -75,7 +77,8 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { let updateReceived = expectation(description: "Update notification received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -83,11 +86,12 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { } guard let order = try? mutationEvent.decodeModel() as? CustomerOrder, - order.id == customerOrder.id else { + order.id == customerOrder.id + else { return } - + if mutationEvent.mutationType == GraphQLMutationType.update.rawValue { XCTAssertEqual(order.email, updatedCustomerOrder.email) XCTAssertEqual(order.orderId, updatedCustomerOrder.orderId) @@ -113,12 +117,13 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { XCTAssertEqual(order.id, updatedCustomerOrder.id) XCTAssertEqual(order.orderId, updatedCustomerOrder.orderId) XCTAssertEqual(order.email, updatedCustomerOrder.email) - + // delete the customer order let deleteReceived = expectation(description: "Delete notification received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -126,7 +131,8 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { } guard let order = try? mutationEvent.decodeModel() as? CustomerOrder, - order.id == customerOrder.id else { + order.id == customerOrder.id + else { return } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreEndToEndTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreEndToEndTests.swift index a23a537dd1..86b609a06f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreEndToEndTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreEndToEndTests.swift @@ -35,7 +35,7 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { XCTFail("Error \(error)") } } - + func testCreate() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForReady() @@ -44,7 +44,8 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let newPost = Post( title: "This is a new post I created", content: "Original content from DataStoreEndToEndTests at \(date)", - createdAt: date) + createdAt: date + ) let outboxMutationEnqueued = expectation(description: "received OutboxMutationEnqueuedEvent") outboxMutationEnqueued.assertForOverFulfill = false @@ -127,7 +128,8 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let newPost = Post( title: "This is a new post I created", content: "Original content from DataStoreEndToEndTests at \(date)", - createdAt: date) + createdAt: date + ) var updatedPost = newPost updatedPost.content = "UPDATED CONTENT from DataStoreEndToEndTests at \(Date())" @@ -135,7 +137,8 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let createReceived = expectation(description: "Create notification received") var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -166,7 +169,8 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let updateReceived = expectation(description: "Update notification received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -192,11 +196,12 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { } _ = try await Amplify.DataStore.save(updatedPost) await fulfillment(of: [updateReceived], timeout: networkTimeout) - + let deleteReceived = expectation(description: "Delete notification received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -238,14 +243,16 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let newPost = Post( title: title, content: "Original content from DataStoreEndToEndTests at \(date)", - createdAt: date) + createdAt: date + ) var updatedPost = newPost updatedPost.content = "UPDATED CONTENT from DataStoreEndToEndTests at \(Date())" let createReceived = expectation(description: "Create notification received") var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -271,11 +278,12 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { } _ = try await Amplify.DataStore.save(newPost) await fulfillment(of: [createReceived], timeout: networkTimeout) - + let updateReceived = expectation(description: "Update notification received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -320,7 +328,8 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let newPost = Post( title: title, content: "Original content from DataStoreEndToEndTests at \(date.iso8601String)", - createdAt: date) + createdAt: date + ) var updatedPost = newPost updatedPost.content = "UPDATED CONTENT from DataStoreEndToEndTests at \(Date())" @@ -358,7 +367,7 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { _ = try await Amplify.DataStore.save(newPost) await fulfillment(of: [createReceived], timeout: networkTimeout) - + let updateLocalSuccess = expectation(description: "Update local successful") storageAdapter.save(updatedPost) { result in switch result { @@ -397,7 +406,7 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(updatedPost, where: post.content == updatedPost.content) await fulfillment(of: [conditionalReceived], timeout: networkTimeout) @@ -419,7 +428,7 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { try await Amplify.DataStore.start() try await validateSavePost() } - + /// Ensure DataStore.stop followed by DataStore.start is successful /// /// - Given: DataStore has just configured, but not yet started @@ -542,12 +551,11 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let newPost = Post(title: UUID().uuidString, content: UUID().uuidString, createdAt: .now()) let titlePrefix = UUID().uuidString - let posts = (0..() let extractPost: (DataStoreHubEvent) -> Post? = { if case .outboxMutationProcessed(let mutationEvent) = $0, - mutationEvent.modelName == Post.modelName - { + mutationEvent.modelName == Post.modelName { return mutationEvent.element.model as? Post } return nil @@ -661,11 +669,13 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let newPost = Post( title: "This is a new post I created", content: "Original content from DataStoreEndToEndTests at \(date)", - createdAt: date) + createdAt: date + ) let createReceived = expectation(description: "Create notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -692,7 +702,7 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { } _ = try await Amplify.DataStore.save(newPost) - + await fulfillment(of: [createReceived], timeout: networkTimeout) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreHubEventsTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreHubEventsTests.swift index a5fe3115f4..b68ca9615b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreHubEventsTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreHubEventsTests.swift @@ -170,7 +170,8 @@ class DataStoreHubEventTests: HubEventsIntegrationTestBase { if modelSyncedEvents.count == 2 { guard let postModelSyncedEvent = modelSyncedEvents.first(where: { $0.modelName == "Post" }), - let commentModelSyncedEvent = modelSyncedEvents.first(where: { $0.modelName == "Comment" }) else { + let commentModelSyncedEvent = modelSyncedEvents.first(where: { $0.modelName == "Comment" }) + else { XCTFail("Could not get modelSyncedEvent for Post and Comment") return } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreLargeNumberModelsSubscriptionTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreLargeNumberModelsSubscriptionTests.swift index 4121f562bd..d18f61b52e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreLargeNumberModelsSubscriptionTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreLargeNumberModelsSubscriptionTests.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - -import XCTest -import Combine import Amplify +import Combine +import XCTest @testable import AWSAPIPlugin class DataStoreLargeNumberModelsSubscriptionTests: SyncEngineIntegrationTestBase { @@ -56,8 +55,8 @@ class DataStoreLargeNumberModelsSubscriptionTests: SyncEngineIntegrationTestBase let repeatCount = 5 await setUp(withModels: TestModelRegistration()) try startAmplify() - - for _ in 0..() - + struct TestModelRegistration: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { registry.register(modelType: Post.self) @@ -61,8 +61,10 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { querySnapshotsCancelled.fulfill() } let receivedPost = expectation(description: "received Post") - try await savePostAndWaitForSync(Post(title: "title", content: "content", createdAt: .now()), - postSyncedExpctation: receivedPost) + try await savePostAndWaitForSync( + Post(title: "title", content: "content", createdAt: .now()), + postSyncedExpctation: receivedPost + ) await fulfillment(of: [snapshotWithIsSynced], timeout: 100) task.cancel() await fulfillment(of: [querySnapshotsCancelled], timeout: 10) @@ -108,7 +110,7 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { postSyncedExpctation: receivedPost ) await fulfillment(of: [snapshotWithIsSynced], timeout: 100) - + XCTAssertTrue(snapshots.count >= 2) XCTAssertFalse(snapshots[0].isSynced) } @@ -151,7 +153,7 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { } }.store(in: &cancellables) await fulfillment(of: [observeQueryReadyForTest], timeout: 100) - + _ = try await Amplify.DataStore.save(post) await fulfillment(of: [snapshotWithPost], timeout: 100) } @@ -175,7 +177,8 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { modelPredicate: { Post.keys.createdAt.ge(startTime) } ) ], - disableSubscriptions: { false }) + disableSubscriptions: { false } + ) #else let configuration: DataStoreConfiguration = .custom( syncMaxRecords: 100, @@ -184,7 +187,8 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { modelSchema: Post.schema, modelPredicate: { Post.keys.createdAt.ge(startTime) } ) - ]) + ] + ) #endif await setUp( withModels: TestModelRegistration(), @@ -223,19 +227,18 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { snapshotWithIsSynced.fulfill() } else if snapshotWithIsSyncedFulfilled { if querySnapshot.items.count >= 4 - && querySnapshot.items.allSatisfy({ $0.title.contains(randomTitle)}) - { + && querySnapshot.items.allSatisfy({ $0.title.contains(randomTitle)}) { receivedPostFromObserveQuery.fulfill() } } - + }.store(in: &cancellables) await fulfillment(of: [snapshotWithIsSynced], timeout: 100) try await savePostAndWaitForSync(post4) await fulfillment(of: [receivedPostFromObserveQuery], timeout: 100) - + XCTAssertTrue(snapshots.count >= 2) } @@ -315,8 +318,10 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { } }.store(in: &cancellables) let receivedPost = expectation(description: "received Post") - try await savePostAndWaitForSync(Post(title: "title", content: "content", createdAt: .now()), - postSyncedExpctation: receivedPost) + try await savePostAndWaitForSync( + Post(title: "title", content: "content", createdAt: .now()), + postSyncedExpctation: receivedPost + ) await fulfillment(of: [snapshotWithIsSynced], timeout: 30) XCTAssertTrue(snapshots.count >= 2) XCTAssertFalse(snapshots[0].isSynced) @@ -360,8 +365,10 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { let newPost = Post(title: "title", content: "content", createdAt: .now()) let receivedPost = expectation(description: "received Post") - try await savePostAndWaitForSync(newPost, - postSyncedExpctation: receivedPost) + try await savePostAndWaitForSync( + newPost, + postSyncedExpctation: receivedPost + ) await fulfillment(of: [snapshotWithIsSynced], timeout: 30) XCTAssertTrue(snapshots.count >= 2) @@ -445,13 +452,13 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { } }.store(in: &cancellables) await fulfillment(of: [snapshotExpectation1], timeout: 10) - + // (1) Add model that matches predicate - should be received on the snapshot let postMatchPredicate = Post(title: "xyz 1", content: testId, createdAt: .now()) - + try await savePostAndWaitForSync(postMatchPredicate) await fulfillment(of: [snapshotExpectation23], timeout: 10) - + // (2) Add model that does not match predicate - should not be received on the snapshot // (3) Update model that used to match the predicate to no longer match - should be removed from snapshot let postDoesNotMatch = Post(title: "doesNotMatch", content: testId, createdAt: .now()) @@ -461,21 +468,23 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { postMatchPredicateNoLongerMatches.title = "doesNotMatch" try await savePostAndWaitForSync(postMatchPredicateNoLongerMatches) await fulfillment(of: [snapshotExpectation4], timeout: 10) - + // (4) Update model that does not match predicate to match - should be added to snapshot var postDoesNotMatchNowMatches = postDoesNotMatch postDoesNotMatchNowMatches.title = "xyz 2" try await savePostAndWaitForSync(postDoesNotMatchNowMatches) await fulfillment(of: [snapshotExpectation56], timeout: 10) - + // (5) Delete the model that matches the predicate - should be removed try await deletePostAndWaitForSync(postDoesNotMatchNowMatches) await fulfillment(of: [snapshotExpectation7], timeout: 10) - + // (6) Delete the model that does not match predicate - should have no snapshot emitted let postMatchPredicateNoLongerMatchesExpectation = expectation(description: " received") - try await deletePostAndWaitForSync(postMatchPredicateNoLongerMatches, - postSyncedExpctation: postMatchPredicateNoLongerMatchesExpectation) + try await deletePostAndWaitForSync( + postMatchPredicateNoLongerMatches, + postSyncedExpctation: postMatchPredicateNoLongerMatchesExpectation + ) // Save "xyz 3" to force a snapshot to be emitted try await savePostAndWaitForSync(Post(title: "xyz 3", content: testId, createdAt: .now())) @@ -501,9 +510,11 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { var snapshotCount = 0 let observeQueryReadyForTest = expectation(description: "observeQuery initial query completed") let allSnapshotsReceived = expectation(description: "query snapshots received") - let sink = Amplify.Publisher.create(Amplify.DataStore.observeQuery(for: Post.self, - where: Post.keys.content == testId, - sort: .ascending(Post.keys.title))) + let sink = Amplify.Publisher.create(Amplify.DataStore.observeQuery( + for: Post.self, + where: Post.keys.content == testId, + sort: .ascending(Post.keys.title) + )) .sink { completed in switch completed { case .finished: @@ -607,7 +618,7 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { } }.store(in: &cancellables) await fulfillment(of: [firstSnapshotWithIsSynced], timeout: 10) - + let observeQueryReceivedCompleted = expectation(description: "observeQuery received completed") observeQueryReceivedCompleted.isInverted = true onComplete = { completed in @@ -642,7 +653,7 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { } }.store(in: &cancellables) await fulfillment(of: [firstSnapshotWithIsSynced], timeout: 100) - + let observeQueryReceivedCompleted = expectation(description: "observeQuery received completed") observeQueryReceivedCompleted.isInverted = true onComplete = { completed in @@ -711,7 +722,7 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { XCTFail("Failed \(error)") } } - + _ = try await Amplify.DataStore.save(post) await fulfillment(of: [receivedPost], timeout: 100) } @@ -738,7 +749,7 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { XCTFail("Failed \(error)") } } - + _ = try await Amplify.DataStore.delete(post) await fulfillment(of: [deletedPost], timeout: 100) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreScalarTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreScalarTests.swift index e24629883f..8e04331ba3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreScalarTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreScalarTests.swift @@ -27,19 +27,21 @@ class DataStoreScalarTests: SyncEngineIntegrationTestBase { func testScalarContainer() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let container = ScalarContainer(myString: "myString", - myInt: 1, - myDouble: 1.0, - myBool: true, - myDate: .now(), - myTime: .now(), - myDateTime: .now(), - myTimeStamp: 123, - myEmail: "local-part@domain-part", - myJSON: "{}", - myPhone: "2342355678", - myURL: "https://www.amazon.com/dp/B000NZW3KC/", - myIPAddress: "123.12.34.56") + let container = ScalarContainer( + myString: "myString", + myInt: 1, + myDouble: 1.0, + myBool: true, + myDate: .now(), + myTime: .now(), + myDateTime: .now(), + myTimeStamp: 123, + myEmail: "local-part@domain-part", + myJSON: "{}", + myPhone: "2342355678", + myURL: "https://www.amazon.com/dp/B000NZW3KC/", + myIPAddress: "123.12.34.56" + ) let updatedContainer = ScalarContainer(id: container.id) let savedModel = try await Amplify.DataStore.save(container) XCTAssertEqual(savedModel, container) @@ -61,15 +63,18 @@ class DataStoreScalarTests: SyncEngineIntegrationTestBase { intList: [], intNullableList: [], nullableIntList: [], - nullableIntNullableList: nil) - - let updatedContainer = ListIntContainer(id: container.id, - test: 2, - nullableInt: nil, - intList: [1, 2, 3], - intNullableList: [1, 2, 3], - nullableIntList: [1, 2, 3], - nullableIntNullableList: [1, 2, 3]) + nullableIntNullableList: nil + ) + + let updatedContainer = ListIntContainer( + id: container.id, + test: 2, + nullableInt: nil, + intList: [1, 2, 3], + intNullableList: [1, 2, 3], + nullableIntList: [1, 2, 3], + nullableIntNullableList: [1, 2, 3] + ) let savedModel = try await Amplify.DataStore.save(container) XCTAssertEqual(savedModel, container) let updatedModel = try await Amplify.DataStore.save(updatedContainer) @@ -90,15 +95,18 @@ class DataStoreScalarTests: SyncEngineIntegrationTestBase { stringList: ["value1"], stringNullableList: [], nullableStringList: [], - nullableStringNullableList: nil) - - let updatedContainer = ListStringContainer(id: container.id, - test: "test", - nullableString: "test", - stringList: ["value1"], - stringNullableList: ["value1"], - nullableStringList: ["value1"], - nullableStringNullableList: ["value1"]) + nullableStringNullableList: nil + ) + + let updatedContainer = ListStringContainer( + id: container.id, + test: "test", + nullableString: "test", + stringList: ["value1"], + stringNullableList: ["value1"], + nullableStringList: ["value1"], + nullableStringNullableList: ["value1"] + ) let savedModel = try await Amplify.DataStore.save(container) XCTAssertEqual(savedModel, container) let updatedModel = try await Amplify.DataStore.save(updatedContainer) @@ -120,15 +128,18 @@ class DataStoreScalarTests: SyncEngineIntegrationTestBase { stringList: ["value1"], stringNullableList: nil, nullableStringList: [nil], - nullableStringNullableList: nil) - - let updatedContainer = ListStringContainer(id: container.id, - test: "test", - nullableString: "test", - stringList: ["value1"], - stringNullableList: ["value1"], - nullableStringList: ["value1"], - nullableStringNullableList: ["value1"]) + nullableStringNullableList: nil + ) + + let updatedContainer = ListStringContainer( + id: container.id, + test: "test", + nullableString: "test", + stringList: ["value1"], + stringNullableList: ["value1"], + nullableStringList: ["value1"], + nullableStringNullableList: ["value1"] + ) let savedModel = try await Amplify.DataStore.save(container) XCTAssertEqual(savedModel, container) let updatedModel = try await Amplify.DataStore.save(updatedContainer) @@ -143,19 +154,23 @@ class DataStoreScalarTests: SyncEngineIntegrationTestBase { func testEnumTestModel() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let container = EnumTestModel(enumVal: .valueOne, - nullableEnumVal: .valueTwo, - enumList: [.valueOne], - enumNullableList: [.valueTwo], - nullableEnumList: [.valueOne, .valueTwo], - nullableEnumNullableList: [.valueTwo, .valueOne]) - let updatedContainer = EnumTestModel(id: container.id, - enumVal: .valueTwo, - nullableEnumVal: nil, - enumList: [.valueTwo], - enumNullableList: [.valueTwo, .valueOne], - nullableEnumList: [.valueTwo, .valueOne], - nullableEnumNullableList: [.valueOne, .valueTwo]) + let container = EnumTestModel( + enumVal: .valueOne, + nullableEnumVal: .valueTwo, + enumList: [.valueOne], + enumNullableList: [.valueTwo], + nullableEnumList: [.valueOne, .valueTwo], + nullableEnumNullableList: [.valueTwo, .valueOne] + ) + let updatedContainer = EnumTestModel( + id: container.id, + enumVal: .valueTwo, + nullableEnumVal: nil, + enumList: [.valueTwo], + enumNullableList: [.valueTwo, .valueOne], + nullableEnumList: [.valueTwo, .valueOne], + nullableEnumNullableList: [.valueOne, .valueTwo] + ) let savedModel = try await Amplify.DataStore.save(container) XCTAssertEqual(savedModel, container) let updatedModel = try await Amplify.DataStore.save(updatedContainer) @@ -170,20 +185,24 @@ class DataStoreScalarTests: SyncEngineIntegrationTestBase { func testNestedEnumTestModel() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let container = NestedTypeTestModel(nestedVal: .init(valueOne: 1), - nullableNestedVal: .init(), - nestedList: [.init(valueTwo: "value2")], - nestedNullableList: [.init()], - nullableNestedList: [.init(valueOne: 1, valueTwo: "value2")], - nullableNestedNullableList: [.init(valueOne: 1, valueTwo: "value2")]) - - let updatedContainer = NestedTypeTestModel(id: container.id, - nestedVal: .init(valueOne: 1), - nullableNestedVal: .init(), - nestedList: [.init(valueTwo: "updatedValue"), .init(valueOne: 1)], - nestedNullableList: [.init(valueOne: 1, valueTwo: "value2")], - nullableNestedList: [], - nullableNestedNullableList: nil) + let container = NestedTypeTestModel( + nestedVal: .init(valueOne: 1), + nullableNestedVal: .init(), + nestedList: [.init(valueTwo: "value2")], + nestedNullableList: [.init()], + nullableNestedList: [.init(valueOne: 1, valueTwo: "value2")], + nullableNestedNullableList: [.init(valueOne: 1, valueTwo: "value2")] + ) + + let updatedContainer = NestedTypeTestModel( + id: container.id, + nestedVal: .init(valueOne: 1), + nullableNestedVal: .init(), + nestedList: [.init(valueTwo: "updatedValue"), .init(valueOne: 1)], + nestedNullableList: [.init(valueOne: 1, valueTwo: "value2")], + nullableNestedList: [], + nullableNestedNullableList: nil + ) let savedModel = try await Amplify.DataStore.save(container) XCTAssertEqual(savedModel, container) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/AmplifyModels.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/AmplifyModels.swift index 2f95bb74f4..20d39f3f52 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/AmplifyModels.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/AmplifyModels.swift @@ -11,7 +11,7 @@ import Foundation // Contains the set of classes that conforms to the `Model` protocol. -final public class AmplifyModels: AmplifyModelRegistration { +public final class AmplifyModels: AmplifyModelRegistration { public let version: String public init(version: String = "46369a50a95486d76713fd33833fb782") { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article+Schema.swift index 251a7dfe2c..bb0d8d1529 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Article { +public extension Article { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt @@ -19,10 +19,10 @@ extension Article { case authorNotes } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let article = Article.keys model.listPluralName = "Articles" @@ -38,10 +38,11 @@ extension Article { .field(article.content, is: .required, ofType: .string), .field(article.createdAt, is: .required, ofType: .dateTime), .field(article.owner, is: .optional, ofType: .string), - .field(article.authorNotes, - is: .optional, - ofType: .string, - authRules: [rule(allow: .owner, ownerField: "owner", operations: [.update])] + .field( + article.authorNotes, + is: .optional, + ofType: .string, + authRules: [rule(allow: .owner, ownerField: "owner", operations: [.update])] ) ) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article.swift index 5b1486510a..84661e4cfc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article.swift @@ -16,11 +16,13 @@ public struct Article: Model { public var owner: String? public var authorNotes: String? - public init(id: String = UUID().uuidString, - content: String, - createdAt: Temporal.DateTime, - owner: String?, - authorNotes: String?) { + public init( + id: String = UUID().uuidString, + content: String, + createdAt: Temporal.DateTime, + owner: String?, + authorNotes: String? + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author+Schema.swift index 9d64613c81..3b253b6aa8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author+Schema.swift @@ -8,26 +8,28 @@ import Amplify import Foundation -extension Author { +public extension Author { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case books } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let author = Author.keys model.fields( .id(), - .hasMany(author.books, - ofType: BookAuthor.self, - associatedWith: BookAuthor.keys.book) + .hasMany( + author.books, + ofType: BookAuthor.self, + associatedWith: BookAuthor.keys.book + ) ) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author.swift index de80ddf0ec..2aaaf7bdc8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author.swift @@ -15,8 +15,10 @@ public struct Author: Model { // hasMany(associatedWith: "author") public var books: List - public init(id: String = UUID().uuidString, - books: List = []) { + public init( + id: String = UUID().uuidString, + books: List = [] + ) { self.id = id self.books = books } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book+Schema.swift index 72c6af2f9d..4854747fe9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book+Schema.swift @@ -8,26 +8,28 @@ import Amplify import Foundation -extension Book { +public extension Book { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case authors } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let book = Book.keys model.fields( .id(), - .hasMany(book.authors, - ofType: BookAuthor.self, - associatedWith: BookAuthor.keys.author) + .hasMany( + book.authors, + ofType: BookAuthor.self, + associatedWith: BookAuthor.keys.author + ) ) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book.swift index d2d130e83a..51be34c79f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book.swift @@ -15,8 +15,10 @@ public struct Book: Model { // hasMany(associatedWith: "book") public var authors: List - public init(id: String = UUID().uuidString, - authors: List = []) { + public init( + id: String = UUID().uuidString, + authors: List = [] + ) { self.id = id self.authors = authors } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor+Schema.swift index 52600e0a9d..2b048a1ca6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor+Schema.swift @@ -8,30 +8,34 @@ import Amplify import Foundation -extension BookAuthor { +public extension BookAuthor { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case book case author } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let bookAuthor = BookAuthor.keys model.fields( .id(), - .belongsTo(bookAuthor.book, - ofType: Book.self, - associatedWith: Book.keys.authors), - .belongsTo(bookAuthor.author, - ofType: Author.self, - associatedWith: Author.keys.books) + .belongsTo( + bookAuthor.book, + ofType: Book.self, + associatedWith: Book.keys.authors + ), + .belongsTo( + bookAuthor.author, + ofType: Author.self, + associatedWith: Author.keys.books + ) ) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor.swift index 1c837b590c..e29875b031 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor.swift @@ -18,9 +18,11 @@ public struct BookAuthor: Model { // belongsTo public let book: Book - public init(id: String = UUID().uuidString, - book: Book, - author: Author) { + public init( + id: String = UUID().uuidString, + book: Book, + author: Author + ) { self.id = id self.book = book self.author = author diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount+Schema.swift index dc51cd80e0..adf7fb3f85 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount+Schema.swift @@ -8,27 +8,29 @@ import Amplify import Foundation -extension UserAccount { +public extension UserAccount { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case profile } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let account = UserAccount.keys model.fields( .id(), - .hasOne(account.profile, - is: .optional, - ofType: UserProfile.self, - associatedWith: UserProfile.CodingKeys.account) + .hasOne( + account.profile, + is: .optional, + ofType: UserProfile.self, + associatedWith: UserProfile.CodingKeys.account + ) ) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount.swift index 268b5f0fed..a05e352f88 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount.swift @@ -20,8 +20,10 @@ public class UserAccount: Model { // hasOne(associatedWith: "account") public var profile: UserProfile? - public init(id: String = UUID().uuidString, - profile: UserProfile? = nil) { + public init( + id: String = UUID().uuidString, + profile: UserProfile? = nil + ) { self.id = id self.profile = profile } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile+Schema.swift index 6b6eb355d7..d4e2c7ee1d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile+Schema.swift @@ -8,26 +8,28 @@ import Amplify import Foundation -extension UserProfile { +public extension UserProfile { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case account } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let profile = UserProfile.keys model.fields( .id(), - .belongsTo(profile.account, - ofType: UserAccount.self, - associatedWith: UserAccount.keys.profile) + .belongsTo( + profile.account, + ofType: UserAccount.self, + associatedWith: UserAccount.keys.profile + ) ) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile.swift index 227d1c8da5..26d1d2e7cb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile.swift @@ -20,8 +20,10 @@ public class UserProfile: Model { // belongsTo(associatedWith: "profile") public var account: UserAccount - public init(id: String = UUID().uuidString, - account: UserAccount) { + public init( + id: String = UUID().uuidString, + account: UserAccount + ) { self.id = id self.account = account } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1+Schema.swift index d561583928..7d0aacab8b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Project1 { +public extension Project1 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project1 = Project1.keys model.listPluralName = "Project1s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1.swift index ab67718c80..8760364532 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1.swift @@ -14,9 +14,11 @@ public struct Project1: Model { public var name: String? public var team: Team1? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String? = nil, - team: Team1? = nil) { + team: Team1? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1+Schema.swift index be252d9197..946b4692c0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1+Schema.swift @@ -9,17 +9,17 @@ import Amplify import Foundation -extension Team1 { +public extension Team1 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team1 = Team1.keys model.listPluralName = "Team1s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1.swift index 4a6101a50c..0bcf352358 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1.swift @@ -13,8 +13,10 @@ public struct Team1: Model { public let id: String public var name: String - public init(id: String = UUID().uuidString, - name: String) { + public init( + id: String = UUID().uuidString, + name: String + ) { self.id = id self.name = name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2+Schema.swift index 7bd2fd74ce..837b30544e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Project2 { +public extension Project2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case teamID case team } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project2 = Project2.keys model.listPluralName = "Project2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2.swift index a5307b612c..0dbc730331 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2.swift @@ -15,10 +15,12 @@ public struct Project2: Model { public var teamID: String public var team: Team2? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String? = nil, teamID: String, - team: Team2? = nil) { + team: Team2? = nil + ) { self.id = id self.name = name self.teamID = teamID diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2+Schema.swift index 9c7424a94d..4e97ad88c6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2+Schema.swift @@ -9,17 +9,17 @@ import Amplify import Foundation -extension Team2 { +public extension Team2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team2 = Team2.keys model.listPluralName = "Team2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2.swift index eece17c222..7c3b6617a8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2.swift @@ -13,8 +13,10 @@ public struct Team2: Model { public let id: String public var name: String - public init(id: String = UUID().uuidString, - name: String) { + public init( + id: String = UUID().uuidString, + name: String + ) { self.id = id self.name = name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3+Schema.swift index 03c4b0eb64..f2be1939c8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Comment3 { +public extension Comment3 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case postID case content } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment3 = Comment3.keys model.listPluralName = "Comment3s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3.swift index f24badf993..14c2cce660 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3.swift @@ -14,9 +14,11 @@ public struct Comment3: Model { public var postID: String public var content: String - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, postID: String, - content: String) { + content: String + ) { self.id = id self.postID = postID self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3+Schema.swift index 9f828c7c44..fbda57a013 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Post3 { +public extension Post3 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post3 = Post3.keys model.listPluralName = "Post3s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3.swift index 1302c5a233..63d64a9316 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3.swift @@ -14,9 +14,11 @@ public struct Post3: Model { public var title: String public var comments: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, - comments: List? = []) { + comments: List? = [] + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4+Schema.swift index 16b6b2a416..35b7c9278c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Comment4 { +public extension Comment4 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment4 = Comment4.keys model.listPluralName = "Comment4s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4.swift index 175c4d994a..a404407183 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4.swift @@ -14,9 +14,11 @@ public struct Comment4: Model { public var content: String public var post: Post4? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, content: String, - post: Post4? = nil) { + post: Post4? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4+Schema.swift index 17144a90a0..ac5c751832 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Post4 { +public extension Post4 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post4 = Post4.keys model.listPluralName = "Post4s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4.swift index 4764058a79..84fc6972ba 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4.swift @@ -14,9 +14,11 @@ public struct Post4: Model { public var title: String public var comments: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, - comments: List? = []) { + comments: List? = [] + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5+Schema.swift index 3898f6addd..419ffc556d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Post5 { +public extension Post5 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case editors } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post5 = Post5.keys model.listPluralName = "Post5s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5.swift index 023c8eb0dc..d4f8fc51fa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5.swift @@ -14,9 +14,11 @@ public struct Post5: Model { public var title: String public var editors: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, - editors: List? = []) { + editors: List? = [] + ) { self.id = id self.title = title self.editors = editors diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5+Schema.swift index 586429c143..2d054312a0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension PostEditor5 { +public extension PostEditor5 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post case editor } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let postEditor5 = PostEditor5.keys model.listPluralName = "PostEditor5s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5.swift index 24cad3a416..30af2f8558 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5.swift @@ -14,9 +14,11 @@ public struct PostEditor5: Model { public var post: Post5 public var editor: User5 - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, post: Post5, - editor: User5) { + editor: User5 + ) { self.id = id self.post = post self.editor = editor diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5+Schema.swift index cf467b9f55..431a0027db 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension User5 { +public extension User5 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case username case posts } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let user5 = User5.keys model.listPluralName = "User5s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5.swift index 3fab8d8d27..63e5ad8478 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5.swift @@ -14,9 +14,11 @@ public struct User5: Model { public var username: String public var posts: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, username: String, - posts: List? = []) { + posts: List? = [] + ) { self.id = id self.username = username self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6+Schema.swift index fc6b58b600..af044289e0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Blog6 { +public extension Blog6 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog6 = Blog6.keys model.listPluralName = "Blog6s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6.swift index 9bc903c6d4..d226a82190 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6.swift @@ -14,9 +14,11 @@ public struct Blog6: Model { public var name: String public var posts: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String, - posts: List? = []) { + posts: List? = [] + ) { self.id = id self.name = name self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6+Schema.swift index 3d180ac245..ef05fae7ca 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Comment6 { +public extension Comment6 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post case content } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment6 = Comment6.keys model.listPluralName = "Comment6s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6.swift index 061c288aa1..960b55edd1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6.swift @@ -14,9 +14,11 @@ public struct Comment6: Model { public var post: Post6? public var content: String - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, post: Post6? = nil, - content: String) { + content: String + ) { self.id = id self.post = post self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6+Schema.swift index e84aa85350..24956ef8f6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Post6 { +public extension Post6 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case blog case comments } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post6 = Post6.keys model.listPluralName = "Post6s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6.swift index a470246a15..122eebf379 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6.swift @@ -15,10 +15,12 @@ public struct Post6: Model { public var blog: Blog6? public var comments: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, blog: Blog6? = nil, - comments: List? = []) { + comments: List? = [] + ) { self.id = id self.title = title self.blog = blog diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment+Schema.swift index 97c63c8661..e50f2f4c35 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Comment { +public extension Comment { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt case post } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment = Comment.keys model.listPluralName = "Comments" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment.swift index 51db95f439..58b9cc17ab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment.swift @@ -15,10 +15,12 @@ public struct Comment: Model { public var createdAt: Temporal.DateTime public var post: Post - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, content: String, createdAt: Temporal.DateTime, - post: Post) { + post: Post + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder+Schema.swift index 2bd91ddb85..36b482fc13 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension CustomerOrder { +public extension CustomerOrder { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case orderId case email } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerOrder = CustomerOrder.keys model.listPluralName = "CustomerOrders" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder.swift index 92609d0848..2e3472728a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder.swift @@ -22,9 +22,11 @@ public struct CustomerOrder: Model { public var orderId: String public var email: String - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, orderId: String, - email: String) { + email: String + ) { self.id = id self.orderId = orderId self.email = email diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Deprecated/DeprecatedTodo.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Deprecated/DeprecatedTodo.swift index 2e364e24d6..53a88d40c5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Deprecated/DeprecatedTodo.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Deprecated/DeprecatedTodo.swift @@ -8,6 +8,7 @@ // swiftlint:disable all import Amplify import Foundation + /* The schema used to codegen this model: type DeprecatedTodo @model { @@ -30,27 +31,29 @@ public struct DeprecatedTodo: Model { public var description: String? public var note: Note? - public init(id: String = UUID().uuidString, - description: String? = nil, - note: Note? = nil) { + public init( + id: String = UUID().uuidString, + description: String? = nil, + note: Note? = nil + ) { self.id = id self.description = description self.note = note } } -extension DeprecatedTodo { +public extension DeprecatedTodo { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case description case note } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let deprecatedTodo = DeprecatedTodo.keys model.pluralName = "DeprecatedTodos" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost+Schema.swift index 7d700109e9..c9a94931a5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension M2MPost { +public extension M2MPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case editors } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let m2MPost = M2MPost.keys model.listPluralName = "M2MPosts" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost.swift index 38b678400f..12862030b3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost.swift @@ -14,9 +14,11 @@ public struct M2MPost: Model { public var title: String public var editors: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, - editors: List? = []) { + editors: List? = [] + ) { self.id = id self.title = title self.editors = editors diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor+Schema.swift index 7c48259298..d37c0719cb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension M2MPostEditor { +public extension M2MPostEditor { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post case editor } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let m2MPostEditor = M2MPostEditor.keys model.listPluralName = "M2MPostEditors" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor.swift index f90b4ec386..2cfd57b223 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor.swift @@ -14,9 +14,11 @@ public struct M2MPostEditor: Model { public var post: M2MPost public var editor: M2MUser - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, post: M2MPost, - editor: M2MUser) { + editor: M2MUser + ) { self.id = id self.post = post self.editor = editor diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser+Schema.swift index 452ca2b270..1db74f78b5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension M2MUser { +public extension M2MUser { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case username case posts } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let m2MUser = M2MUser.keys model.listPluralName = "M2MUsers" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser.swift index 076f5fb3b5..4c62eb0f75 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser.swift @@ -14,9 +14,11 @@ public struct M2MUser: Model { public var username: String public var posts: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, username: String, - posts: List? = []) { + posts: List? = [] + ) { self.id = id self.username = username self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Category.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Category.swift index 277b136bf2..3f5375f2db 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Category.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Category.swift @@ -14,18 +14,20 @@ public struct Category: Embeddable { var color: Color } -extension Category { +public extension Category { - public enum CodingKeys: CodingKey { + enum CodingKeys: CodingKey { case name case color } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self - public static let schema = defineSchema { embedded in + static let schema = defineSchema { embedded in let category = Category.keys - embedded.fields(.field(category.name, is: .required, ofType: .string), - .field(category.color, is: .required, ofType: .embedded(type: Color.self))) + embedded.fields( + .field(category.name, is: .required, ofType: .string), + .field(category.color, is: .required, ofType: .embedded(type: Color.self)) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Color.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Color.swift index 793b6a6844..be00159e03 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Color.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Color.swift @@ -16,21 +16,23 @@ public struct Color: Embeddable { var blue: Int } -extension Color { - public enum CodingKeys: CodingKey { +public extension Color { + enum CodingKeys: CodingKey { case name case red case green case blue } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self - public static let schema = defineSchema { embedded in + static let schema = defineSchema { embedded in let color = Color.keys - embedded.fields(.field(color.name, is: .required, ofType: .string), - .field(color.red, is: .required, ofType: .int), - .field(color.green, is: .required, ofType: .int), - .field(color.blue, is: .required, ofType: .int)) + embedded.fields( + .field(color.name, is: .required, ofType: .string), + .field(color.red, is: .required, ofType: .int), + .field(color.green, is: .required, ofType: .int), + .field(color.blue, is: .required, ofType: .int) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicEmbedded.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicEmbedded.swift index 2636100012..dbe3743464 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicEmbedded.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicEmbedded.swift @@ -18,7 +18,7 @@ struct DynamicEmbedded: Embeddable, JSONValueHolder { public init(from decoder: Decoder) throws { let json = try JSONValue(from: decoder) if case .object(let jsonValue) = json { - values = jsonValue + self.values = jsonValue } else { self.values = [:] } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicModel.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicModel.swift index a88cfeb7fe..c2207d7e1d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicModel.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicModel.swift @@ -21,10 +21,10 @@ struct DynamicModel: Model, JSONValueHolder { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - id = try container.decode(String.self, forKey: .id) + self.id = try container.decode(String.self, forKey: .id) let json = try JSONValue(from: decoder) if case .object(let jsonValues) = json { - values = jsonValues + self.values = jsonValues } else { self.values = [:] } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Section.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Section.swift index 0ffd42eb2f..2686d17849 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Section.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Section.swift @@ -14,17 +14,19 @@ public struct Section: Embeddable { var number: Double } -extension Section { - public enum CodingKeys: CodingKey { +public extension Section { + enum CodingKeys: CodingKey { case name case number } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self - public static let schema = defineSchema { embedded in + static let schema = defineSchema { embedded in let section = Section.keys - embedded.fields(.field(section.name, is: .required, ofType: .string), - .field(section.number, is: .required, ofType: .double)) + embedded.fields( + .field(section.name, is: .required, ofType: .string), + .field(section.number, is: .required, ofType: .double) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo+Schema.swift index d53b4c0e07..75a2e93363 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Todo { +public extension Todo { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case description @@ -20,10 +20,10 @@ extension Todo { case stickies } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todo = Todo.keys model.listPluralName = "Todos" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo.swift index 423f2aa568..58eb250fcf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo.swift @@ -8,6 +8,7 @@ // swiftlint:disable all import Amplify import Foundation + /* The schema used to codegen this model: type Todo @model { @@ -45,12 +46,14 @@ public struct Todo: Model { public var section: Section? public var stickies: [String]? - public init(id: String = UUID().uuidString, - name: String, - description: String? = nil, - categories: [Category]? = [], - section: Section? = nil, - stickies: [String]? = []) { + public init( + id: String = UUID().uuidString, + name: String, + description: String? = nil, + categories: [Category]? = [], + section: Section? = nil, + stickies: [String]? = [] + ) { self.id = id self.name = name self.description = description diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost+Schema.swift index 69170decb4..9a31e531e8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension OGCScenarioBMGroupPost { +public extension OGCScenarioBMGroupPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case owner } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let oGCScenarioBMGroupPost = OGCScenarioBMGroupPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost.swift index 64ab04bf3f..7b07808b60 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost.swift @@ -14,9 +14,11 @@ public struct OGCScenarioBMGroupPost: Model { public var title: String public var owner: String? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, - owner: String? = nil) { + owner: String? = nil + ) { self.id = id self.title = title self.owner = owner diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost+Schema.swift index 2a3c67066f..bf69f585ca 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension OGCScenarioBPost { +public extension OGCScenarioBPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case owner } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let oGCScenarioBPost = OGCScenarioBPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost.swift index 5ee8d97fb9..b49ef50072 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost.swift @@ -14,9 +14,11 @@ public struct OGCScenarioBPost: Model { public var title: String public var owner: String? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, - owner: String? = nil) { + owner: String? = nil + ) { self.id = id self.title = title self.owner = owner diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post+Schema.swift index 8ae2020779..51b399bccb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post { +public extension Post { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case content @@ -23,10 +23,10 @@ extension Post { case comments } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post = Post.keys model.listPluralName = "Posts" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post.swift index 282bd91846..7c43a79452 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post.swift @@ -20,7 +20,8 @@ public struct Post: Model { public var status: PostStatus? public var comments: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, content: String, createdAt: Temporal.DateTime, @@ -28,7 +29,8 @@ public struct Post: Model { draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, - comments: List? = []) { + comments: List? = [] + ) { self.id = id self.title = title self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/PostCommentModelRegistration.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/PostCommentModelRegistration.swift index b3c1e7a4a1..b3e51e7f77 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/PostCommentModelRegistration.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/PostCommentModelRegistration.swift @@ -8,7 +8,7 @@ import Amplify import Foundation -final public class PostCommentModelRegistration: AmplifyModelRegistration { +public final class PostCommentModelRegistration: AmplifyModelRegistration { public func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post.self) ModelRegistry.register(modelType: Comment.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen+Schema.swift index 4571c1ed25..58ecadd569 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension QPredGen { +public extension QPredGen { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case myBool @@ -23,10 +23,10 @@ extension QPredGen { case myTime } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let qPredGen = QPredGen.keys model.listPluralName = "QPredGens" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen.swift index b26ad62ede..6c5f5e6406 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen.swift @@ -8,6 +8,7 @@ // swiftlint:disable all import Amplify import Foundation + /* Generated from: @@ -34,7 +35,8 @@ public struct QPredGen: Model { public var myDateTime: Temporal.DateTime? public var myTime: Temporal.Time? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String, myBool: Bool? = nil, myDouble: Double? = nil, @@ -42,7 +44,8 @@ public struct QPredGen: Model { myString: String? = nil, myDate: Temporal.Date? = nil, myDateTime: Temporal.DateTime? = nil, - myTime: Temporal.Time? = nil) { + myTime: Temporal.Time? = nil + ) { self.id = id self.name = name self.myBool = myBool diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record+Schema.swift index 7df7ca922e..5d014387bf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record+Schema.swift @@ -5,13 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify + // swiftlint:disable all import Foundation -import Amplify -extension Record { +public extension Record { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case description @@ -21,10 +22,10 @@ extension Record { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let record = Record.keys model.listPluralName = "Records" @@ -41,10 +42,11 @@ extension Record { isReadOnly: true, ofType: RecordCover.self, associatedWith: RecordCover.keys.id, - targetName: "coverId"), + targetName: "coverId" + ), .field(record.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), .field(record.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) - ) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record.swift index 6b8f224c54..47608bb491 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record.swift @@ -5,9 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify + // swiftlint:disable all import Foundation -import Amplify public struct Record: Model { public let id: String @@ -18,23 +19,29 @@ public struct Record: Model { public let createdAt: Temporal.DateTime? public let updatedAt: Temporal.DateTime? - public init(name: String, - description: String? = nil) { - self.init(name: name, - description: description, - coverId: nil, - cover: nil, - createdAt: nil, - updatedAt: nil) + public init( + name: String, + description: String? = nil + ) { + self.init( + name: name, + description: description, + coverId: nil, + cover: nil, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - description: String? = nil, - coverId: String? = nil, - cover: RecordCover? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + description: String? = nil, + coverId: String? = nil, + cover: RecordCover? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.description = description diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover+Schema.swift index 04f4f8a460..7b0fa29fcb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover+Schema.swift @@ -5,33 +5,34 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify + // swiftlint:disable all import Foundation -import Amplify -extension RecordCover { +public extension RecordCover { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case artist case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let recordCover = RecordCover.keys model.listPluralName = "RecordCovers" model.syncPluralName = "RecordCovers" model.fields( - .id(), - .field(recordCover.artist, is: .required, ofType: .string), - .field(recordCover.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), - .field(recordCover.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) - ) + .id(), + .field(recordCover.artist, is: .required, ofType: .string), + .field(recordCover.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), + .field(recordCover.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover.swift index 21d00c458f..c3730c1d79 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation // swiftlint:disable all @@ -17,15 +17,19 @@ public struct RecordCover: Model { public let updatedAt: Temporal.DateTime? public init(artist: String) { - self.init(artist: artist, - createdAt: nil, - updatedAt: nil) + self.init( + artist: artist, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - artist: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + artist: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.artist = artist self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group+Schema.swift index e7a80ecd9b..9bbab7d799 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group+Schema.swift @@ -5,19 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation -extension Group { +public extension Group { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let group = Group.keys model.listPluralName = "Groups" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group.swift index 2a270048e6..5452511e2f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public struct Group: Model { public let id: String diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row+Schema.swift index 6878da26b5..3e55c96621 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row+Schema.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation -extension Row { +public extension Row { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case group } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let row = Row.keys model.listPluralName = "Rows" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row.swift index 496c3426e7..4db70b5d80 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row.swift @@ -5,15 +5,17 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public struct Row: Model { public let id: String public var group: Group - public init(id: String = UUID().uuidString, - group: Group) { + public init( + id: String = UUID().uuidString, + group: Group + ) { self.id = id self.group = group } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction+Schema.swift index 8c5ac3a9b0..4dc6dcfcfb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction+Schema.swift @@ -5,20 +5,21 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify + // swiftlint:disable all import Foundation -import Amplify -extension Transaction { +public extension Transaction { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let transaction = Transaction.keys model.listPluralName = "Transactions" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction.swift index 0cdd05cc3c..0c249b049a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction.swift @@ -5,9 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify + // swiftlint:disable all import Foundation -import Amplify public struct Transaction: Model { public let id: String diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish+Schema.swift index 3022b9e276..e8945e7e10 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Dish { +public extension Dish { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case dishName case menu } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let dish = Dish.keys model.listPluralName = "Dishes" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish.swift index 73fe887fe0..58afa9e691 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish.swift @@ -14,9 +14,11 @@ public struct Dish: Model { public var dishName: String? public var menu: Menu? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, dishName: String? = nil, - menu: Menu? = nil) { + menu: Menu? = nil + ) { self.id = id self.dishName = dishName self.menu = menu diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu+Schema.swift index e3188b3f4f..34a3e35ceb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Menu { +public extension Menu { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case menuType @@ -19,10 +19,10 @@ extension Menu { case dishes } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let menu = Menu.keys model.listPluralName = "Menus" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu.swift index 5b571fef48..7ec55a7ec6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu.swift @@ -16,11 +16,13 @@ public struct Menu: Model { public var restaurant: Restaurant? public var dishes: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String, menuType: MenuType? = nil, restaurant: Restaurant? = nil, - dishes: List? = []) { + dishes: List? = [] + ) { self.id = id self.name = name self.menuType = menuType diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant+Schema.swift index 6d677b46aa..636f1d05ad 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Restaurant { +public extension Restaurant { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case restaurantName case menus } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let restaurant = Restaurant.keys model.listPluralName = "Restaurants" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant.swift index 37ce26d911..20ec8bde27 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant.swift @@ -14,9 +14,11 @@ public struct Restaurant: Model { public var restaurantName: String public var menus: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, restaurantName: String, - menus: List? = []) { + menus: List? = [] + ) { self.id = id self.restaurantName = restaurantName self.menus = menus diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel+Schema.swift index 05ff5b0fbc..bd9858f7d1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension EnumTestModel { +public extension EnumTestModel { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case enumVal case nullableEnumVal @@ -21,10 +21,10 @@ extension EnumTestModel { case nullableEnumNullableList } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let enumTestModel = EnumTestModel.keys model.listPluralName = "EnumTestModels" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel.swift index 65fe699440..ac3e7f73e3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel.swift @@ -18,13 +18,15 @@ public struct EnumTestModel: Model { public var nullableEnumList: [TestEnum?] public var nullableEnumNullableList: [TestEnum?]? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, enumVal: TestEnum, nullableEnumVal: TestEnum? = nil, enumList: [TestEnum] = [], enumNullableList: [TestEnum]? = nil, nullableEnumList: [TestEnum?] = [], - nullableEnumNullableList: [TestEnum?]? = nil) { + nullableEnumNullableList: [TestEnum?]? = nil + ) { self.id = id self.enumVal = enumVal self.nullableEnumVal = nullableEnumVal diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer+Schema.swift index 6ef039ff38..8362ac98fe 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension ListIntContainer { +public extension ListIntContainer { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case test case nullableInt @@ -21,10 +21,10 @@ extension ListIntContainer { case nullableIntNullableList } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let listIntContainer = ListIntContainer.keys model.listPluralName = "ListIntContainers" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer.swift index 4dd8862fe3..45604058ba 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer.swift @@ -18,13 +18,15 @@ public struct ListIntContainer: Model { public var nullableIntList: [Int?] public var nullableIntNullableList: [Int?]? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, test: Int, nullableInt: Int? = nil, intList: [Int] = [], intNullableList: [Int]? = nil, nullableIntList: [Int?] = [], - nullableIntNullableList: [Int?]? = nil) { + nullableIntNullableList: [Int?]? = nil + ) { self.id = id self.test = test self.nullableInt = nullableInt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer+Schema.swift index 00d1f2b153..28095c5617 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension ListStringContainer { +public extension ListStringContainer { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case test case nullableString @@ -21,10 +21,10 @@ extension ListStringContainer { case nullableStringNullableList } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let listStringContainer = ListStringContainer.keys model.listPluralName = "ListStringContainers" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer.swift index 5a23f7a5de..712c970012 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer.swift @@ -18,13 +18,15 @@ public struct ListStringContainer: Model { public var nullableStringList: [String?] public var nullableStringNullableList: [String?]? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, test: String, nullableString: String? = nil, stringList: [String] = [], stringNullableList: [String]? = nil, nullableStringList: [String?] = [], - nullableStringNullableList: [String?]? = nil) { + nullableStringNullableList: [String?]? = nil + ) { self.id = id self.test = test self.nullableString = nullableString diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Nested+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Nested+Schema.swift index f1d85adce4..edafe3cc62 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Nested+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Nested+Schema.swift @@ -9,17 +9,17 @@ import Amplify import Foundation -extension Nested { +public extension Nested { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case valueOne case valueTwo } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let nested = Nested.keys model.listPluralName = "Nesteds" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel+Schema.swift index 79f122f0ad..806dce775f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension NestedTypeTestModel { +public extension NestedTypeTestModel { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case nestedVal case nullableNestedVal @@ -21,10 +21,10 @@ extension NestedTypeTestModel { case nullableNestedNullableList } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let nestedTypeTestModel = NestedTypeTestModel.keys model.listPluralName = "NestedTypeTestModels" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel.swift index 5ceda72443..c9ba508760 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel.swift @@ -18,13 +18,15 @@ public struct NestedTypeTestModel: Model { public var nullableNestedList: [Nested?] public var nullableNestedNullableList: [Nested?]? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, nestedVal: Nested, nullableNestedVal: Nested? = nil, nestedList: [Nested] = [], nestedNullableList: [Nested]? = nil, nullableNestedList: [Nested?] = [], - nullableNestedNullableList: [Nested?]? = nil) { + nullableNestedNullableList: [Nested?]? = nil + ) { self.id = id self.nestedVal = nestedVal self.nullableNestedVal = nullableNestedVal diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Scalar+Equatable.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Scalar+Equatable.swift index 3dff2379d4..d8ddc691cc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Scalar+Equatable.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Scalar+Equatable.swift @@ -7,7 +7,7 @@ extension ScalarContainer: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.myInt == rhs.myInt && lhs.myDouble == rhs.myDouble && lhs.myBool == rhs.myBool @@ -19,60 +19,60 @@ extension ScalarContainer: Equatable { && lhs.myJSON == rhs.myJSON && lhs.myPhone == rhs.myPhone && lhs.myURL == rhs.myURL - && lhs.myIPAddress == rhs.myIPAddress) + && lhs.myIPAddress == rhs.myIPAddress } } extension ListIntContainer: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.test == rhs.test && lhs.nullableInt == rhs.nullableInt && lhs.intList == rhs.intList && lhs.intNullableList == rhs.intNullableList && lhs.nullableIntList == rhs.nullableIntList - && lhs.nullableIntNullableList == rhs.nullableIntNullableList) + && lhs.nullableIntNullableList == rhs.nullableIntNullableList } } extension ListStringContainer: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.test == rhs.test && lhs.nullableString == rhs.nullableString && lhs.stringList == rhs.stringList && lhs.stringNullableList == rhs.stringNullableList && lhs.nullableStringList == rhs.nullableStringList - && lhs.nullableStringNullableList == rhs.nullableStringNullableList) + && lhs.nullableStringNullableList == rhs.nullableStringNullableList } } extension EnumTestModel: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.enumVal == rhs.enumVal && lhs.nullableEnumVal == rhs.nullableEnumVal && lhs.enumList == rhs.enumList && lhs.enumNullableList == rhs.enumNullableList && lhs.nullableEnumList == rhs.nullableEnumList - && lhs.nullableEnumNullableList == rhs.nullableEnumNullableList) + && lhs.nullableEnumNullableList == rhs.nullableEnumNullableList } } extension NestedTypeTestModel: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.nestedVal == rhs.nestedVal && lhs.nullableNestedVal == rhs.nullableNestedVal && lhs.nestedList == rhs.nestedList && lhs.nestedNullableList == rhs.nestedNullableList && lhs.nullableNestedList == rhs.nullableNestedList - && lhs.nullableNestedNullableList == rhs.nullableNestedNullableList) + && lhs.nullableNestedNullableList == rhs.nullableNestedNullableList } } extension Nested: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.valueOne == rhs.valueOne - && lhs.valueTwo == rhs.valueTwo) + return lhs.valueOne == rhs.valueOne + && lhs.valueTwo == rhs.valueTwo } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer+Schema.swift index 8fc935838a..d05931be73 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension ScalarContainer { +public extension ScalarContainer { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case myString case myInt @@ -28,10 +28,10 @@ extension ScalarContainer { case myIPAddress } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let scalarContainer = ScalarContainer.keys model.listPluralName = "ScalarContainers" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer.swift index 17191db613..94b6ff7475 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer.swift @@ -25,7 +25,8 @@ public struct ScalarContainer: Model { public var myURL: String? public var myIPAddress: String? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, myString: String? = nil, myInt: Int? = nil, myDouble: Double? = nil, @@ -38,7 +39,8 @@ public struct ScalarContainer: Model { myJSON: String? = nil, myPhone: String? = nil, myURL: String? = nil, - myIPAddress: String? = nil) { + myIPAddress: String? = nil + ) { self.id = id self.myString = myString self.myInt = myInt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post+Schema.swift index 57d9581507..cbc6d7ea57 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post+Schema.swift @@ -9,17 +9,17 @@ import Amplify import Foundation -extension ScenarioATest6Post { +public extension ScenarioATest6Post { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let scenarioATest6Post = ScenarioATest6Post.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post.swift index 108b4bfa0e..db203304ff 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post.swift @@ -13,8 +13,10 @@ public struct ScenarioATest6Post: Model { public let id: String public var title: String - public init(id: String = UUID().uuidString, - title: String) { + public init( + id: String = UUID().uuidString, + title: String + ) { self.id = id self.title = title } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project+Schema.swift index 73c9190fdc..1716d0b332 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Project { +public extension Project { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project = Project.keys model.listPluralName = "Projects" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project.swift index 14ae5d0559..db3e85ced2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project.swift @@ -14,9 +14,11 @@ public struct Project: Model { public var name: String? public var team: Team? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String? = nil, - team: Team? = nil) { + team: Team? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team+Schema.swift index a9710d86f8..d6dbe43e23 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team+Schema.swift @@ -9,17 +9,17 @@ import Amplify import Foundation -extension Team { +public extension Team { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team = Team.keys model.listPluralName = "Teams" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team.swift index 3ca4e7e2ef..086f20f10a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team.swift @@ -13,8 +13,10 @@ public struct Team: Model { public let id: String public var name: String - public init(id: String = UUID().uuidString, - name: String) { + public init( + id: String = UUID().uuidString, + name: String + ) { self.id = id self.name = name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2+Schema.swift index e51bfa5402..f798199559 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project1V2 { +public extension Project1V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team @@ -20,10 +20,10 @@ extension Project1V2 { case project1V2TeamId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project1V2 = Project1V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2.swift index 34440bbb51..7cf9f9a23f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2.swift @@ -17,23 +17,29 @@ public struct Project1V2: Model { public var updatedAt: Temporal.DateTime? public var project1V2TeamId: String? - public init(id: String = UUID().uuidString, - name: String? = nil, - team: Team1V2? = nil, - project1V2TeamId: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team1V2? = nil, + project1V2TeamId: String? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, updatedAt: nil, - project1V2TeamId: project1V2TeamId) + project1V2TeamId: project1V2TeamId + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team1V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project1V2TeamId: String? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team1V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project1V2TeamId: String? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2+Schema.swift index 8ed0f54ddf..2fa869b077 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Team1V2 { +public extension Team1V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team1V2 = Team1V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2.swift index ed29653b08..9e547cc972 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2.swift @@ -15,17 +15,23 @@ public struct Team1V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2+Schema.swift index 286ca57848..b1d25f76ab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project2V2 { +public extension Project2V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case teamID @@ -20,10 +20,10 @@ extension Project2V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project2V2 = Project2V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2.swift index fed160bd8c..adc2cfc7fc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2.swift @@ -17,23 +17,29 @@ public struct Project2V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2V2? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2V2? = nil + ) { + self.init( + id: id, name: name, teamID: teamID, team: team, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.teamID = teamID diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2+Schema.swift index 43e0f11b00..0db2c5e78b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Team2V2 { +public extension Team2V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team2V2 = Team2V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2.swift index 7f13b3927a..9b8e27a8b3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2.swift @@ -15,17 +15,23 @@ public struct Team2V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2+Schema.swift index cee3850f92..023f2e2d90 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment3V2 { +public extension Comment3V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case postID case content @@ -19,10 +19,10 @@ extension Comment3V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment3V2 = Comment3V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2.swift index 52f14a06fe..6f0647dd70 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2.swift @@ -16,20 +16,26 @@ public struct Comment3V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - postID: String, - content: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + postID: String, + content: String + ) { + self.init( + id: id, postID: postID, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - postID: String, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + postID: String, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.postID = postID self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2+Schema.swift index f377adf509..e8525efd3a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post3V2 { +public extension Post3V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension Post3V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post3V2 = Post3V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2.swift index 365ff8bc83..bfd3f9db93 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2.swift @@ -16,20 +16,26 @@ public struct Post3V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift index 41081acbfc..a2efc3dd3f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment3aV2 { +public extension Comment3aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt @@ -19,10 +19,10 @@ extension Comment3aV2 { case post3aV2CommentsId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment3aV2 = Comment3aV2.keys model.pluralName = "Comment3aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2.swift index 883bbd6eb8..362732db79 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2.swift @@ -16,20 +16,26 @@ public struct Comment3aV2: Model { public var updatedAt: Temporal.DateTime? public var post3aV2CommentsId: String? - public init(id: String = UUID().uuidString, - content: String, - post3aV2CommentsId: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String, + post3aV2CommentsId: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, updatedAt: nil, - post3aV2CommentsId: post3aV2CommentsId) + post3aV2CommentsId: post3aV2CommentsId + ) } - internal init(id: String = UUID().uuidString, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - post3aV2CommentsId: String? = nil) { + init( + id: String = UUID().uuidString, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + post3aV2CommentsId: String? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift index 3b33c9960e..067713be06 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post3aV2 { +public extension Post3aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension Post3aV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post3aV2 = Post3aV2.keys model.pluralName = "Post3aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2.swift index 5332fcf81a..78361ec783 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2.swift @@ -16,20 +16,26 @@ public struct Post3aV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2+Schema.swift index db568413b1..90683b5561 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment4V2 { +public extension Comment4V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post @@ -19,10 +19,10 @@ extension Comment4V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment4V2 = Comment4V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2.swift index 5873d993e4..0d4073d6b4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2.swift @@ -16,20 +16,26 @@ public struct Comment4V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2+Schema.swift index c0fa5fdfbb..e010e1c080 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post4V2 { +public extension Post4V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension Post4V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post4V2 = Post4V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2.swift index 7978edceb7..9106744759 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2.swift @@ -16,20 +16,26 @@ public struct Post4V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift index 5142fd05de..63cb47ada7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project4aV2 { +public extension Project4aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team @@ -20,10 +20,10 @@ extension Project4aV2 { case project4aV2TeamId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project4aV2 = Project4aV2.keys model.pluralName = "Project4aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2.swift index 51b873975c..4777b1dcda 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2.swift @@ -21,23 +21,29 @@ public class Project4aV2: Model { public var updatedAt: Temporal.DateTime? public var project4aV2TeamId: String? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String? = nil, team: Team4aV2? = nil, - project4aV2TeamId: String? = nil) { - self.init(id: id, + project4aV2TeamId: String? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, updatedAt: nil, - project4aV2TeamId: project4aV2TeamId) + project4aV2TeamId: project4aV2TeamId + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team4aV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project4aV2TeamId: String? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team4aV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project4aV2TeamId: String? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift index 9b7cae724e..18ccef180d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Team4aV2 { +public extension Team4aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case project @@ -19,10 +19,10 @@ extension Team4aV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team4aV2 = Team4aV2.keys model.pluralName = "Team4aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2.swift index 71d880f56b..7abfb7100b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2.swift @@ -16,20 +16,26 @@ public class Team4aV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String, - project: Project4aV2? = nil) { - self.init(id: id, + project: Project4aV2? = nil + ) { + self.init( + id: id, name: name, project: project, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - project: Project4aV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + project: Project4aV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.project = project diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift index 236d2be094..e3f4983c80 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project4bV2 { +public extension Project4bV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team @@ -20,10 +20,10 @@ extension Project4bV2 { case project4bV2TeamId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project4bV2 = Project4bV2.keys model.pluralName = "Project4bV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2.swift index 2369a6c57b..9b280c61df 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2.swift @@ -17,23 +17,29 @@ public class Project4bV2: Model { public var updatedAt: Temporal.DateTime? public var project4bV2TeamId: String? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String? = nil, team: Team4bV2? = nil, - project4bV2TeamId: String? = nil) { - self.init(id: id, + project4bV2TeamId: String? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, updatedAt: nil, - project4bV2TeamId: project4bV2TeamId) + project4bV2TeamId: project4bV2TeamId + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team4bV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project4bV2TeamId: String? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team4bV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project4bV2TeamId: String? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift index 311044fad2..eb0ec1c290 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Team4bV2 { +public extension Team4bV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case project @@ -19,10 +19,10 @@ extension Team4bV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team4bV2 = Team4bV2.keys model.pluralName = "Team4bV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2.swift index 644c856c81..b1831b611b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2.swift @@ -16,20 +16,26 @@ public class Team4bV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String, - project: Project4bV2? = nil) { - self.init(id: id, + project: Project4bV2? = nil + ) { + self.init( + id: id, name: name, project: project, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - project: Project4bV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + project: Project4bV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.project = project diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2+Schema.swift index 84a32e2cb8..9528d2576d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post5V2 { +public extension Post5V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case editors @@ -19,10 +19,10 @@ extension Post5V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post5V2 = Post5V2.keys model.pluralName = "Post5V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2.swift index 3165ee7f99..1090df258b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2.swift @@ -16,20 +16,26 @@ public struct Post5V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - editors: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + editors: List? = [] + ) { + self.init( + id: id, title: title, editors: editors, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - editors: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + editors: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.editors = editors diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift index cdbcd3e07d..23a7be5848 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension PostEditor5V2 { +public extension PostEditor5V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post5V2 case user5V2 @@ -19,10 +19,10 @@ extension PostEditor5V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let postEditor5V2 = PostEditor5V2.keys model.pluralName = "PostEditor5V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2.swift index f78bbe9420..dabb434aac 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2.swift @@ -16,20 +16,26 @@ public struct PostEditor5V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - post5V2: Post5V2, - user5V2: User5V2) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + post5V2: Post5V2, + user5V2: User5V2 + ) { + self.init( + id: id, post5V2: post5V2, user5V2: user5V2, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - post5V2: Post5V2, - user5V2: User5V2, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + post5V2: Post5V2, + user5V2: User5V2, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.post5V2 = post5V2 self.user5V2 = user5V2 diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2+Schema.swift index 5c35bd5ad9..a15d33b3ab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension User5V2 { +public extension User5V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case username case posts @@ -19,10 +19,10 @@ extension User5V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let user5V2 = User5V2.keys model.pluralName = "User5V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2.swift index 7329a37803..dbf049a0f0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2.swift @@ -16,20 +16,26 @@ public struct User5V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - username: String, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + username: String, + posts: List? = [] + ) { + self.init( + id: id, username: username, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - username: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + username: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.username = username self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2+Schema.swift index 0c2d801a88..280cafde47 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Blog6V2 { +public extension Blog6V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts @@ -19,10 +19,10 @@ extension Blog6V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog6V2 = Blog6V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2.swift index 1d1c62c34c..b4cbf30247 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2.swift @@ -16,20 +16,26 @@ public struct Blog6V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2+Schema.swift index 2d8fe7959c..cb476aa8cc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment6V2 { +public extension Comment6V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post case content @@ -19,10 +19,10 @@ extension Comment6V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment6V2 = Comment6V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2.swift index f975f70fb2..027da3fbc5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2.swift @@ -16,20 +16,26 @@ public struct Comment6V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - post: Post6V2? = nil, - content: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + post: Post6V2? = nil, + content: String + ) { + self.init( + id: id, post: post, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - post: Post6V2? = nil, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + post: Post6V2? = nil, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.post = post self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2+Schema.swift index 5e96bf8cd9..8322b709e5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post6V2 { +public extension Post6V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case blog @@ -20,10 +20,10 @@ extension Post6V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post6V2 = Post6V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2.swift index bebe11af46..c955a6e87e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2.swift @@ -17,23 +17,29 @@ public struct Post6V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - blog: Blog6V2? = nil, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + blog: Blog6V2? = nil, + comments: List? = [] + ) { + self.init( + id: id, title: title, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - blog: Blog6V2? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + blog: Blog6V2? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.blog = blog diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2+Schema.swift index 84fa41ace3..5e2f6f64ca 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Blog7V2 { +public extension Blog7V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts @@ -19,10 +19,10 @@ extension Blog7V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog7V2 = Blog7V2.keys model.pluralName = "Blog7V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2.swift index e963392ee5..537cd210a4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2.swift @@ -16,20 +16,26 @@ public struct Blog7V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2+Schema.swift index 0f71ceb037..077286678f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment7V2 { +public extension Comment7V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post @@ -19,10 +19,10 @@ extension Comment7V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment7V2 = Comment7V2.keys model.pluralName = "Comment7V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2.swift index 317bef7b62..fa9b8c14ec 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2.swift @@ -16,20 +16,26 @@ public struct Comment7V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post7V2? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post7V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post7V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post7V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2+Schema.swift index e16552145c..18d5da8dc9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post7V2 { +public extension Post7V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case blog @@ -20,10 +20,10 @@ extension Post7V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post7V2 = Post7V2.keys model.pluralName = "Post7V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2.swift index a1cb3dfb84..e6fe9a9aab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2.swift @@ -17,23 +17,29 @@ public struct Post7V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - blog: Blog7V2? = nil, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + blog: Blog7V2? = nil, + comments: List? = [] + ) { + self.init( + id: id, title: title, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - blog: Blog7V2? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + blog: Blog7V2? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.blog = blog diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift index d77a61d5ee..aa10f9edd5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Attendee8V2 { +public extension Attendee8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case meetings case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let attendee8V2 = Attendee8V2.keys model.pluralName = "Attendee8V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2.swift index bdb90d7726..1ae9221f59 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2.swift @@ -15,17 +15,23 @@ public struct Attendee8V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - meetings: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + meetings: List? = [] + ) { + self.init( + id: id, meetings: meetings, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - meetings: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + meetings: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.meetings = meetings self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift index ea734e16d1..540f9e81b7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Meeting8V2 { +public extension Meeting8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case attendees @@ -19,10 +19,10 @@ extension Meeting8V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let meeting8V2 = Meeting8V2.keys model.pluralName = "Meeting8V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2.swift index 84abbbdd0c..8101985510 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2.swift @@ -16,20 +16,26 @@ public struct Meeting8V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - attendees: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + attendees: List? = [] + ) { + self.init( + id: id, title: title, attendees: attendees, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - attendees: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + attendees: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.attendees = attendees diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2+Schema.swift index 72355ba4ea..303c84d91b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Registration8V2 { +public extension Registration8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case meeting case attendee @@ -19,10 +19,10 @@ extension Registration8V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let registration8V2 = Registration8V2.keys model.pluralName = "Registration8V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2.swift index f9d2aa3b4b..3c572b4969 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2.swift @@ -16,20 +16,26 @@ public struct Registration8V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - meeting: Meeting8V2, - attendee: Attendee8V2) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + meeting: Meeting8V2, + attendee: Attendee8V2 + ) { + self.init( + id: id, meeting: meeting, attendee: attendee, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - meeting: Meeting8V2, - attendee: Attendee8V2, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + meeting: Meeting8V2, + attendee: Attendee8V2, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.meeting = meeting self.attendee = attendee diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift index f760ef2c9c..fae219e308 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CustomerMultipleSecondaryIndexV2 { +public extension CustomerMultipleSecondaryIndexV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case phoneNumber @@ -21,10 +21,10 @@ extension CustomerMultipleSecondaryIndexV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerMultipleSecondaryIndexV2 = CustomerMultipleSecondaryIndexV2.keys model.pluralName = "CustomerMultipleSecondaryIndexV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift index 7e92f12052..1c4e60e2d5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift @@ -18,26 +18,32 @@ public struct CustomerMultipleSecondaryIndexV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - age: Int, - accountRepresentativeID: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + age: Int, + accountRepresentativeID: String + ) { + self.init( + id: id, name: name, phoneNumber: phoneNumber, age: age, accountRepresentativeID: accountRepresentativeID, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - age: Int, - accountRepresentativeID: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + age: Int, + accountRepresentativeID: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.phoneNumber = phoneNumber diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift index 3058f7d566..1118ef8ca6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CustomerSecondaryIndexV2 { +public extension CustomerSecondaryIndexV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case phoneNumber @@ -20,10 +20,10 @@ extension CustomerSecondaryIndexV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerSecondaryIndexV2 = CustomerSecondaryIndexV2.keys model.pluralName = "CustomerSecondaryIndexV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2.swift index e6e0d76c04..195405ac60 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2.swift @@ -17,23 +17,29 @@ public struct CustomerSecondaryIndexV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - accountRepresentativeID: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + accountRepresentativeID: String + ) { + self.init( + id: id, name: name, phoneNumber: phoneNumber, accountRepresentativeID: accountRepresentativeID, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - accountRepresentativeID: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + accountRepresentativeID: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.phoneNumber = phoneNumber diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift index 40e8c0f7ce..021d8bfa84 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CustomerWithMultipleFieldsinPK { +public extension CustomerWithMultipleFieldsinPK { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case dob case date @@ -25,10 +25,10 @@ extension CustomerWithMultipleFieldsinPK { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerWithMultipleFieldsinPK = CustomerWithMultipleFieldsinPK.keys model.pluralName = "CustomerWithMultipleFieldsinPKs" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift index 32293d9975..0ae721e741 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift @@ -22,16 +22,19 @@ public struct CustomerWithMultipleFieldsinPK: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - date: Temporal.Date, - time: Temporal.Time, - phoneNumber: Int, - priority: Priority, - height: Double, - firstName: String? = nil, - lastName: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + date: Temporal.Date, + time: Temporal.Time, + phoneNumber: Int, + priority: Priority, + height: Double, + firstName: String? = nil, + lastName: String? = nil + ) { + self.init( + id: id, dob: dob, date: date, time: time, @@ -41,19 +44,22 @@ public struct CustomerWithMultipleFieldsinPK: Model { firstName: firstName, lastName: lastName, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - date: Temporal.Date, - time: Temporal.Time, - phoneNumber: Int, - priority: Priority, - height: Double, - firstName: String? = nil, - lastName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + date: Temporal.Date, + time: Temporal.Time, + phoneNumber: Int, + priority: Priority, + height: Double, + firstName: String? = nil, + lastName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.dob = dob self.date = date diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift index 03ace0efac..9f21d12e70 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Blog8 { +public extension Blog8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case customs @@ -21,10 +21,10 @@ extension Blog8 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog8 = Blog8.keys model.pluralName = "Blog8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8.swift index 92c1ccae48..48aa59e7fc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8.swift @@ -18,26 +18,32 @@ public struct Blog8: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [] + ) { + self.init( + id: id, name: name, customs: customs, notes: notes, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.customs = customs diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift index 6258c76ca6..f2e773e8ee 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment8 { +public extension Comment8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post @@ -19,10 +19,10 @@ extension Comment8 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment8 = Comment8.keys model.pluralName = "Comment8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8.swift index 4a0042140e..d6fa843ba3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8.swift @@ -16,20 +16,26 @@ public struct Comment8: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift index 27f611af59..85693fb8fa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension MyCustomModel8 { +public extension MyCustomModel8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case desc case children } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let myCustomModel8 = MyCustomModel8.keys model.pluralName = "MyCustomModel8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift index 1d18ede96f..206fee3987 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension MyNestedModel8 { +public extension MyNestedModel8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case nestedName case notes } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let myNestedModel8 = MyNestedModel8.keys model.pluralName = "MyNestedModel8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift index bd21917eb4..5cf1fb9e29 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post8 { +public extension Post8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case randomId @@ -21,10 +21,10 @@ extension Post8 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post8 = Post8.keys model.pluralName = "Post8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8.swift index 306eb3395b..09bec3b160 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8.swift @@ -18,26 +18,32 @@ public struct Post8: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8? = nil, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8? = nil, + comments: List? = [] + ) { + self.init( + id: id, name: name, randomId: randomId, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.randomId = randomId diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift index 5d527c5bdf..59af4deb74 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension SchemaDrift { +public extension SchemaDrift { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case enumValue case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let schemaDrift = SchemaDrift.keys model.pluralName = "SchemaDrifts" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift index dfac48fda6..b6159e7589 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift @@ -30,17 +30,23 @@ public struct SchemaDrift: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - enumValue: EnumDrift? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + enumValue: EnumDrift? = nil + ) { + self.init( + id: id, enumValue: enumValue, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - enumValue: EnumDrift? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + enumValue: EnumDrift? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.enumValue = enumValue self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift index 716f4848fe..2ed40a52b9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension TodoCustomTimestampV2 { +public extension TodoCustomTimestampV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdOn case updatedOn } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todoCustomTimestampV2 = TodoCustomTimestampV2.keys model.pluralName = "TodoCustomTimestampV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2.swift index 4bad844e17..97842a31a0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2.swift @@ -15,17 +15,23 @@ public struct TodoCustomTimestampV2: Model { public var createdOn: Temporal.DateTime? public var updatedOn: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdOn: nil, - updatedOn: nil) + updatedOn: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdOn: Temporal.DateTime? = nil, - updatedOn: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdOn: Temporal.DateTime? = nil, + updatedOn: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdOn = createdOn diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift index 6de5d45ae2..0e390adf51 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension TodoWithDefaultValueV2 { +public extension TodoWithDefaultValueV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todoWithDefaultValueV2 = TodoWithDefaultValueV2.keys model.pluralName = "TodoWithDefaultValueV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2.swift index dd622e15fc..75c66e59c2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2.swift @@ -15,17 +15,23 @@ public struct TodoWithDefaultValueV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User+Schema.swift index 7e59a9d0a7..45eed23650 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension User { +public extension User { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case following case followers } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let user = User.keys model.listPluralName = "Users" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User.swift index e3bf9a2bb1..cd852353ea 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User.swift @@ -15,10 +15,12 @@ public struct User: Model { public var following: List? public var followers: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String, following: List? = [], - followers: List? = []) { + followers: List? = [] + ) { self.id = id self.name = name self.following = following diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers+Schema.swift index 61de3ccd2a..657a4f854e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension UserFollowers { +public extension UserFollowers { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case user case followersUser } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let userFollowers = UserFollowers.keys model.listPluralName = "UserFollowers" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers.swift index 5c2f851f90..ccbc4f0e10 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers.swift @@ -14,9 +14,11 @@ public struct UserFollowers: Model { public var user: User? public var followersUser: User? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, user: User? = nil, - followersUser: User? = nil) { + followersUser: User? = nil + ) { self.id = id self.user = user self.followersUser = followersUser diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing+Schema.swift index d3dec6d064..4788315076 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension UserFollowing { +public extension UserFollowing { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case user case followingUser } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let userFollowing = UserFollowing.keys model.listPluralName = "UserFollowings" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing.swift index a545803ac3..cc61a04a54 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing.swift @@ -14,9 +14,11 @@ public struct UserFollowing: Model { public var user: User? public var followingUser: User? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, user: User? = nil, - followingUser: User? = nil) { + followingUser: User? = nil + ) { self.id = id self.user = user self.followingUser = followingUser diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/SubscriptionEndToEndTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/SubscriptionEndToEndTests.swift index 3642428f98..34436cc5f7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/SubscriptionEndToEndTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/SubscriptionEndToEndTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Combine import AWSPluginsCore +import Combine +import XCTest @testable import Amplify @testable import AWSDataStorePlugin @@ -77,7 +77,7 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { XCTAssertEqual(createdPost?.content, originalContent) XCTAssertEqual(createSyncData?.syncMetadata.version, 1) XCTAssertEqual(createSyncData?.syncMetadata.deleted, false) - + // Act: send update mutation try await sendUpdateRequest(forId: id, content: updatedContent, version: 1) await fulfillment(of: [updateReceived], timeout: 10) @@ -89,7 +89,7 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { XCTAssertEqual(updatedPost?.content, updatedContent) XCTAssertEqual(updateSyncData?.syncMetadata.version, 2) XCTAssertEqual(updateSyncData?.syncMetadata.deleted, false) - + // Act: send delete mutation try await sendDeleteRequest(forId: id, version: 2) await fulfillment(of: [deleteReceived], timeout: 10) @@ -108,7 +108,8 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { title updatedAt __typename _version _deleted _lastChangedAt } } """ - let input: [String: Any] = ["input": + let input: [String: Any] = [ + "input": [ "id": id, "title": Optional("This is a new post I created"), @@ -120,10 +121,12 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { ] ] - let request = GraphQLRequest(document: document, - variables: input, - responseType: Post.self, - decodePath: "createPost") + let request = GraphQLRequest( + document: document, + variables: input, + responseType: Post.self, + decodePath: "createPost" + ) let graphQLResult = try await Amplify.API.mutate(request: request) switch graphQLResult { @@ -142,7 +145,8 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { title updatedAt __typename _version _deleted _lastChangedAt } } """ - let input: [String: Any] = ["input": + let input: [String: Any] = [ + "input": [ "id": id, "content": content, @@ -150,10 +154,12 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { ] ] - let request = GraphQLRequest(document: document, - variables: input, - responseType: Post.self, - decodePath: "updatePost") + let request = GraphQLRequest( + document: document, + variables: input, + responseType: Post.self, + decodePath: "updatePost" + ) let graphQLResult = try await Amplify.API.mutate(request: request) switch graphQLResult { @@ -172,17 +178,20 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { title updatedAt __typename _version _deleted _lastChangedAt } } """ - let input: [String: Any] = ["input": + let input: [String: Any] = [ + "input": [ "id": id, "_version": version ] ] - let request = GraphQLRequest(document: document, - variables: input, - responseType: Post.self, - decodePath: "deletePost") + let request = GraphQLRequest( + document: document, + variables: input, + responseType: Post.self, + decodePath: "deletePost" + ) let graphQLResult = try await Amplify.API.mutate(request: request) switch graphQLResult { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreInternal.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreInternal.swift index 84e7fb7f9b..beae3433c0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreInternal.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreInternal.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import Foundation @testable import Amplify @testable import AWSDataStorePlugin -import Foundation -struct DataStoreInternal { +enum DataStoreInternal { static var dbFilePath: URL? { getAdapter()?.dbFilePath } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreTestBase.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreTestBase.swift index af43355440..c59161451e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreTestBase.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation import XCTest -import Amplify class DataStoreTestBase: XCTestCase { - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/SyncEngineIntegrationTestBase.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/SyncEngineIntegrationTestBase.swift index 33be2c76f0..846f847f06 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/SyncEngineIntegrationTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/SyncEngineIntegrationTestBase.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Combine import AWSAPIPlugin +import Combine +import XCTest @testable import Amplify @testable import AWSDataStorePlugin @@ -79,11 +79,11 @@ class SyncEngineIntegrationTestBase: DataStoreTestBase { return } } - + func stopDataStore() async throws { try await Amplify.DataStore.stop() } - + func clearDataStore() async throws { try await Amplify.DataStore.clear() } @@ -125,5 +125,5 @@ class SyncEngineIntegrationTestBase: DataStoreTestBase { await fulfillment(of: [eventReceived], timeout: 10) } - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/AWSDataStoreLazyLoadPostComment4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/AWSDataStoreLazyLoadPostComment4V2.swift index 9a315baed5..aefb9f3ed7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/AWSDataStoreLazyLoadPostComment4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/AWSDataStoreLazyLoadPostComment4V2.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @@ -17,7 +17,7 @@ class AWSDataStoreLazyLoadPostComment4V2: AWSDataStoreLazyLoadBaseTest { await setup(withModels: PostComment4V2Models()) let post = Post4V2(title: "title") let comment = Comment4V2(content: "content", post: post) - + let commentSynced = expectation(description: "DataStore start success") let mutationEvents = Amplify.DataStore.observe(Comment4V2.self) Task { @@ -31,10 +31,10 @@ class AWSDataStoreLazyLoadPostComment4V2: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed with error \(error)") } } - + try await Amplify.DataStore.save(post) try await Amplify.DataStore.save(comment) - + await fulfillment(of: [commentSynced], timeout: 10) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2SnapshotTests.swift index b7b294b081..f08dcd0bc8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2SnapshotTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPostComment4V2Tests { - + func testPostSelectionSets() { setUpModelRegistrationOnly(withModels: PostComment4V2Models()) continueAfterFailure = true @@ -35,7 +35,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: post, modelSchema: Post.schema) let updateDocument = """ @@ -53,7 +53,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: post, modelSchema: Post.schema) let deleteDocument = """ @@ -71,7 +71,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -89,7 +89,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -107,7 +107,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -125,7 +125,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -148,13 +148,13 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testCommentSelectionSets() { setUpModelRegistrationOnly(withModels: PostComment4V2Models()) continueAfterFailure = true let post = Post(title: "title") let comment = Comment(content: "content", post: post) - + // Create let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) let createDocument = """ @@ -182,7 +182,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: comment, modelSchema: Comment.schema) let updateDocument = """ @@ -210,7 +210,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: comment, modelSchema: Comment.schema) let deleteDocument = """ @@ -238,7 +238,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Comment.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -261,7 +261,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -284,7 +284,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -307,7 +307,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Comment.self) let syncDocument = """ @@ -335,5 +335,5 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2StressTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2StressTests.swift index 260534710f..30e8aee057 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2StressTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2StressTests.swift @@ -5,19 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest import Amplify -import AWSPluginsCore import AWSDataStorePlugin +import AWSPluginsCore extension AWSDataStoreLazyLoadPostComment4V2Tests { static let loggingContext = "multiSaveWithInterruptions" - /// Test performing save's and stop/start concurrently. + /// Test performing save's and stop/start concurrently. /// /// This test was validated prior to [PR 3492](https://github.com/aws-amplify/amplify-swift/pull/3492) /// and will fail. The failure will show up when the test asserts that a queried comment from AppSync should contain the associated @@ -63,7 +63,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { /// The minimum number of iterations, through trial and error, found to reproduce the bug. private let count = 15 - + /// `isOutboxEmpty` is used to return the flow back to the caller via fulfilling the `savesSyncedExpectation`. /// By listening to the OutboxEvent after performing the operations, the last outboxEvent to be `true` while `index` /// is the last index, will be when `savesSyncedExpectation` is fulfilled and returned execution back to the caller. @@ -82,10 +82,10 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { while isOutboxEmpty == false { try await Task.sleep(seconds: 1) } - for i in 0...createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveComment() async throws { await setup(withModels: PostComment4V2Models()) try await startAndWaitForReady() @@ -289,18 +319,18 @@ class AWSDataStoreLazyLoadPostComment4V2Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: PostComment4V2Models()) try await startAndWaitForReady() @@ -322,27 +352,27 @@ class AWSDataStoreLazyLoadPostComment4V2Tests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + snapshotReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryComment() async throws { await setup(withModels: PostComment4V2Models()) try await startAndWaitForReady() - + let post = Post(title: "title") let savedPost = try await createAndWaitForSync(post) let comment = Comment(content: "content", post: post) @@ -356,14 +386,14 @@ class AWSDataStoreLazyLoadPostComment4V2Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -372,7 +402,7 @@ class AWSDataStoreLazyLoadPostComment4V2Tests: AWSDataStoreLazyLoadBaseTest { extension AWSDataStoreLazyLoadPostComment4V2Tests { typealias Post = Post4V2 typealias Comment = Comment4V2 - + struct PostComment4V2Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2+Schema.swift index 225bbfd4fd..448c925ca0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment4V2 { +public extension Comment4V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let comment4V2 = Comment4V2.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Comment4V2s" - + model.attributes( .index(fields: ["postID", "content"], name: "byPost4"), .primaryKey(fields: [comment4V2.id]) ) - + model.fields( .field(comment4V2.id, is: .required, ofType: .string), .field(comment4V2.content, is: .required, ofType: .string), @@ -37,29 +44,29 @@ extension Comment4V2 { .field(comment4V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment4V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Comment4V2 { - public var id: FieldPath { +public extension ModelPath where ModelType == Comment4V2 { + var id: FieldPath { string("id") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var post: ModelPath { + var post: ModelPath { Post4V2.Path(name: "post", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2.swift index fe39f08abe..ee184a16d7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Comment4V2: Model { public let id: String public var content: String - internal var _post: LazyReference + var _post: LazyReference public var post: Post4V2? { get async throws { try await _post.get() @@ -13,21 +20,27 @@ public struct Comment4V2: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil) { - self.init(id: id, - content: content, - post: post, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil + ) { + self.init( + id: id, + content: content, + post: post, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct Comment4V2: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post4V2? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try values.decode(String.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try values.decode(String.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2+Schema.swift index 3caa6ac8cd..9f73e2b710 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post4V2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post4V2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post4V2 = Post4V2.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Post4V2s" - + model.attributes( .primaryKey(fields: [post4V2.id]) ) - + model.fields( .field(post4V2.id, is: .required, ofType: .string), .field(post4V2.title, is: .required, ofType: .string), @@ -36,10 +43,10 @@ extension Post4V2 { .field(post4V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post4V2: ModelIdentifiable { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2.swift index 08f3e4b429..9106744759 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post4V2: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7SnapshotTests.swift index a136207c79..a014bcd7b1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7SnapshotTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPostComment7Tests { @@ -35,7 +35,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: post, modelSchema: Post.schema) let updateDocument = """ @@ -53,7 +53,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: post, modelSchema: Post.schema) let deleteDocument = """ @@ -71,7 +71,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -89,7 +89,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -107,7 +107,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -125,7 +125,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -148,14 +148,16 @@ extension AWSDataStoreLazyLoadPostComment7Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testCommentSelectionSets() { setUpModelRegistrationOnly(withModels: PostComment7Models()) continueAfterFailure = true let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post: post) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post: post + ) // Create let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) let createDocument = """ @@ -183,7 +185,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: comment, modelSchema: Comment.schema) let updateDocument = """ @@ -211,7 +213,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: comment, modelSchema: Comment.schema) let deleteDocument = """ @@ -239,7 +241,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Comment.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -263,7 +265,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -287,7 +289,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -311,7 +313,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Comment.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7Tests.swift index 89462e259c..3e30afd2ce 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7Tests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest { @@ -19,7 +19,7 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest let post = Post(postId: UUID().uuidString, title: "title") try await createAndWaitForSync(post) } - + func testSaveComment() async throws { await setup(withModels: PostComment7Models()) try await startAndWaitForReady() @@ -28,10 +28,10 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) } - + func testLazyLoad() async throws { await setup(withModels: PostComment7Models()) - + let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) let savedPost = try await createAndWaitForSync(post) @@ -43,73 +43,91 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest let queriedPost = try await query(for: savedPost) try await assertPost(queriedPost, canLazyLoad: savedComment) } - - func assertComment(_ comment: Comment, - hasEagerLoaded post: Post) async throws { - assertLazyReference(comment._post, - state: .loaded(model: post)) - + + func assertComment( + _ comment: Comment, + hasEagerLoaded post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) + guard let loadedPost = try await comment.post else { XCTFail("Failed to retrieve the post from the comment") return } XCTAssertEqual(loadedPost.postId, post.postId) - + // retrieve loaded model guard let loadedPost = try await comment.post else { XCTFail("Failed to retrieve the loaded post from the comment") return } XCTAssertEqual(loadedPost.postId, post.postId) - + try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertComment(_ comment: Comment, - canLazyLoad post: Post) async throws { - assertLazyReference(comment._post, - state: .notLoaded(identifiers: [ - .init(name: Post7.keys.postId.stringValue, value: post.postId), - .init(name: Post7.keys.title.stringValue, value: post.title) - ])) + + func assertComment( + _ comment: Comment, + canLazyLoad post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .notLoaded(identifiers: [ + .init(name: Post7.keys.postId.stringValue, value: post.postId), + .init(name: Post7.keys.title.stringValue, value: post.title) + ]) + ) guard let loadedPost = try await comment.post else { XCTFail("Failed to load the post from the comment") return } XCTAssertEqual(loadedPost.postId, post.postId) - assertLazyReference(comment._post, - state: .loaded(model: post)) + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertPost(_ post: Post, - canLazyLoad comment: Comment) async throws { + + func assertPost( + _ post: Post, + canLazyLoad comment: Comment + ) async throws { guard let comments = post.comments else { XCTFail("Missing comments on post") return } - assertList(comments, state: .isNotLoaded(associatedIds: [post.identifier], - associatedFields: ["post"])) + assertList(comments, state: .isNotLoaded( + associatedIds: [post.identifier], + associatedFields: ["post"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) guard let comment = comments.first else { XCTFail("Missing lazy loaded comment from post") return } - assertLazyReference(comment._post, - state: .notLoaded(identifiers: [ - .init(name: Post7.keys.postId.stringValue, value: post.postId), - .init(name: Post7.keys.title.stringValue, value: post.title) - ])) + assertLazyReference( + comment._post, + state: .notLoaded(identifiers: [ + .init(name: Post7.keys.postId.stringValue, value: post.postId), + .init(name: Post7.keys.title.stringValue, value: post.title) + ]) + ) } - + func testSaveWithoutPost() async throws { await setup(withModels: PostComment7Models()) let comment = Comment(commentId: UUID().uuidString, content: "content") let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: nil) + ) let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) queriedComment.setPost(savedPost) @@ -117,7 +135,7 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: saveCommentWithPost) try await assertComment(queriedComment2, canLazyLoad: post) } - + func testUpdateFromQueriedComment() async throws { await setup(withModels: PostComment7Models()) let post = Post(postId: UUID().uuidString, title: "title") @@ -125,30 +143,34 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) let queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.postId.stringValue, value: post.postId), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.postId.stringValue, value: post.postId), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) let savedQueriedComment = try await updateAndWaitForSync(queriedComment) let queriedComment2 = try await query(for: savedQueriedComment) try await assertComment(queriedComment2, canLazyLoad: savedPost) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostComment7Models()) - + let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.postId.stringValue, value: post.postId), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) - + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.postId.stringValue, value: post.postId), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) + let newPost = Post(postId: UUID().uuidString, title: "title") _ = try await createAndWaitForSync(newPost) queriedComment.setPost(newPost) @@ -156,31 +178,35 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: saveCommentWithNewPost) try await assertComment(queriedComment2, canLazyLoad: newPost) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostComment7Models()) - + let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.postId.stringValue, value: post.postId), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) - + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.postId.stringValue, value: post.postId), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) + queriedComment.setPost(nil) let saveCommentRemovePost = try await updateAndWaitForSync(queriedComment) let queriedCommentNoPost = try await query(for: saveCommentRemovePost) - assertLazyReference(queriedCommentNoPost._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedCommentNoPost._post, + state: .notLoaded(identifiers: nil) + ) } - + func testDelete() async throws { await setup(withModels: PostComment7Models()) - + let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) let savedPost = try await createAndWaitForSync(post) @@ -189,7 +215,7 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest try await assertModelDoesNotExist(savedComment) try await assertModelDoesNotExist(savedPost) } - + func testObservePost() async throws { await setup(withModels: PostComment7Models()) try await startAndWaitForReady() @@ -203,7 +229,7 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest version == 1, let receivedPost = try? mutationEvent.decodeModel(as: Post.self), receivedPost.postId == post.postId { - + try await createAndWaitForSync(comment) guard let comments = receivedPost.comments else { XCTFail("Lazy List does not exist") @@ -215,23 +241,23 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveComment() async throws { await setup(withModels: PostComment7Models()) try await startAndWaitForReady() @@ -251,18 +277,18 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: PostComment7Models()) try await startAndWaitForReady() @@ -284,27 +310,27 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + snapshotReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryComment() async throws { await setup(withModels: PostComment7Models()) try await startAndWaitForReady() - + let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) @@ -318,14 +344,14 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -334,7 +360,7 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest extension AWSDataStoreLazyLoadPostComment7Tests { typealias Post = Post7 typealias Comment = Comment7 - + struct PostComment7Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7+Schema.swift index 2850d94c8d..1cb4ae68a7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment7 { +public extension Comment7 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case commentId case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let comment7 = Comment7.keys - + model.pluralName = "Comment7s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .index(fields: ["postId", "postTitle"], name: "byPost"), .primaryKey(fields: [comment7.commentId, comment7.content]) ) - + model.fields( .field(comment7.commentId, is: .required, ofType: .string), .field(comment7.content, is: .required, ofType: .string), @@ -34,9 +41,9 @@ extension Comment7 { .field(comment7.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment7: ModelIdentifiable { @@ -44,26 +51,28 @@ extension Comment7: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment7.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment7.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == Comment7 { - public var commentId: FieldPath { +public extension ModelPath where ModelType == Comment7 { + var commentId: FieldPath { string("commentId") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var post: ModelPath { + var post: ModelPath { Post7.Path(name: "post", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7.swift index ff1a8abfae..dd9775521a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Comment7: Model { public let commentId: String public let content: String - internal var _post: LazyReference + var _post: LazyReference public var post: Post7? { get async throws { try await _post.get() @@ -13,21 +20,27 @@ public struct Comment7: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(commentId: String, - content: String, - post: Post7? = nil) { - self.init(commentId: commentId, - content: content, - post: post, - createdAt: nil, - updatedAt: nil) + + public init( + commentId: String, + content: String, + post: Post7? = nil + ) { + self.init( + commentId: commentId, + content: content, + post: post, + createdAt: nil, + updatedAt: nil + ) } - internal init(commentId: String, - content: String, - post: Post7? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + commentId: String, + content: String, + post: Post7? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.commentId = commentId self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct Comment7: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post7? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - commentId = try values.decode(String.self, forKey: .commentId) - content = try values.decode(String.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.commentId = try values.decode(String.self, forKey: .commentId) + self.content = try values.decode(String.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7+Schema.swift index 2a1cf86992..a110e8378b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post7 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post7 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post7 = Post7.keys - + model.pluralName = "Post7s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post7.postId, post7.title]) ) - + model.fields( .field(post7.postId, is: .required, ofType: .string), .field(post7.title, is: .required, ofType: .string), @@ -33,10 +40,10 @@ extension Post7 { .field(post7.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post7: ModelIdentifiable { @@ -44,10 +51,12 @@ extension Post7: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post7.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post7.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7.swift index 8cb750a96d..c07fbc8320 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post7: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8SnapshotTests.swift index ae70c2d65f..e4c629cc1f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8SnapshotTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPostComment8Tests { @@ -35,7 +35,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: post, modelSchema: Post.schema) let updateDocument = """ @@ -53,7 +53,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: post, modelSchema: Post.schema) let deleteDocument = """ @@ -71,7 +71,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -89,7 +89,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -107,7 +107,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -125,7 +125,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -148,15 +148,17 @@ extension AWSDataStoreLazyLoadPostComment8Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testCommentSelectionSets() { setUpModelRegistrationOnly(withModels: PostComment8Models()) continueAfterFailure = true let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) // Create let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) let createDocument = """ @@ -176,7 +178,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: comment, modelSchema: Comment.schema) let updateDocument = """ @@ -196,7 +198,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: comment, modelSchema: Comment.schema) let deleteDocument = """ @@ -216,7 +218,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Comment.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -236,7 +238,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -256,7 +258,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -276,7 +278,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Comment.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8Tests.swift index a6375821d1..ed9d26bfe1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8Tests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest { @@ -19,27 +19,31 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest let post = Post(postId: UUID().uuidString, title: "title") try await createAndWaitForSync(post) } - + func testSaveComment() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) try await createAndWaitForSync(post) try await createAndWaitForSync(comment) } - + func testLazyLoad() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) assertComment(savedComment, contains: savedPost) @@ -49,25 +53,29 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest let queriedPost = try await query(for: savedPost) try await assertPost(queriedPost, canLazyLoad: savedComment) } - + func assertComment(_ comment: Comment, contains post: Post) { XCTAssertEqual(comment.postId, post.postId) XCTAssertEqual(comment.postTitle, post.title) } - + func assertCommentDoesNotContainPost(_ comment: Comment) { XCTAssertNil(comment.postId) XCTAssertNil(comment.postTitle) } - - func assertPost(_ post: Post, - canLazyLoad comment: Comment) async throws { + + func assertPost( + _ post: Post, + canLazyLoad comment: Comment + ) async throws { guard let comments = post.comments else { XCTFail("Missing comments on post") return } - assertList(comments, state: .isNotLoaded(associatedIds: [post.postId, post.title], - associatedFields: ["postId", "postTitle"])) + assertList(comments, state: .isNotLoaded( + associatedIds: [post.postId, post.title], + associatedFields: ["postId", "postTitle"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) guard let comment = comments.first else { @@ -76,7 +84,7 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest } assertComment(comment, contains: post) } - + func testSaveWithoutPost() async throws { await setup(withModels: PostComment8Models()) let comment = Comment(commentId: UUID().uuidString, content: "content") @@ -91,14 +99,16 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: saveCommentWithPost) assertComment(queriedComment2, contains: post) } - + func testUpdateFromQueriedComment() async throws { await setup(withModels: PostComment8Models()) let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) let queriedComment = try await query(for: savedComment) @@ -107,15 +117,17 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: savedQueriedComment) assertComment(queriedComment2, contains: savedPost) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) @@ -128,55 +140,61 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: saveCommentWithNewPost) assertComment(queriedComment2, contains: newPost) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) assertComment(queriedComment, contains: post) - + queriedComment.postId = nil queriedComment.postTitle = nil - + let saveCommentRemovePost = try await updateAndWaitForSync(queriedComment) let queriedCommentNoPost = try await query(for: saveCommentRemovePost) assertCommentDoesNotContainPost(queriedCommentNoPost) } - + func testDelete() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) try await deleteAndWaitForSync(savedPost) - + // The expected behavior when deleting a post should be that the // child models are deleted (comment) followed by the parent model (post). try await assertModelDoesNotExist(savedPost) // Is there a way to delete the children models in uni directional relationships? try await assertModelExists(savedComment) } - + func testObservePost() async throws { await setup(withModels: PostComment8Models()) try await startAndWaitForReady() let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Post.self) Task { @@ -191,27 +209,29 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveComment() async throws { await setup(withModels: PostComment8Models()) try await startAndWaitForReady() let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Comment.self) Task { @@ -225,26 +245,28 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: PostComment8Models()) try await startAndWaitForReady() let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Post.self, where: Post.keys.postId == post.postId) Task { @@ -256,28 +278,30 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryComment() async throws { await setup(withModels: PostComment8Models()) try await startAndWaitForReady() - + let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Comment.self, where: Comment.keys.commentId == comment.commentId) Task { @@ -288,14 +312,14 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -304,7 +328,7 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest extension AWSDataStoreLazyLoadPostComment8Tests { typealias Post = Post8 typealias Comment = Comment8 - + struct PostComment8Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8+Schema.swift index 1f74e46906..2f2568baef 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case commentId case content case postId @@ -12,21 +19,21 @@ extension Comment8 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment8 = Comment8.keys - + model.pluralName = "Comment8s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .index(fields: ["postId", "postTitle"], name: "byPost"), .primaryKey(fields: [comment8.commentId, comment8.content]) ) - + model.fields( .field(comment8.commentId, is: .required, ofType: .string), .field(comment8.content, is: .required, ofType: .string), @@ -36,10 +43,10 @@ extension Comment8 { .field(comment8.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment8: ModelIdentifiable { @@ -47,10 +54,12 @@ extension Comment8: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment8.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment8.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8.swift index 22fcd26a4b..0fc5456492 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Comment8: Model { public var postTitle: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(commentId: String, - content: String, - postId: String? = nil, - postTitle: String? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + postId: String? = nil, + postTitle: String? = nil + ) { + self.init( + commentId: commentId, content: content, postId: postId, postTitle: postTitle, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(commentId: String, - content: String, - postId: String? = nil, - postTitle: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + commentId: String, + content: String, + postId: String? = nil, + postTitle: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.commentId = commentId self.content = content self.postId = postId @@ -34,4 +47,4 @@ public struct Comment8: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8+Schema.swift index 3778ad3bfa..93f32fa772 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post8 = Post8.keys - + model.pluralName = "Post8s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post8.postId, post8.title]) ) - + model.fields( .field(post8.postId, is: .required, ofType: .string), .field(post8.title, is: .required, ofType: .string), @@ -33,10 +40,10 @@ extension Post8 { .field(post8.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post8: ModelIdentifiable { @@ -44,10 +51,12 @@ extension Post8: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post8.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post8.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8.swift index 440cd2b9d7..eb60ae8287 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post8: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildSansTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildSansTests.swift index 27c69259d8..68bcee2c5d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildSansTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildSansTests.swift @@ -5,34 +5,35 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadCompositePKTests { - + // MARK: - CompositePKParent / ChildSansBelongsTo - + func initChildSansBelongsTo(with parent: CompositePKParent) -> ChildSansBelongsTo { ChildSansBelongsTo( childId: UUID().uuidString, content: "content", compositePKParentChildrenSansBelongsToCustomId: parent.customId, - compositePKParentChildrenSansBelongsToContent: parent.content) + compositePKParentChildrenSansBelongsToContent: parent.content + ) } - + func testSaveChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initChildSansBelongsTo(with: savedParent) try await createAndWaitForSync(child) } - + func testUpdateChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -41,7 +42,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { var savedChild = try await createAndWaitForSync(child) XCTAssertEqual(savedChild.compositePKParentChildrenSansBelongsToCustomId, savedParent.customId) XCTAssertEqual(savedChild.compositePKParentChildrenSansBelongsToContent, savedParent.content) - + // update the child to a new parent let newParent = initParent() let savedNewParent = try await createAndWaitForSync(newParent) @@ -51,38 +52,43 @@ extension AWSDataStoreLazyLoadCompositePKTests { XCTAssertEqual(updatedChild.compositePKParentChildrenSansBelongsToCustomId, savedNewParent.customId) XCTAssertEqual(updatedChild.compositePKParentChildrenSansBelongsToContent, savedNewParent.content) } - + func testDeleteChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initChildSansBelongsTo(with: parent) let savedChild = try await createAndWaitForSync(child) - + try await deleteAndWaitForSync(savedChild) try await assertModelDoesNotExist(savedChild) - + try await deleteAndWaitForSync(savedParent) try await assertModelDoesNotExist(savedParent) } - + func testGetChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initChildSansBelongsTo(with: parent) let savedChild = try await createAndWaitForSync(child) - + // query parent and load the children let queriedParent = try await query(for: savedParent) - assertList(queriedParent.childrenSansBelongsTo!, state: .isNotLoaded(associatedIds: [queriedParent.customId, - queriedParent.content], - associatedFields: [ - "compositePKParentChildrenSansBelongsToCustomId", - "compositePKParentChildrenSansBelongsToContent"])) + assertList(queriedParent.childrenSansBelongsTo!, state: .isNotLoaded( + associatedIds: [ + queriedParent.customId, + queriedParent.content + ], + associatedFields: [ + "compositePKParentChildrenSansBelongsToCustomId", + "compositePKParentChildrenSansBelongsToContent" + ] + )) try await queriedParent.childrenSansBelongsTo?.fetch() assertList(queriedParent.childrenSansBelongsTo!, state: .isLoaded(count: 1)) - + // query children and verify the parent - ChildSansBelongsTo let queriedChildSansBelongsTo = try await query(for: savedChild) XCTAssertEqual(queriedChildSansBelongsTo.compositePKParentChildrenSansBelongsToCustomId, savedParent.customId) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildTests.swift index 531c18807d..df9deaa7bc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildTests.swift @@ -5,30 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadCompositePKTests { - + // MARK: - CompositePKParent / CompositePKChild - + func initChild(with parent: CompositePKParent? = nil) -> CompositePKChild { CompositePKChild(childId: UUID().uuidString, content: "content", parent: parent) } - + func testSaveCompositePKChild() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initChild(with: savedParent) try await createAndWaitForSync(child) } - + func testUpdateCompositePKChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -37,7 +37,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { var savedChild = try await createAndWaitForSync(child) let loadedParent = try await savedChild.parent XCTAssertEqual(loadedParent?.identifier, savedParent.identifier) - + // update the child to a new parent let newParent = initParent() let savedNewParent = try await createAndWaitForSync(newParent) @@ -46,60 +46,66 @@ extension AWSDataStoreLazyLoadCompositePKTests { let loadedNewParent = try await updatedChild.parent XCTAssertEqual(loadedNewParent?.identifier, savedNewParent.identifier) } - + func testUpdateFromNoParentCompositePKChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) - + let childWithoutParent = initChild() var savedChild = try await createAndWaitForSync(childWithoutParent) let nilParent = try await savedChild.parent XCTAssertNil(nilParent) - + // update the child to a parent savedChild.setParent(savedParent) let savedChildWithParent = try await updateAndWaitForSync(savedChild) let loadedParent = try await savedChildWithParent.parent XCTAssertEqual(loadedParent?.identifier, savedParent.identifier) } - + func testDeleteCompositePKChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initChild(with: parent) let savedChild = try await createAndWaitForSync(child) - + try await deleteAndWaitForSync(savedParent) try await assertModelDoesNotExist(savedParent) try await assertModelDoesNotExist(savedChild) } - + func testGetCompositePKChild() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initChild(with: parent) let savedCompositePKChild = try await createAndWaitForSync(child) - + // query parent and load the children let queriedParent = try await query(for: savedParent) - assertList(queriedParent.children!, state: .isNotLoaded(associatedIds: [queriedParent.identifier], - associatedFields: ["parent"])) + assertList(queriedParent.children!, state: .isNotLoaded( + associatedIds: [queriedParent.identifier], + associatedFields: ["parent"] + )) try await queriedParent.children?.fetch() assertList(queriedParent.children!, state: .isLoaded(count: 1)) - + // query child and load the parent - CompositePKChild let queriedCompositePKChild = try await query(for: savedCompositePKChild) - assertLazyReference(queriedCompositePKChild._parent, - state: .notLoaded(identifiers: [ - .init(name: CompositePKParent.keys.customId.stringValue, value: savedParent.customId), - .init(name: CompositePKParent.keys.content.stringValue, value: savedParent.content) - ])) + assertLazyReference( + queriedCompositePKChild._parent, + state: .notLoaded(identifiers: [ + .init(name: CompositePKParent.keys.customId.stringValue, value: savedParent.customId), + .init(name: CompositePKParent.keys.content.stringValue, value: savedParent.content) + ]) + ) let loadedParent = try await queriedCompositePKChild.parent - assertLazyReference(queriedCompositePKChild._parent, - state: .loaded(model: loadedParent)) + assertLazyReference( + queriedCompositePKChild._parent, + state: .loaded(model: loadedParent) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKImplicitTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKImplicitTests.swift index b2ffec5fd6..fa4134f8e6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKImplicitTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKImplicitTests.swift @@ -5,30 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadCompositePKTests { - + // MARK: - CompositePKParent / ImplicitChild - + func initImplicitChild(with parent: CompositePKParent) -> ImplicitChild { ImplicitChild(childId: UUID().uuidString, content: UUID().uuidString, parent: parent) } - + func testSaveImplicitChild() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initImplicitChild(with: savedParent) try await createAndWaitForSync(child) } - + func testUpdateImplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -37,7 +37,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { var savedChild = try await createAndWaitForSync(child) let loadedParent = try await savedChild.parent XCTAssertEqual(loadedParent.identifier, savedParent.identifier) - + // update the child to a new parent let newParent = initParent() let savedNewParent = try await createAndWaitForSync(newParent) @@ -45,47 +45,53 @@ extension AWSDataStoreLazyLoadCompositePKTests { let updatedChild = try await updateAndWaitForSync(savedChild) let loadedNewParent = try await updatedChild.parent XCTAssertEqual(loadedNewParent.identifier, savedNewParent.identifier) - + } - + func testDeleteImplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initImplicitChild(with: parent) let savedChild = try await createAndWaitForSync(child) - + try await deleteAndWaitForSync(savedChild) try await assertModelDoesNotExist(savedChild) try await deleteAndWaitForSync(savedParent) try await assertModelDoesNotExist(savedParent) } - + func testGetImplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initImplicitChild(with: parent) let savedChild = try await createAndWaitForSync(child) - + // query parent and load the children let queriedParent = try await query(for: savedParent) - - assertList(queriedParent.implicitChildren!, state: .isNotLoaded(associatedIds: [queriedParent.identifier], - associatedFields: ["parent"])) + + assertList(queriedParent.implicitChildren!, state: .isNotLoaded( + associatedIds: [queriedParent.identifier], + associatedFields: ["parent"] + )) try await queriedParent.implicitChildren?.fetch() assertList(queriedParent.implicitChildren!, state: .isLoaded(count: 1)) - - + + // query child and load the parent - ImplicitChild let queriedImplicitChild = try await query(for: savedChild) - assertLazyReference(queriedImplicitChild._parent, - state: .notLoaded(identifiers: [ - .init(name: CompositePKParent.keys.customId.stringValue, value: savedParent.customId), - .init(name: CompositePKParent.keys.content.stringValue, value: savedParent.content) - ])) + assertLazyReference( + queriedImplicitChild._parent, + state: .notLoaded(identifiers: [ + .init(name: CompositePKParent.keys.customId.stringValue, value: savedParent.customId), + .init(name: CompositePKParent.keys.content.stringValue, value: savedParent.content) + ]) + ) let loadedParent = try await queriedImplicitChild.parent - assertLazyReference(queriedImplicitChild._parent, - state: .loaded(model: loadedParent)) + assertLazyReference( + queriedImplicitChild._parent, + state: .loaded(model: loadedParent) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKSnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKSnapshotTests.swift index c135c6520c..334ec2b31e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKSnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKSnapshotTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadCompositePKTests { @@ -28,7 +28,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { - All subscription GraphQL requests on `CompositePKParent` model have correct selection set */ func testCompositePKParent_withGraphQLOperations_generateCorrectSelectionSets() { - Operation.allOperations(on: CompositePKParent.schema, model: CompositePKParent.self).forEach { operation in + for operation in Operation.allOperations(on: CompositePKParent.schema, model: CompositePKParent.self) { let expectedDocument = operation.expectedDocument XCTAssertNotNil(expectedDocument) XCTAssertEqual(operation.graphQLRequest?.document, expectedDocument) @@ -44,7 +44,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { - All subscription GraphQL requests on `CompositePKChild` model have correct selection set */ func testCompositePKChild_withGraphQLOperations_generateCorrectSelectionSets() { - Operation.allOperations(on: CompositePKChild.schema, model: CompositePKChild.self).forEach { operation in + for operation in Operation.allOperations(on: CompositePKChild.schema, model: CompositePKChild.self) { let expectedDocument = operation.expectedDocument XCTAssertNotNil(expectedDocument) XCTAssertEqual(operation.graphQLRequest?.document, expectedDocument) @@ -60,7 +60,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { - All subscription GraphQL requests on `ChildSansBelongsTo` model have correct selection set */ func testChildSansBelongsTo_withGraphQLOperations_generateCorrectSelectionSets() { - Operation.allOperations(on: ChildSansBelongsTo.schema, model: ChildSansBelongsTo.self).forEach { operation in + for operation in Operation.allOperations(on: ChildSansBelongsTo.schema, model: ChildSansBelongsTo.self) { let expectedDocument = operation.expectedDocument XCTAssertNotNil(expectedDocument) XCTAssertEqual(operation.graphQLRequest?.document, expectedDocument) @@ -76,7 +76,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { - All subscription GraphQL requests on `ImplicitChild` model have correct selection set */ func testImplicitChild_withGraphQLOperations_generateCorrectSelectionSets() { - Operation.allOperations(on: ImplicitChild.schema, model: ImplicitChild.self).forEach { operation in + for operation in Operation.allOperations(on: ImplicitChild.schema, model: ImplicitChild.self) { let expectedDocument = operation.expectedDocument XCTAssertNotNil(expectedDocument) XCTAssertEqual(operation.graphQLRequest?.document, expectedDocument) @@ -92,7 +92,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { - All subscription GraphQL requests on `StrangeExplicitChild` model have correct selection set */ func testStrangeExplicitChild_withGraphQLOperations_generateCorrectSelectionSets() { - Operation.allOperations(on: StrangeExplicitChild.schema, model: StrangeExplicitChild.self).forEach { operation in + for operation in Operation.allOperations(on: StrangeExplicitChild.schema, model: StrangeExplicitChild.self) { let expectedDocument = operation.expectedDocument XCTAssertNotNil(expectedDocument) XCTAssertEqual(operation.graphQLRequest?.document, expectedDocument) @@ -101,7 +101,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { } -fileprivate enum Operation { +private enum Operation { case mutation(String, ModelSchema, Model.Type) case subscription(GraphQLSubscriptionType, ModelSchema, Model.Type) @@ -171,7 +171,7 @@ fileprivate enum Operation { } } -fileprivate protocol RandomTestSampleInstance { +private protocol RandomTestSampleInstance { static func randomInstance() -> Model static func mutationDocument(operation: String) -> String static func subscriptionDocument(operation: GraphQLSubscriptionType) -> String diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKStrangeExplicitTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKStrangeExplicitTests.swift index 54bf4118c4..e1ab8867d2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKStrangeExplicitTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKStrangeExplicitTests.swift @@ -5,30 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadCompositePKTests { - + // MARK: - CompositePKParent / StrangeExplicitChild - + func initStrangeExplicitChild(with parent: CompositePKParent) -> StrangeExplicitChild { StrangeExplicitChild(strangeId: UUID().uuidString, content: "content", parent: parent) } - + func testSaveStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initStrangeExplicitChild(with: savedParent) try await createAndWaitForSync(child) } - + func testUpdateStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -37,7 +37,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { var savedChild = try await createAndWaitForSync(child) let loadedParent = try await savedChild.parent XCTAssertEqual(loadedParent.identifier, savedParent.identifier) - + // update the child to a new parent let newParent = initParent() let savedNewParent = try await createAndWaitForSync(newParent) @@ -45,46 +45,52 @@ extension AWSDataStoreLazyLoadCompositePKTests { let updatedChild = try await updateAndWaitForSync(savedChild) let loadedNewParent = try await updatedChild.parent XCTAssertEqual(loadedNewParent.identifier, savedNewParent.identifier) - + } - + func testDeleteStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initStrangeExplicitChild(with: parent) let savedChild = try await createAndWaitForSync(child) - + try await deleteAndWaitForSync(savedChild) try await assertModelDoesNotExist(savedChild) try await deleteAndWaitForSync(savedParent) try await assertModelDoesNotExist(savedParent) } - + func testGetStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initStrangeExplicitChild(with: parent) let savedChild = try await createAndWaitForSync(child) - + // query parent and load the children let queriedParent = try await query(for: savedParent) - - assertList(queriedParent.strangeChildren!, state: .isNotLoaded(associatedIds: [queriedParent.identifier], - associatedFields: ["parent"])) + + assertList(queriedParent.strangeChildren!, state: .isNotLoaded( + associatedIds: [queriedParent.identifier], + associatedFields: ["parent"] + )) try await queriedParent.strangeChildren?.fetch() assertList(queriedParent.strangeChildren!, state: .isLoaded(count: 1)) - + // query children and load the parent - StrangeExplicitChild let queriedStrangeImplicitChild = try await query(for: savedChild) - assertLazyReference(queriedStrangeImplicitChild._parent, - state: .notLoaded(identifiers: [ - .init(name: CompositePKParent.keys.customId.stringValue, value: savedParent.customId), - .init(name: CompositePKParent.keys.content.stringValue, value: savedParent.content) - ])) + assertLazyReference( + queriedStrangeImplicitChild._parent, + state: .notLoaded(identifiers: [ + .init(name: CompositePKParent.keys.customId.stringValue, value: savedParent.customId), + .init(name: CompositePKParent.keys.content.stringValue, value: savedParent.content) + ]) + ) let loadedParent3 = try await queriedStrangeImplicitChild.parent - assertLazyReference(queriedStrangeImplicitChild._parent, - state: .loaded(model: loadedParent3)) + assertLazyReference( + queriedStrangeImplicitChild._parent, + state: .loaded(model: loadedParent3) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKTests.swift index df13ac6f85..8c1513a5fb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKTests.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadCompositePKTests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: CompositePKModels()) try await startAndWaitForReady() } - + func testSaveCompositePKParent() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -27,7 +27,7 @@ class AWSDataStoreLazyLoadCompositePKTests: AWSDataStoreLazyLoadBaseTest { } extension AWSDataStoreLazyLoadCompositePKTests { - + struct CompositePKModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -38,9 +38,11 @@ extension AWSDataStoreLazyLoadCompositePKTests { ModelRegistry.register(modelType: ChildSansBelongsTo.self) } } - + func initParent() -> CompositePKParent { - CompositePKParent(customId: UUID().uuidString, - content: UUID().uuidString) + CompositePKParent( + customId: UUID().uuidString, + content: UUID().uuidString + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo+Schema.swift index 1f4e006ad2..e7abeb3b2a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ChildSansBelongsTo { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ChildSansBelongsTo { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case childId case content case compositePKParentChildrenSansBelongsToCustomId @@ -12,21 +19,21 @@ extension ChildSansBelongsTo { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let childSansBelongsTo = ChildSansBelongsTo.keys - + model.pluralName = "ChildSansBelongsTos" - + model.attributes( .index(fields: ["childId", "content"], name: nil), .index(fields: ["compositePKParentChildrenSansBelongsToCustomId", "compositePKParentChildrenSansBelongsToContent"], name: "byParent"), .primaryKey(fields: [childSansBelongsTo.childId, childSansBelongsTo.content]) ) - + model.fields( .field(childSansBelongsTo.childId, is: .required, ofType: .string), .field(childSansBelongsTo.content, is: .required, ofType: .string), @@ -36,9 +43,9 @@ extension ChildSansBelongsTo { .field(childSansBelongsTo.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ChildSansBelongsTo: ModelIdentifiable { @@ -46,29 +53,31 @@ extension ChildSansBelongsTo: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ChildSansBelongsTo.IdentifierProtocol { - public static func identifier(childId: String, - content: String) -> Self { - .make(fields:[(name: "childId", value: childId), (name: "content", value: content)]) +public extension ChildSansBelongsTo.IdentifierProtocol { + static func identifier( + childId: String, + content: String + ) -> Self { + .make(fields: [(name: "childId", value: childId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == ChildSansBelongsTo { - public var childId: FieldPath { - string("childId") +public extension ModelPath where ModelType == ChildSansBelongsTo { + var childId: FieldPath { + string("childId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var compositePKParentChildrenSansBelongsToCustomId: FieldPath { - string("compositePKParentChildrenSansBelongsToCustomId") + var compositePKParentChildrenSansBelongsToCustomId: FieldPath { + string("compositePKParentChildrenSansBelongsToCustomId") } - public var compositePKParentChildrenSansBelongsToContent: FieldPath { - string("compositePKParentChildrenSansBelongsToContent") + var compositePKParentChildrenSansBelongsToContent: FieldPath { + string("compositePKParentChildrenSansBelongsToContent") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo.swift index 47af9e3213..6ebf5f53be 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct ChildSansBelongsTo: Model { public var compositePKParentChildrenSansBelongsToContent: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(childId: String, + + public init( + childId: String, content: String, compositePKParentChildrenSansBelongsToCustomId: String, - compositePKParentChildrenSansBelongsToContent: String? = nil) { - self.init(childId: childId, - content: content, - compositePKParentChildrenSansBelongsToCustomId: compositePKParentChildrenSansBelongsToCustomId, - compositePKParentChildrenSansBelongsToContent: compositePKParentChildrenSansBelongsToContent, - createdAt: nil, - updatedAt: nil) + compositePKParentChildrenSansBelongsToContent: String? = nil + ) { + self.init( + childId: childId, + content: content, + compositePKParentChildrenSansBelongsToCustomId: compositePKParentChildrenSansBelongsToCustomId, + compositePKParentChildrenSansBelongsToContent: compositePKParentChildrenSansBelongsToContent, + createdAt: nil, + updatedAt: nil + ) } - internal init(childId: String, + init( + childId: String, content: String, compositePKParentChildrenSansBelongsToCustomId: String, compositePKParentChildrenSansBelongsToContent: String? = nil, createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + updatedAt: Temporal.DateTime? = nil + ) { self.childId = childId self.content = content self.compositePKParentChildrenSansBelongsToCustomId = compositePKParentChildrenSansBelongsToCustomId @@ -36,12 +49,12 @@ public struct ChildSansBelongsTo: Model { } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - childId = try values.decode(String.self, forKey: .childId) - content = try values.decode(String.self, forKey: .content) - compositePKParentChildrenSansBelongsToCustomId = try values.decode(String.self, forKey: .compositePKParentChildrenSansBelongsToCustomId) - compositePKParentChildrenSansBelongsToContent = try values.decode(String?.self, forKey: .compositePKParentChildrenSansBelongsToContent) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.childId = try values.decode(String.self, forKey: .childId) + self.content = try values.decode(String.self, forKey: .content) + self.compositePKParentChildrenSansBelongsToCustomId = try values.decode(String.self, forKey: .compositePKParentChildrenSansBelongsToCustomId) + self.compositePKParentChildrenSansBelongsToContent = try values.decode(String?.self, forKey: .compositePKParentChildrenSansBelongsToContent) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -52,4 +65,4 @@ public struct ChildSansBelongsTo: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild+Schema.swift index 6360f82b98..fb7c116016 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CompositePKChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension CompositePKChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case childId case content case parent case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let compositePKChild = CompositePKChild.keys - + model.pluralName = "CompositePKChildren" - + model.attributes( .index(fields: ["childId", "content"], name: nil), .index(fields: ["parentId", "parentTitle"], name: "byParent"), .primaryKey(fields: [compositePKChild.childId, compositePKChild.content]) ) - + model.fields( .field(compositePKChild.childId, is: .required, ofType: .string), .field(compositePKChild.content, is: .required, ofType: .string), @@ -34,9 +41,9 @@ extension CompositePKChild { .field(compositePKChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension CompositePKChild: ModelIdentifiable { @@ -44,26 +51,28 @@ extension CompositePKChild: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CompositePKChild.IdentifierProtocol { - public static func identifier(childId: String, - content: String) -> Self { - .make(fields:[(name: "childId", value: childId), (name: "content", value: content)]) +public extension CompositePKChild.IdentifierProtocol { + static func identifier( + childId: String, + content: String + ) -> Self { + .make(fields: [(name: "childId", value: childId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == CompositePKChild { - public var childId: FieldPath { - string("childId") +public extension ModelPath where ModelType == CompositePKChild { + var childId: FieldPath { + string("childId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var parent: ModelPath { - CompositePKParent.Path(name: "parent", parent: self) + var parent: ModelPath { + CompositePKParent.Path(name: "parent", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild.swift index 3ade723583..773d3e412c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,29 +12,35 @@ import Foundation public struct CompositePKChild: Model { public let childId: String public let content: String - internal var _parent: LazyReference + var _parent: LazyReference public var parent: CompositePKParent? { - get async throws { + get async throws { try await _parent.get() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(childId: String, - content: String, - parent: CompositePKParent? = nil) { - self.init(childId: childId, + + public init( + childId: String, + content: String, + parent: CompositePKParent? = nil + ) { + self.init( + childId: childId, content: content, parent: parent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(childId: String, - content: String, - parent: CompositePKParent? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + childId: String, + content: String, + parent: CompositePKParent? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.childId = childId self.content = content self._parent = LazyReference(parent) @@ -35,15 +48,15 @@ public struct CompositePKChild: Model { self.updatedAt = updatedAt } public mutating func setParent(_ parent: CompositePKParent? = nil) { - self._parent = LazyReference(parent) + _parent = LazyReference(parent) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - childId = try values.decode(String.self, forKey: .childId) - content = try values.decode(String.self, forKey: .content) - _parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.childId = try values.decode(String.self, forKey: .childId) + self.content = try values.decode(String.self, forKey: .content) + self._parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent+Schema.swift index e047f0dc3e..0b8341d9c1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CompositePKParent { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension CompositePKParent { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case customId case content case children @@ -14,20 +21,20 @@ extension CompositePKParent { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let compositePKParent = CompositePKParent.keys - + model.pluralName = "CompositePKParents" - + model.attributes( .index(fields: ["customId", "content"], name: nil), .primaryKey(fields: [compositePKParent.customId, compositePKParent.content]) ) - + model.fields( .field(compositePKParent.customId, is: .required, ofType: .string), .field(compositePKParent.content, is: .required, ofType: .string), @@ -39,9 +46,9 @@ extension CompositePKParent { .field(compositePKParent.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension CompositePKParent: ModelIdentifiable { @@ -49,35 +56,37 @@ extension CompositePKParent: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CompositePKParent.IdentifierProtocol { - public static func identifier(customId: String, - content: String) -> Self { - .make(fields:[(name: "customId", value: customId), (name: "content", value: content)]) +public extension CompositePKParent.IdentifierProtocol { + static func identifier( + customId: String, + content: String + ) -> Self { + .make(fields: [(name: "customId", value: customId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == CompositePKParent { - public var customId: FieldPath { - string("customId") +public extension ModelPath where ModelType == CompositePKParent { + var customId: FieldPath { + string("customId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var children: ModelPath { - CompositePKChild.Path(name: "children", isCollection: true, parent: self) + var children: ModelPath { + CompositePKChild.Path(name: "children", isCollection: true, parent: self) } - public var implicitChildren: ModelPath { - ImplicitChild.Path(name: "implicitChildren", isCollection: true, parent: self) + var implicitChildren: ModelPath { + ImplicitChild.Path(name: "implicitChildren", isCollection: true, parent: self) } - public var strangeChildren: ModelPath { - StrangeExplicitChild.Path(name: "strangeChildren", isCollection: true, parent: self) + var strangeChildren: ModelPath { + StrangeExplicitChild.Path(name: "strangeChildren", isCollection: true, parent: self) } - public var childrenSansBelongsTo: ModelPath { - ChildSansBelongsTo.Path(name: "childrenSansBelongsTo", isCollection: true, parent: self) + var childrenSansBelongsTo: ModelPath { + ChildSansBelongsTo.Path(name: "childrenSansBelongsTo", isCollection: true, parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent.swift index d2bef97b61..12a4f511fc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -11,30 +18,36 @@ public struct CompositePKParent: Model { public var childrenSansBelongsTo: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(customId: String, - content: String, - children: List? = [], - implicitChildren: List? = [], - strangeChildren: List? = [], - childrenSansBelongsTo: List? = []) { - self.init(customId: customId, + + public init( + customId: String, + content: String, + children: List? = [], + implicitChildren: List? = [], + strangeChildren: List? = [], + childrenSansBelongsTo: List? = [] + ) { + self.init( + customId: customId, content: content, children: children, implicitChildren: implicitChildren, strangeChildren: strangeChildren, childrenSansBelongsTo: childrenSansBelongsTo, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(customId: String, - content: String, - children: List? = [], - implicitChildren: List? = [], - strangeChildren: List? = [], - childrenSansBelongsTo: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + customId: String, + content: String, + children: List? = [], + implicitChildren: List? = [], + strangeChildren: List? = [], + childrenSansBelongsTo: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.customId = customId self.content = content self.children = children diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild+Schema.swift index 83d53e59e2..cbbbd263a8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ImplicitChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ImplicitChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case childId case content case parent case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let implicitChild = ImplicitChild.keys - + model.pluralName = "ImplicitChildren" - + model.attributes( .index(fields: ["childId", "content"], name: nil), .primaryKey(fields: [implicitChild.childId, implicitChild.content]) ) - + model.fields( .field(implicitChild.childId, is: .required, ofType: .string), .field(implicitChild.content, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension ImplicitChild { .field(implicitChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ImplicitChild: ModelIdentifiable { @@ -43,26 +50,28 @@ extension ImplicitChild: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ImplicitChild.IdentifierProtocol { - public static func identifier(childId: String, - content: String) -> Self { - .make(fields:[(name: "childId", value: childId), (name: "content", value: content)]) +public extension ImplicitChild.IdentifierProtocol { + static func identifier( + childId: String, + content: String + ) -> Self { + .make(fields: [(name: "childId", value: childId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == ImplicitChild { - public var childId: FieldPath { - string("childId") +public extension ModelPath where ModelType == ImplicitChild { + var childId: FieldPath { + string("childId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var parent: ModelPath { - CompositePKParent.Path(name: "parent", parent: self) + var parent: ModelPath { + CompositePKParent.Path(name: "parent", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild.swift index 78ec7c0f2d..b8f2e21ccb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct ImplicitChild: Model { public let childId: String public let content: String - internal var _parent: LazyReference + var _parent: LazyReference public var parent: CompositePKParent { get async throws { try await _parent.require() @@ -13,21 +20,27 @@ public struct ImplicitChild: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(childId: String, - content: String, - parent: CompositePKParent) { - self.init(childId: childId, + + public init( + childId: String, + content: String, + parent: CompositePKParent + ) { + self.init( + childId: childId, content: content, parent: parent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(childId: String, - content: String, - parent: CompositePKParent, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + childId: String, + content: String, + parent: CompositePKParent, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.childId = childId self.content = content self._parent = LazyReference(parent) @@ -35,15 +48,15 @@ public struct ImplicitChild: Model { self.updatedAt = updatedAt } public mutating func setParent(_ parent: CompositePKParent) { - self._parent = LazyReference(parent) + _parent = LazyReference(parent) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - childId = try values.decode(String.self, forKey: .childId) - content = try values.decode(String.self, forKey: .content) - _parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.childId = try values.decode(String.self, forKey: .childId) + self.content = try values.decode(String.self, forKey: .content) + self._parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild+Schema.swift index 33af033c9b..172e7a9b4c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension StrangeExplicitChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension StrangeExplicitChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case strangeId case content case parent case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let strangeExplicitChild = StrangeExplicitChild.keys - + model.pluralName = "StrangeExplicitChildren" - + model.attributes( .index(fields: ["strangeId", "content"], name: nil), .index(fields: ["strangeParentId", "strangeParentTitle"], name: "byCompositePKParentX"), .primaryKey(fields: [strangeExplicitChild.strangeId, strangeExplicitChild.content]) ) - + model.fields( .field(strangeExplicitChild.strangeId, is: .required, ofType: .string), .field(strangeExplicitChild.content, is: .required, ofType: .string), @@ -34,9 +41,9 @@ extension StrangeExplicitChild { .field(strangeExplicitChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension StrangeExplicitChild: ModelIdentifiable { @@ -44,26 +51,28 @@ extension StrangeExplicitChild: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension StrangeExplicitChild.IdentifierProtocol { - public static func identifier(strangeId: String, - content: String) -> Self { - .make(fields:[(name: "strangeId", value: strangeId), (name: "content", value: content)]) +public extension StrangeExplicitChild.IdentifierProtocol { + static func identifier( + strangeId: String, + content: String + ) -> Self { + .make(fields: [(name: "strangeId", value: strangeId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == StrangeExplicitChild { - public var strangeId: FieldPath { - string("strangeId") +public extension ModelPath where ModelType == StrangeExplicitChild { + var strangeId: FieldPath { + string("strangeId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var parent: ModelPath { - CompositePKParent.Path(name: "parent", parent: self) + var parent: ModelPath { + CompositePKParent.Path(name: "parent", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild.swift index c0fd404bb9..0e004fc8f3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,29 +12,35 @@ import Foundation public struct StrangeExplicitChild: Model { public let strangeId: String public let content: String - internal var _parent: LazyReference + var _parent: LazyReference public var parent: CompositePKParent { - get async throws { + get async throws { try await _parent.require() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(strangeId: String, - content: String, - parent: CompositePKParent) { - self.init(strangeId: strangeId, + + public init( + strangeId: String, + content: String, + parent: CompositePKParent + ) { + self.init( + strangeId: strangeId, content: content, parent: parent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(strangeId: String, - content: String, - parent: CompositePKParent, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + strangeId: String, + content: String, + parent: CompositePKParent, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.strangeId = strangeId self.content = content self._parent = LazyReference(parent) @@ -35,15 +48,15 @@ public struct StrangeExplicitChild: Model { self.updatedAt = updatedAt } public mutating func setParent(_ parent: CompositePKParent) { - self._parent = LazyReference(parent) + _parent = LazyReference(parent) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - strangeId = try values.decode(String.self, forKey: .strangeId) - content = try values.decode(String.self, forKey: .content) - _parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.strangeId = try values.decode(String.self, forKey: .strangeId) + self.content = try values.decode(String.self, forKey: .content) + self._parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKSnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKSnapshotTests.swift index 71bbfd2c58..b7fdf44476 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKSnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKSnapshotTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadDefaultPKTests { - + func testParentSelectionSets() { setUpModelRegistrationOnly(withModels: DefaultPKModels()) continueAfterFailure = true @@ -35,7 +35,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: parent, modelSchema: Parent.schema) let updateDocument = """ @@ -53,7 +53,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: parent, modelSchema: Parent.schema) let deleteDocument = """ @@ -71,7 +71,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Parent.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -89,7 +89,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Parent.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -107,7 +107,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Parent.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -125,7 +125,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Parent.self) let syncDocument = """ @@ -148,13 +148,13 @@ extension AWSDataStoreLazyLoadDefaultPKTests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testChildSelectionSets() { setUpModelRegistrationOnly(withModels: DefaultPKModels()) continueAfterFailure = true let parent = Parent() let child = Child(parent: parent) - + // Create let createRequest = GraphQLRequest.createMutation(of: child, modelSchema: Child.schema) let createDocument = """ @@ -182,7 +182,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: child, modelSchema: Child.schema) let updateDocument = """ @@ -210,7 +210,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: child, modelSchema: Child.schema) let deleteDocument = """ @@ -238,7 +238,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Child.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -261,7 +261,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Child.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -284,7 +284,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Child.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -307,7 +307,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Child.self) let syncDocument = """ @@ -335,6 +335,6 @@ extension AWSDataStoreLazyLoadDefaultPKTests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKTests.swift index c769340da9..3b98a5bf73 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKTests.swift @@ -5,26 +5,26 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: DefaultPKModels()) try await startAndWaitForReady() } - + func testSaveParent() async throws { await setup(withModels: DefaultPKModels()) let parent = Parent() try await createAndWaitForSync(parent) } - + func testSaveChild() async throws { await setup(withModels: DefaultPKModels()) let parent = Parent() @@ -32,10 +32,10 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { try await createAndWaitForSync(parent) try await createAndWaitForSync(child) } - + func testLazyLoad() async throws { await setup(withModels: DefaultPKModels()) - + let parent = Parent() let child = Child(parent: parent) let savedParent = try await createAndWaitForSync(parent) @@ -47,113 +47,135 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { let queriedPost = try await query(for: savedParent) try await assertParent(queriedPost, canLazyLoad: savedChild) } - + func testLazyLoadOnSaveAfterEncodeDecode() async throws { await setup(withModels: DefaultPKModels()) - + let parent = Parent() let child = Child(parent: parent) let savedParent = try await createAndWaitForSync(parent) let savedChild = try await createAndWaitForSync(child) - + guard let encodedChild = try? savedChild.toJSON() else { XCTFail("Could not encode child") return } try await assertChild(savedChild, canLazyLoad: savedParent) - - guard let decodedChild = try? ModelRegistry.decode(modelName: Child.modelName, - from: encodedChild) as? Child else { - + + guard let decodedChild = try? ModelRegistry.decode( + modelName: Child.modelName, + from: encodedChild + ) as? Child else { + XCTFail("Could not decode comment") return } - + try await assertChild(decodedChild, canLazyLoad: savedParent) } - + func testLazyLoadOnQueryAfterEncodeDecoder() async throws { await setup(withModels: DefaultPKModels()) - + let parent = Parent() let child = Child(parent: parent) let savedParent = try await createAndWaitForSync(parent) let savedChild = try await createAndWaitForSync(child) let queriedChild = try await query(for: savedChild) - + guard let encodedChild = try? queriedChild.toJSON() else { XCTFail("Could not encode child") return } - + try await assertChild(queriedChild, canLazyLoad: savedParent) - - guard let decodedChild = try? ModelRegistry.decode(modelName: Child.modelName, - from: encodedChild) as? Child else { - + + guard let decodedChild = try? ModelRegistry.decode( + modelName: Child.modelName, + from: encodedChild + ) as? Child else { + XCTFail("Could not decode comment") return } - + try await assertChild(decodedChild, canLazyLoad: savedParent) } - - func assertChild(_ child: Child, - hasEagerLoaded parent: Parent) async throws { - assertLazyReference(child._parent, - state: .loaded(model: parent)) - + + func assertChild( + _ child: Child, + hasEagerLoaded parent: Parent + ) async throws { + assertLazyReference( + child._parent, + state: .loaded(model: parent) + ) + guard let loadedParent = try await child.parent else { XCTFail("Failed to retrieve the parent from the child") return } XCTAssertEqual(loadedParent.id, parent.id) - + try await assertParent(loadedParent, canLazyLoad: child) } - - func assertChild(_ child: Child, - canLazyLoad parent: Parent) async throws { - assertLazyReference(child._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)])) + + func assertChild( + _ child: Child, + canLazyLoad parent: Parent + ) async throws { + assertLazyReference( + child._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)]) + ) guard let loadedParent = try await child.parent else { XCTFail("Failed to load the parent from the child") return } XCTAssertEqual(loadedParent.id, parent.id) - assertLazyReference(child._parent, - state: .loaded(model: parent)) + assertLazyReference( + child._parent, + state: .loaded(model: parent) + ) try await assertParent(loadedParent, canLazyLoad: child) } - - func assertParent(_ parent: Parent, - canLazyLoad child: Child) async throws { + + func assertParent( + _ parent: Parent, + canLazyLoad child: Child + ) async throws { guard let children = parent.children else { XCTFail("Missing children on parent") return } - assertList(children, state: .isNotLoaded(associatedIds: [parent.identifier], - associatedFields: ["parent"])) - + assertList(children, state: .isNotLoaded( + associatedIds: [parent.identifier], + associatedFields: ["parent"] + )) + try await children.fetch() assertList(children, state: .isLoaded(count: 1)) guard let child = children.first else { XCTFail("Missing lazy loaded child from parent") return } - + // further nested models should not be loaded - assertLazyReference(child._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)])) + assertLazyReference( + child._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)]) + ) } - + func testSaveWithoutPost() async throws { await setup(withModels: DefaultPKModels()) let child = Child(content: "content") let savedChild = try await createAndWaitForSync(child) var queriedChild = try await query(for: savedChild) - assertLazyReference(queriedChild._parent, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedChild._parent, + state: .notLoaded(identifiers: nil) + ) let parent = Parent() let savedParent = try await createAndWaitForSync(parent) queriedChild.setParent(savedParent) @@ -161,7 +183,7 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { let queriedChild2 = try await query(for: saveCommentWithPost) try await assertChild(queriedChild2, canLazyLoad: parent) } - + func testUpdateFromqueriedChild() async throws { await setup(withModels: DefaultPKModels()) let parent = Parent() @@ -169,24 +191,28 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { let savedParent = try await createAndWaitForSync(parent) let savedChild = try await createAndWaitForSync(child) let queriedChild = try await query(for: savedChild) - assertLazyReference(queriedChild._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)])) + assertLazyReference( + queriedChild._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)]) + ) let savedqueriedChild = try await updateAndWaitForSync(queriedChild) let queriedChild2 = try await query(for: savedqueriedChild) try await assertChild(queriedChild2, canLazyLoad: savedParent) } - + func testUpdateToNewPost() async throws { await setup(withModels: DefaultPKModels()) - + let parent = Parent() let child = Child(parent: parent) _ = try await createAndWaitForSync(parent) let savedChild = try await createAndWaitForSync(child) var queriedChild = try await query(for: savedChild) - assertLazyReference(queriedChild._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)])) - + assertLazyReference( + queriedChild._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)]) + ) + let newParent = DefaultPKParent() _ = try await createAndWaitForSync(newParent) queriedChild.setParent(newParent) @@ -194,28 +220,32 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { let queriedChild2 = try await query(for: saveCommentWithNewPost) try await assertChild(queriedChild2, canLazyLoad: newParent) } - + func testUpdateRemovePost() async throws { await setup(withModels: DefaultPKModels()) - + let parent = Parent() let child = Child(parent: parent) _ = try await createAndWaitForSync(parent) let savedChild = try await createAndWaitForSync(child) var queriedChild = try await query(for: savedChild) - assertLazyReference(queriedChild._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)])) - + assertLazyReference( + queriedChild._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)]) + ) + queriedChild.setParent(nil) let saveCommentRemovePost = try await updateAndWaitForSync(queriedChild) let queriedChildNoParent = try await query(for: saveCommentRemovePost) - assertLazyReference(queriedChildNoParent._parent, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedChildNoParent._parent, + state: .notLoaded(identifiers: nil) + ) } - + func testDelete() async throws { await setup(withModels: DefaultPKModels()) - + let parent = Parent() let child = Child(parent: parent) let savedParent = try await createAndWaitForSync(parent) @@ -224,7 +254,7 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { try await assertModelDoesNotExist(savedChild) try await assertModelDoesNotExist(savedParent) } - + func testObserveParent() async throws { await setup(withModels: DefaultPKModels()) try await startAndWaitForReady() @@ -238,9 +268,9 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { version == 1, let receivedParent = try? mutationEvent.decodeModel(as: Parent.self), receivedParent.id == parent.id { - + try await createAndWaitForSync(child) - + guard let children = receivedParent.children else { XCTFail("Lazy List does not exist") return @@ -251,23 +281,23 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load children \(error)") } XCTAssertEqual(children.count, 1) - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: parent, modelSchema: Parent.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveChild() async throws { await setup(withModels: DefaultPKModels()) try await startAndWaitForReady() @@ -287,18 +317,18 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: child, modelSchema: Child.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryParent() async throws { await setup(withModels: DefaultPKModels()) try await startAndWaitForReady() @@ -320,27 +350,27 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load children \(error)") } XCTAssertEqual(children.count, 1) - + snapshotReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: parent, modelSchema: Parent.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryChild() async throws { await setup(withModels: DefaultPKModels()) try await startAndWaitForReady() - + let parent = Parent() let savedParent = try await createAndWaitForSync(parent) let child = Child(parent: parent) @@ -354,24 +384,24 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: child, modelSchema: Child.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } } extension AWSDataStoreLazyLoadDefaultPKTests { - + typealias Parent = DefaultPKParent typealias Child = DefaultPKChild - + struct DefaultPKModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild+Schema.swift index b2bef9f056..44da59840b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension DefaultPKChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension DefaultPKChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case parent case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let defaultPKChild = DefaultPKChild.keys - + model.pluralName = "DefaultPKChildren" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [defaultPKChild.id]) ) - + model.fields( .field(defaultPKChild.id, is: .required, ofType: .string), .field(defaultPKChild.content, is: .optional, ofType: .string), @@ -33,29 +40,29 @@ extension DefaultPKChild { .field(defaultPKChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension DefaultPKChild: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == DefaultPKChild { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == DefaultPKChild { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var parent: ModelPath { - DefaultPKParent.Path(name: "parent", parent: self) + var parent: ModelPath { + DefaultPKParent.Path(name: "parent", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild.swift index dabbd4888e..e1ef75fd6d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct DefaultPKChild: Model { public let id: String public var content: String? - internal var _parent: LazyReference + var _parent: LazyReference public var parent: DefaultPKParent? { get async throws { try await _parent.get() @@ -13,21 +20,27 @@ public struct DefaultPKChild: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - parent: DefaultPKParent? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + parent: DefaultPKParent? = nil + ) { + self.init( + id: id, content: content, parent: parent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - parent: DefaultPKParent? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + parent: DefaultPKParent? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._parent = LazyReference(parent) @@ -35,15 +48,15 @@ public struct DefaultPKChild: Model { self.updatedAt = updatedAt } public mutating func setParent(_ parent: DefaultPKParent? = nil) { - self._parent = LazyReference(parent) + _parent = LazyReference(parent) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try? values.decode(String?.self, forKey: .content) - _parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try? values.decode(String?.self, forKey: .content) + self._parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent+Schema.swift index d493d3a95f..39c2889c26 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension DefaultPKParent { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension DefaultPKParent { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case children case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let defaultPKParent = DefaultPKParent.keys - + model.pluralName = "DefaultPKParents" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [defaultPKParent.id]) ) - + model.fields( .field(defaultPKParent.id, is: .required, ofType: .string), .field(defaultPKParent.content, is: .optional, ofType: .string), @@ -33,29 +40,29 @@ extension DefaultPKParent { .field(defaultPKParent.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension DefaultPKParent: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == DefaultPKParent { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == DefaultPKParent { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var children: ModelPath { - DefaultPKChild.Path(name: "children", isCollection: true, parent: self) + var children: ModelPath { + DefaultPKChild.Path(name: "children", isCollection: true, parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent.swift index 830d085e35..d2bedd8d1e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,21 +15,27 @@ public struct DefaultPKParent: Model { public var children: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - children: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + children: List? = [] + ) { + self.init( + id: id, content: content, children: children, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - children: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + children: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.children = children diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneSnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneSnapshotTests.swift index 5688cdd524..423ca27fde 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneSnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneSnapshotTests.swift @@ -5,21 +5,21 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadHasOneTests { - + func testHasOneParentSelectionSets() { setUpModelRegistrationOnly(withModels: HasOneModels()) continueAfterFailure = true let child = HasOneChild() let parent = HasOneParent(child: child, hasOneParentChildId: child.id) - + // Create let createRequest = GraphQLRequest.createMutation(of: parent, modelSchema: HasOneParent.schema) let createDocument = """ @@ -47,7 +47,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: parent, modelSchema: HasOneParent.schema) let updateDocument = """ @@ -75,7 +75,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: parent, modelSchema: HasOneParent.schema) let deleteDocument = """ @@ -103,7 +103,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: HasOneParent.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -126,7 +126,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: HasOneParent.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -149,7 +149,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: HasOneParent.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -172,7 +172,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: HasOneParent.self) let syncDocument = """ @@ -200,12 +200,12 @@ extension AWSDataStoreLazyLoadHasOneTests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testHasOneChildSelectionSets() { setUpModelRegistrationOnly(withModels: HasOneModels()) continueAfterFailure = true let child = HasOneChild() - + // Create let createRequest = GraphQLRequest.createMutation(of: child, modelSchema: HasOneChild.schema) let createDocument = """ @@ -223,7 +223,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: child, modelSchema: HasOneChild.schema) let updateDocument = """ @@ -241,7 +241,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: child, modelSchema: HasOneChild.schema) let deleteDocument = """ @@ -259,7 +259,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: HasOneChild.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -277,7 +277,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: HasOneChild.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -295,7 +295,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: HasOneChild.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -313,7 +313,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: HasOneChild.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneTests.swift index 72b44fb797..7645269868 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadHasOneTests: AWSDataStoreLazyLoadBaseTest { @@ -64,12 +64,12 @@ class AWSDataStoreLazyLoadHasOneTests: AWSDataStoreLazyLoadBaseTest { // populating `hasOneParentChildId` is required to sync successfully let parent = HasOneParent(child: child, hasOneParentChildId: child.id) try await createAndWaitForSync(parent) - + // Query from API let response = try await Amplify.API.query(request: .get(HasOneParent.self, byId: parent.id)) switch response { case .success(let queriedParent): - guard let queriedParent = queriedParent else { + guard let queriedParent else { XCTFail("Unexpected, query should return model") return } @@ -81,19 +81,19 @@ class AWSDataStoreLazyLoadHasOneTests: AWSDataStoreLazyLoadBaseTest { case .failure(let error): XCTFail("Error querying for parent directly from AppSync \(error)") } - + // Query from DataStore let queriedParent = try await query(for: parent) - + // The child can be lazy loaded. assertLazyReference(queriedParent._child, state: .notLoaded(identifiers: [.init(name: "id", value: child.id)])) let queriedParentChild = try await queriedParent.child! XCTAssertEqual(queriedParentChild.id, child.id) - + // The child model id can be found on the explicit field. let childId = queriedParent.hasOneParentChildId XCTAssertEqual(childId, child.id) - + // Delete try await deleteAndWaitForSync(parent) try await assertModelDoesNotExist(parent) @@ -121,10 +121,12 @@ class AWSDataStoreLazyLoadHasOneTests: AWSDataStoreLazyLoadBaseTest { XCTAssertEqual(queriedParent.hasOneParentChildId, savedChild.id) // The child can be lazy loaded. - assertLazyReference(queriedParent._child, - state: .notLoaded(identifiers: [ - .init(name: HasOneChild.keys.id.stringValue, value: child.id) - ])) + assertLazyReference( + queriedParent._child, + state: .notLoaded(identifiers: [ + .init(name: HasOneChild.keys.id.stringValue, value: child.id) + ]) + ) let newChild = HasOneChild() let savedNewChild = try await createAndWaitForSync(newChild) @@ -162,8 +164,7 @@ class AWSDataStoreLazyLoadHasOneTests: AWSDataStoreLazyLoadBaseTest { if let version = mutationEvent.version, version == 1, let receivedChild = try? mutationEvent.decodeModel(as: HasOneChild.self), - receivedChild.identifier == child.identifier - { + receivedChild.identifier == child.identifier { mutationEventReceived.fulfill() } } @@ -268,7 +269,7 @@ class AWSDataStoreLazyLoadHasOneTests: AWSDataStoreLazyLoadBaseTest { } extension AWSDataStoreLazyLoadHasOneTests { - + struct HasOneModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild+Schema.swift index 5256e3b18a..9a67ca4452 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension HasOneChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension HasOneChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let hasOneChild = HasOneChild.keys - + model.pluralName = "HasOneChildren" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [hasOneChild.id]) ) - + model.fields( .field(hasOneChild.id, is: .required, ofType: .string), .field(hasOneChild.content, is: .optional, ofType: .string), @@ -31,26 +38,26 @@ extension HasOneChild { .field(hasOneChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension HasOneChild: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == HasOneChild { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == HasOneChild { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild.swift index 20714ad8e0..1e37821e08 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,18 +14,24 @@ public struct HasOneChild: Model { public var content: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent+Schema.swift index 6a922e8bd4..f4b24e8e1e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension HasOneParent { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension HasOneParent { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case child case createdAt case updatedAt case hasOneParentChildId } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let hasOneParent = HasOneParent.keys - + model.pluralName = "HasOneParents" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [hasOneParent.id]) ) - + model.fields( .field(hasOneParent.id, is: .required, ofType: .string), .hasOne(hasOneParent.child, is: .optional, ofType: HasOneChild.self, associatedWith: HasOneChild.keys.id, targetNames: ["hasOneParentChildId"]), @@ -33,29 +40,29 @@ extension HasOneParent { .field(hasOneParent.hasOneParentChildId, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension HasOneParent: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == HasOneParent { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == HasOneParent { + var id: FieldPath { + string("id") } - public var child: ModelPath { - HasOneChild.Path(name: "child", parent: self) + var child: ModelPath { + HasOneChild.Path(name: "child", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } - public var hasOneParentChildId: FieldPath { - string("hasOneParentChildId") + var hasOneParentChildId: FieldPath { + string("hasOneParentChildId") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent.swift index 887aedc67d..81931f3e97 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation public struct HasOneParent: Model { public let id: String - internal var _child: LazyReference + var _child: LazyReference public var child: HasOneChild? { get async throws { try await _child.get() @@ -13,21 +20,27 @@ public struct HasOneParent: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? public var hasOneParentChildId: String? - - public init(id: String = UUID().uuidString, - child: HasOneChild? = nil, - hasOneParentChildId: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + child: HasOneChild? = nil, + hasOneParentChildId: String? = nil + ) { + self.init( + id: id, child: child, createdAt: nil, updatedAt: nil, - hasOneParentChildId: hasOneParentChildId) + hasOneParentChildId: hasOneParentChildId + ) } - internal init(id: String = UUID().uuidString, - child: HasOneChild? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - hasOneParentChildId: String? = nil) { + init( + id: String = UUID().uuidString, + child: HasOneChild? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + hasOneParentChildId: String? = nil + ) { self.id = id self._child = LazyReference(child) self.createdAt = createdAt @@ -35,15 +48,15 @@ public struct HasOneParent: Model { self.hasOneParentChildId = hasOneParentChildId } public mutating func setChild(_ child: HasOneChild? = nil) { - self._child = LazyReference(child) + _child = LazyReference(child) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - _child = try values.decodeIfPresent(LazyReference.self, forKey: .child) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - hasOneParentChildId = try? values.decode(String?.self, forKey: .hasOneParentChildId) + self.id = try values.decode(String.self, forKey: .id) + self._child = try values.decodeIfPresent(LazyReference.self, forKey: .child) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.hasOneParentChildId = try? values.decode(String?.self, forKey: .hasOneParentChildId) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallSnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallSnapshotTests.swift index 28b30a9446..8b801a137a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallSnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallSnapshotTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPhoneCallTests { - + } - + diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallTests.swift index 276f3c2632..1ae727ce4f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallTests.swift @@ -5,21 +5,21 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: PhoneCallModels()) try await startAndWaitForReady() printDBPath() } - + /// Saving a person should be successfully /// /// - Given: A model instance of a Person @@ -32,7 +32,7 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { let person = Person(name: "name") try await createAndWaitForSync(person) } - + /// Saving a PhoneCall, requires a caller and a callee, should be successful. /// /// - Given: Two saved persons @@ -52,24 +52,28 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { let phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let savedPhoneCall = try await createAndWaitForSync(phoneCall) let queriedPhoneCall = try await query(for: savedPhoneCall) - assertLazyReference(queriedPhoneCall._caller, - state: .notLoaded(identifiers: [.init(name: "id", value: caller.id)])) - assertLazyReference(queriedPhoneCall._callee, - state: .notLoaded(identifiers: [.init(name: "id", value: callee.id)])) + assertLazyReference( + queriedPhoneCall._caller, + state: .notLoaded(identifiers: [.init(name: "id", value: caller.id)]) + ) + assertLazyReference( + queriedPhoneCall._callee, + state: .notLoaded(identifiers: [.init(name: "id", value: callee.id)]) + ) let loadedCaller = try await queriedPhoneCall.caller let loadedCallee = try await queriedPhoneCall.callee assertLazyReference(queriedPhoneCall._caller, state: .loaded(model: savedCaller)) assertLazyReference(queriedPhoneCall._callee, state: .loaded(model: savedCallee)) - + let queriedCaller = try await query(for: caller) try await queriedCaller.callerOf?.fetch() XCTAssertEqual(queriedCaller.callerOf!.count, 1) - + let queriedCallee = try await query(for: callee) try await queriedCallee.calleeOf?.fetch() XCTAssertEqual(queriedCallee.calleeOf!.count, 1) } - + /// Saving a Transcript with a PhoneCall and a PhoneCall with a Transcript, should be successful /// /// - Given: A Transcript with a PhoneCall. A PhoneCall with a Transcript @@ -89,44 +93,50 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { let savedCallee = try await createAndWaitForSync(callee) var phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let transcript = Transcript(text: "text", phoneCall: phoneCall) - + // When the explicit FK and the connected model exists on the model, setting the connected model // has no effect, we have to set the explicit field `phoneCallTranscriptId`. // phoneCall.setTranscript(transcript) phoneCall.phoneCallTranscriptId = transcript.id - + let savedPhoneCall = try await createAndWaitForSync(phoneCall) XCTAssertEqual(savedPhoneCall.phoneCallTranscriptId, transcript.id) let savedTranscript = try await createAndWaitForSync(transcript) - assertLazyReference(savedTranscript._phoneCall, - state: .notLoaded(identifiers: [ - .init(name: PhoneCall.keys.id.stringValue, value: savedPhoneCall.id) - ])) - + assertLazyReference( + savedTranscript._phoneCall, + state: .notLoaded(identifiers: [ + .init(name: PhoneCall.keys.id.stringValue, value: savedPhoneCall.id) + ]) + ) + let queriedTranscript = try await query(for: savedTranscript) - assertLazyReference(queriedTranscript._phoneCall, - state: .notLoaded(identifiers: [ - .init(name: PhoneCall.keys.id.stringValue, value: savedPhoneCall.id) - ])) + assertLazyReference( + queriedTranscript._phoneCall, + state: .notLoaded(identifiers: [ + .init(name: PhoneCall.keys.id.stringValue, value: savedPhoneCall.id) + ]) + ) let loadedPhoneCall = try await queriedTranscript.phoneCall! - assertLazyReference(queriedTranscript._phoneCall, - state: .loaded(model: savedPhoneCall)) + assertLazyReference( + queriedTranscript._phoneCall, + state: .loaded(model: savedPhoneCall) + ) let loadedCaller = try await loadedPhoneCall.caller let loadedCallee = try await loadedPhoneCall.callee - + try await loadedCaller.callerOf?.fetch() XCTAssertEqual(loadedCaller.callerOf!.count, 1) - + try await loadedCaller.calleeOf?.fetch() XCTAssertEqual(loadedCaller.calleeOf!.count, 0) - + try await loadedCallee.callerOf?.fetch() XCTAssertEqual(loadedCallee.callerOf!.count, 0) - + try await loadedCallee.calleeOf?.fetch() XCTAssertEqual(loadedCallee.calleeOf!.count, 1) } - + func testUpdatePhoneCallToTranscript() async throws { await setup(withModels: PhoneCallModels()) let caller = Person(name: "caller") @@ -138,23 +148,23 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { XCTAssertNil(savedPhoneCall.phoneCallTranscriptId) let transcript = Transcript(text: "text", phoneCall: phoneCall) let savedTranscript = try await createAndWaitForSync(transcript) - - + + var queriedPhoneCall = try await query(for: savedPhoneCall) queriedPhoneCall.phoneCallTranscriptId = transcript.id let updatedPhoneCall = try await updateAndWaitForSync(queriedPhoneCall) XCTAssertEqual(updatedPhoneCall.phoneCallTranscriptId, transcript.id) } - + func testDeletePerson() async throws { await setup(withModels: PhoneCallModels()) let person = Person(name: "name") let savedPerson = try await createAndWaitForSync(person) - + try await deleteAndWaitForSync(savedPerson) try await assertModelDoesNotExist(savedPerson) } - + /// Deleting a PhoneCall is successful /// /// - Given: PhoneCall, belongs to two Persons @@ -171,12 +181,12 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { let savedCallee = try await createAndWaitForSync(callee) let phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let savedPhoneCall = try await createAndWaitForSync(phoneCall) - + try await deleteAndWaitForSync(savedPhoneCall) try await assertModelExists(caller) try await assertModelExists(callee) } - + /// Delete a Person with PhoneCall will delete the PhoneCall as well, cascade delete the Person's hasMany /// /// - Given: PhoneCall which belongs to two different Persons (caller and callee) @@ -194,13 +204,13 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { let savedCallee = try await createAndWaitForSync(callee) let phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let savedPhoneCall = try await createAndWaitForSync(phoneCall) - + try await deleteAndWaitForSync(savedCaller) try await assertModelDoesNotExist(savedCaller) try await assertModelDoesNotExist(savedPhoneCall) try await assertModelExists(savedCallee) } - + /// Delete Transcript does not delete its belongs-to PhoneCall /// /// - Given: Transcript belongs to a PhoneCall @@ -219,15 +229,15 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { var phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let transcript = Transcript(text: "text", phoneCall: phoneCall) phoneCall.phoneCallTranscriptId = transcript.id - + let savedPhoneCall = try await createAndWaitForSync(phoneCall) let savedTranscript = try await createAndWaitForSync(transcript) - + try await deleteAndWaitForSync(transcript) try await assertModelDoesNotExist(transcript) try await assertModelExists(phoneCall) } - + /// Deleting a PhoneCall cascades to the hasOne Transcript /// /// - Given: PhoneCall with Transcript @@ -245,10 +255,10 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { var phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let transcript = Transcript(text: "text", phoneCall: phoneCall) phoneCall.phoneCallTranscriptId = transcript.id - + let savedPhoneCall = try await createAndWaitForSync(phoneCall) let savedTranscript = try await createAndWaitForSync(transcript) - + try await deleteAndWaitForSync(savedPhoneCall) try await assertModelDoesNotExist(savedPhoneCall) try await assertModelDoesNotExist(savedTranscript) @@ -256,7 +266,7 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { } extension AWSDataStoreLazyLoadPhoneCallTests { - + struct PhoneCallModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person+Schema.swift index 28bef917e2..52d8a37214 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Person { +public extension Person { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case callerOf @@ -12,19 +19,19 @@ extension Person { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let person = Person.keys - + model.pluralName = "People" - + model.attributes( .primaryKey(fields: [person.id]) ) - + model.fields( .field(person.id, is: .required, ofType: .string), .field(person.name, is: .required, ofType: .string), @@ -36,32 +43,32 @@ extension Person { .field(person.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Person: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Person { - public var id: FieldPath { +public extension ModelPath where ModelType == Person { + var id: FieldPath { string("id") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var callerOf: ModelPath { + var callerOf: ModelPath { PhoneCall.Path(name: "callerOf", isCollection: true, parent: self) } - public var calleeOf: ModelPath { + var calleeOf: ModelPath { PhoneCall.Path(name: "calleeOf", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person.swift index f3d6c1328a..7b577b70b5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Person: Model { public var calleeOf: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - callerOf: List = [], - calleeOf: List = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + callerOf: List = [], + calleeOf: List = [] + ) { + self.init( + id: id, name: name, callerOf: callerOf, calleeOf: calleeOf, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - callerOf: List = [], - calleeOf: List = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + callerOf: List = [], + calleeOf: List = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.callerOf = callerOf diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall+Schema.swift index 557468c4c4..6f2522afe1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PhoneCall { +public extension PhoneCall { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case caller case callee @@ -13,21 +20,21 @@ extension PhoneCall { case updatedAt case phoneCallTranscriptId } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let phoneCall = PhoneCall.keys - + model.pluralName = "PhoneCalls" - + model.attributes( .index(fields: ["callerId"], name: "byCaller"), .index(fields: ["calleeId"], name: "byCallee"), .primaryKey(fields: [phoneCall.id]) ) - + model.fields( .field(phoneCall.id, is: .required, ofType: .string), .belongsTo(phoneCall.caller, is: .required, ofType: Person.self, targetNames: ["callerId"]), @@ -38,35 +45,35 @@ extension PhoneCall { .field(phoneCall.phoneCallTranscriptId, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PhoneCall: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == PhoneCall { - public var id: FieldPath { +public extension ModelPath where ModelType == PhoneCall { + var id: FieldPath { string("id") } - public var caller: ModelPath { + var caller: ModelPath { Person.Path(name: "caller", parent: self) } - public var callee: ModelPath { + var callee: ModelPath { Person.Path(name: "callee", parent: self) } - public var transcript: ModelPath { + var transcript: ModelPath { Transcript.Path(name: "transcript", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } - public var phoneCallTranscriptId: FieldPath { + var phoneCallTranscriptId: FieldPath { string("phoneCallTranscriptId") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall.swift index 54ebec566c..723b4cb393 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall.swift @@ -1,22 +1,29 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation public struct PhoneCall: Model { public let id: String - internal var _caller: LazyReference + var _caller: LazyReference public var caller: Person { get async throws { try await _caller.require() } } - internal var _callee: LazyReference + var _callee: LazyReference public var callee: Person { get async throws { try await _callee.require() } } - internal var _transcript: LazyReference + var _transcript: LazyReference public var transcript: Transcript? { get async throws { try await _transcript.get() @@ -25,27 +32,33 @@ public struct PhoneCall: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? public var phoneCallTranscriptId: String? - - public init(id: String = UUID().uuidString, - caller: Person, - callee: Person, - transcript: Transcript? = nil, - phoneCallTranscriptId: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + caller: Person, + callee: Person, + transcript: Transcript? = nil, + phoneCallTranscriptId: String? = nil + ) { + self.init( + id: id, caller: caller, callee: callee, transcript: transcript, createdAt: nil, updatedAt: nil, - phoneCallTranscriptId: phoneCallTranscriptId) + phoneCallTranscriptId: phoneCallTranscriptId + ) } - internal init(id: String = UUID().uuidString, - caller: Person, - callee: Person, - transcript: Transcript? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - phoneCallTranscriptId: String? = nil) { + init( + id: String = UUID().uuidString, + caller: Person, + callee: Person, + transcript: Transcript? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + phoneCallTranscriptId: String? = nil + ) { self.id = id self._caller = LazyReference(caller) self._callee = LazyReference(callee) @@ -55,23 +68,23 @@ public struct PhoneCall: Model { self.phoneCallTranscriptId = phoneCallTranscriptId } public mutating func setCaller(_ caller: Person) { - self._caller = LazyReference(caller) + _caller = LazyReference(caller) } public mutating func setCallee(_ callee: Person) { - self._callee = LazyReference(callee) + _callee = LazyReference(callee) } public mutating func setTranscript(_ transcript: Transcript? = nil) { - self._transcript = LazyReference(transcript) + _transcript = LazyReference(transcript) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - _caller = try values.decodeIfPresent(LazyReference.self, forKey: .caller) ?? LazyReference(identifiers: nil) - _callee = try values.decodeIfPresent(LazyReference.self, forKey: .callee) ?? LazyReference(identifiers: nil) - _transcript = try values.decodeIfPresent(LazyReference.self, forKey: .transcript) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - phoneCallTranscriptId = try? values.decode(String?.self, forKey: .phoneCallTranscriptId) + self.id = try values.decode(String.self, forKey: .id) + self._caller = try values.decodeIfPresent(LazyReference.self, forKey: .caller) ?? LazyReference(identifiers: nil) + self._callee = try values.decodeIfPresent(LazyReference.self, forKey: .callee) ?? LazyReference(identifiers: nil) + self._transcript = try values.decodeIfPresent(LazyReference.self, forKey: .transcript) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.phoneCallTranscriptId = try? values.decode(String?.self, forKey: .phoneCallTranscriptId) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript+Schema.swift index 7bffc18bdb..7c600943a4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Transcript { +public extension Transcript { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case text case language @@ -12,19 +19,19 @@ extension Transcript { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let transcript = Transcript.keys - + model.pluralName = "Transcripts" - + model.attributes( .primaryKey(fields: [transcript.id]) ) - + model.fields( .field(transcript.id, is: .required, ofType: .string), .field(transcript.text, is: .required, ofType: .string), @@ -34,32 +41,32 @@ extension Transcript { .field(transcript.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Transcript: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Transcript { - public var id: FieldPath { +public extension ModelPath where ModelType == Transcript { + var id: FieldPath { string("id") } - public var text: FieldPath { + var text: FieldPath { string("text") } - public var language: FieldPath { + var language: FieldPath { string("language") } - public var phoneCall: ModelPath { + var phoneCall: ModelPath { PhoneCall.Path(name: "phoneCall", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript.swift index 039f461e5b..4144fd8b5b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -6,7 +13,7 @@ public struct Transcript: Model { public let id: String public var text: String public var language: String? - internal var _phoneCall: LazyReference + var _phoneCall: LazyReference public var phoneCall: PhoneCall? { get async throws { try await _phoneCall.get() @@ -14,24 +21,30 @@ public struct Transcript: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - text: String, - language: String? = nil, - phoneCall: PhoneCall? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + text: String, + language: String? = nil, + phoneCall: PhoneCall? = nil + ) { + self.init( + id: id, text: text, language: language, phoneCall: phoneCall, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - text: String, - language: String? = nil, - phoneCall: PhoneCall? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + text: String, + language: String? = nil, + phoneCall: PhoneCall? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.text = text self.language = language @@ -40,16 +53,16 @@ public struct Transcript: Model { self.updatedAt = updatedAt } public mutating func setPhoneCall(_ phoneCall: PhoneCall? = nil) { - self._phoneCall = LazyReference(phoneCall) + _phoneCall = LazyReference(phoneCall) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - text = try values.decode(String.self, forKey: .text) - language = try? values.decode(String?.self, forKey: .language) - _phoneCall = try values.decodeIfPresent(LazyReference.self, forKey: .phoneCall) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.text = try values.decode(String.self, forKey: .text) + self.language = try? values.decode(String?.self, forKey: .language) + self._phoneCall = try values.decodeIfPresent(LazyReference.self, forKey: .phoneCall) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentSnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentSnapshotTests.swift index 4ea8a63364..aaac3ce762 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentSnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentSnapshotTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify extension AWSDataStoreLazyLoadUserPostCommentTests { - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentTests.swift index 11bd00c7e3..267aa5f098 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @@ -23,16 +23,16 @@ final class AWSDataStoreLazyLoadUserPostCommentTests: AWSDataStoreLazyLoadBaseTe let user = User(username: "name") try await createAndWaitForSync(user) } - + func testSaveUserSettings() async throws { await setup(withModels: UserPostCommentModels()) let user = User(username: "name") let savedUser = try await createAndWaitForSync(user) - + let userSettings = UserSettings(language: "en-us", user: savedUser) try await createAndWaitForSync(userSettings) } - + func testSavePost() async throws { await setup(withModels: UserPostCommentModels()) let user = User(username: "name") @@ -40,7 +40,7 @@ final class AWSDataStoreLazyLoadUserPostCommentTests: AWSDataStoreLazyLoadBaseTe let post = Post(title: "title", rating: 1, status: .active, author: savedUser) try await createAndWaitForSync(post) } - + func testSaveComment() async throws { await setup(withModels: UserPostCommentModels()) let user = User(username: "name") @@ -50,7 +50,7 @@ final class AWSDataStoreLazyLoadUserPostCommentTests: AWSDataStoreLazyLoadBaseTe let comment = Comment(content: "content", post: savedPost, author: savedUser) try await createAndWaitForSync(comment) } - + /// LazyLoad from queried models /// /// - Given: Saved and synced models @@ -69,7 +69,7 @@ final class AWSDataStoreLazyLoadUserPostCommentTests: AWSDataStoreLazyLoadBaseTe let savedPost = try await createAndWaitForSync(post) let comment = Comment(content: "content", post: savedPost, author: savedUser) try await createAndWaitForSync(comment) - + // Traverse from User let queriedUser = try await query(for: user) try await queriedUser.posts?.fetch() @@ -79,26 +79,26 @@ final class AWSDataStoreLazyLoadUserPostCommentTests: AWSDataStoreLazyLoadBaseTe // Cannot traverse from User to settings //let queriedUserSettings = try await queriedUser.settings //XCTAssertNotNil(queriedUserSettings) - + // Traverse from UserSettings let queriedSettings = try await query(for: userSettings) let queriedSettingsUser = try await queriedSettings.user XCTAssertEqual(queriedSettingsUser.id, user.id) - + // Traverse from Post let queriedPost = try await query(for: post) try await queriedPost.comments?.fetch() XCTAssertEqual(queriedPost.comments?.count, 1) let queriedPostUser = try await queriedPost.author XCTAssertEqual(queriedPostUser.id, user.id) - + // Traverse from Comment let queriedComment = try await query(for: comment) let queriedCommentPost = try await queriedComment.post XCTAssertEqual(queriedCommentPost?.id, post.id) let queriedCommentUser = try await queriedComment.author XCTAssertEqual(queriedCommentUser.id, user.id) - + // Clean up - delete the saved models try await deleteAndWaitForSync(user) try await assertModelDoesNotExist(comment) @@ -114,7 +114,7 @@ extension AWSDataStoreLazyLoadUserPostCommentTests { typealias Post = Post14 typealias Comment = Comment14 typealias UserSettings = UserSettings14 - + struct UserPostCommentModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14+Schema.swift index 1b6f96354c..266463d581 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post @@ -12,23 +19,23 @@ extension Comment14 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment14 = Comment14.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Comment14s" - + model.attributes( .primaryKey(fields: [comment14.id]) ) - + model.fields( .field(comment14.id, is: .required, ofType: .string), .field(comment14.content, is: .optional, ofType: .string), @@ -38,32 +45,32 @@ extension Comment14 { .field(comment14.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Comment14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Comment14 { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var post: ModelPath { - Post14.Path(name: "post", parent: self) + var post: ModelPath { + Post14.Path(name: "post", parent: self) } - public var author: ModelPath { - User14.Path(name: "author", parent: self) + var author: ModelPath { + User14.Path(name: "author", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14.swift index cab42a6f0d..906b61dbe6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,38 +12,44 @@ import Foundation public struct Comment14: Model { public let id: String public var content: String? - internal var _post: LazyReference + var _post: LazyReference public var post: Post14? { - get async throws { + get async throws { try await _post.get() - } + } } - internal var _author: LazyReference + var _author: LazyReference public var author: User14 { - get async throws { + get async throws { try await _author.require() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post14? = nil, - author: User14) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post14? = nil, + author: User14 + ) { + self.init( + id: id, content: content, post: post, author: author, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post14? = nil, - author: User14, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post14? = nil, + author: User14, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -45,19 +58,19 @@ public struct Comment14: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post14? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public mutating func setAuthor(_ author: User14) { - self._author = LazyReference(author) + _author = LazyReference(author) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try? values.decode(String?.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - _author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try? values.decode(String?.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self._author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -68,4 +81,4 @@ public struct Comment14: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14+Schema.swift index bf1baaa6c2..a9f698c3ef 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case rating @@ -14,23 +21,23 @@ extension Post14 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post14 = Post14.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Post14s" - + model.attributes( .primaryKey(fields: [post14.id]) ) - + model.fields( .field(post14.id, is: .required, ofType: .string), .field(post14.title, is: .required, ofType: .string), @@ -42,35 +49,35 @@ extension Post14 { .field(post14.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Post14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Post14 { + var id: FieldPath { + string("id") } - public var title: FieldPath { - string("title") + var title: FieldPath { + string("title") } - public var rating: FieldPath { - int("rating") + var rating: FieldPath { + int("rating") } - public var comments: ModelPath { - Comment14.Path(name: "comments", isCollection: true, parent: self) + var comments: ModelPath { + Comment14.Path(name: "comments", isCollection: true, parent: self) } - public var author: ModelPath { - User14.Path(name: "author", parent: self) + var author: ModelPath { + User14.Path(name: "author", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14.swift index 42d308e637..c290b4e22e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,38 +15,44 @@ public struct Post14: Model { public var rating: Int public var status: PostStatus public var comments: List? - internal var _author: LazyReference + var _author: LazyReference public var author: User14 { - get async throws { + get async throws { try await _author.require() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - rating: Int, - status: PostStatus, - comments: List? = [], - author: User14) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + rating: Int, + status: PostStatus, + comments: List? = [], + author: User14 + ) { + self.init( + id: id, title: title, rating: rating, status: status, comments: comments, author: author, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - rating: Int, - status: PostStatus, - comments: List? = [], - author: User14, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + rating: Int, + status: PostStatus, + comments: List? = [], + author: User14, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.rating = rating @@ -50,18 +63,18 @@ public struct Post14: Model { self.updatedAt = updatedAt } public mutating func setAuthor(_ author: User14) { - self._author = LazyReference(author) + _author = LazyReference(author) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - title = try values.decode(String.self, forKey: .title) - rating = try values.decode(Int.self, forKey: .rating) - status = try values.decode(PostStatus.self, forKey: .status) - comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() - _author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.title = try values.decode(String.self, forKey: .title) + self.rating = try values.decode(Int.self, forKey: .rating) + self.status = try values.decode(PostStatus.self, forKey: .status) + self.comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() + self._author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -74,4 +87,4 @@ public struct Post14: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/PostStatus.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/PostStatus.swift index 47329501d1..39a6c7f3e4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/PostStatus.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/PostStatus.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,4 +12,4 @@ import Foundation public enum PostStatus: String, EnumPersistable { case active = "ACTIVE" case inactive = "INACTIVE" -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14+Schema.swift index c9249873eb..20e2acd13b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension User14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension User14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case username case posts @@ -14,23 +21,23 @@ extension User14 { case updatedAt case user14SettingsId } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let user14 = User14.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "User14s" - + model.attributes( .primaryKey(fields: [user14.id]) ) - + model.fields( .field(user14.id, is: .required, ofType: .string), .field(user14.username, is: .required, ofType: .string), @@ -42,38 +49,38 @@ extension User14 { .field(user14.user14SettingsId, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension User14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == User14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == User14 { + var id: FieldPath { + string("id") } - public var username: FieldPath { - string("username") + var username: FieldPath { + string("username") } - public var posts: ModelPath { - Post14.Path(name: "posts", isCollection: true, parent: self) + var posts: ModelPath { + Post14.Path(name: "posts", isCollection: true, parent: self) } - public var comments: ModelPath { - Comment14.Path(name: "comments", isCollection: true, parent: self) + var comments: ModelPath { + Comment14.Path(name: "comments", isCollection: true, parent: self) } - public var settings: ModelPath { - UserSettings14.Path(name: "settings", parent: self) + var settings: ModelPath { + UserSettings14.Path(name: "settings", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } - public var user14SettingsId: FieldPath { - string("user14SettingsId") + var user14SettingsId: FieldPath { + string("user14SettingsId") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14.swift index b65799b382..7e075a3776 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,39 +14,45 @@ public struct User14: Model { public var username: String public var posts: List? public var comments: List? - internal var _settings: LazyReference + var _settings: LazyReference public var settings: UserSettings14? { - get async throws { + get async throws { try await _settings.get() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? public var user14SettingsId: String? - - public init(id: String = UUID().uuidString, - username: String, - posts: List? = [], - comments: List? = [], - settings: UserSettings14? = nil, - user14SettingsId: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + username: String, + posts: List? = [], + comments: List? = [], + settings: UserSettings14? = nil, + user14SettingsId: String? = nil + ) { + self.init( + id: id, username: username, posts: posts, comments: comments, settings: settings, createdAt: nil, updatedAt: nil, - user14SettingsId: user14SettingsId) + user14SettingsId: user14SettingsId + ) } - internal init(id: String = UUID().uuidString, - username: String, - posts: List? = [], - comments: List? = [], - settings: UserSettings14? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - user14SettingsId: String? = nil) { + init( + id: String = UUID().uuidString, + username: String, + posts: List? = [], + comments: List? = [], + settings: UserSettings14? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + user14SettingsId: String? = nil + ) { self.id = id self.username = username self.posts = posts @@ -50,18 +63,18 @@ public struct User14: Model { self.user14SettingsId = user14SettingsId } public mutating func setSettings(_ settings: UserSettings14? = nil) { - self._settings = LazyReference(settings) + _settings = LazyReference(settings) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - username = try values.decode(String.self, forKey: .username) - posts = try values.decodeIfPresent(List?.self, forKey: .posts) ?? .init() - comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() - _settings = try values.decodeIfPresent(LazyReference.self, forKey: .settings) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - user14SettingsId = try? values.decode(String?.self, forKey: .user14SettingsId) + self.id = try values.decode(String.self, forKey: .id) + self.username = try values.decode(String.self, forKey: .username) + self.posts = try values.decodeIfPresent(List?.self, forKey: .posts) ?? .init() + self.comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() + self._settings = try values.decodeIfPresent(LazyReference.self, forKey: .settings) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.user14SettingsId = try? values.decode(String?.self, forKey: .user14SettingsId) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -74,4 +87,4 @@ public struct User14: Model { try container.encode(updatedAt, forKey: .updatedAt) try container.encode(user14SettingsId, forKey: .user14SettingsId) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14+Schema.swift index 1bc8bcd441..2e8f1dfa0a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension UserSettings14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension UserSettings14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case language case user case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let userSettings14 = UserSettings14.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "UserSettings14s" - + model.attributes( .primaryKey(fields: [userSettings14.id]) ) - + model.fields( .field(userSettings14.id, is: .required, ofType: .string), .field(userSettings14.language, is: .optional, ofType: .string), @@ -36,29 +43,29 @@ extension UserSettings14 { .field(userSettings14.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension UserSettings14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == UserSettings14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == UserSettings14 { + var id: FieldPath { + string("id") } - public var language: FieldPath { - string("language") + var language: FieldPath { + string("language") } - public var user: ModelPath { - User14.Path(name: "user", parent: self) + var user: ModelPath { + User14.Path(name: "user", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14.swift index b0e8cbf0ff..6cc8ae97ae 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,29 +12,35 @@ import Foundation public struct UserSettings14: Model { public let id: String public var language: String? - internal var _user: LazyReference + var _user: LazyReference public var user: User14 { - get async throws { + get async throws { try await _user.require() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - language: String? = nil, - user: User14) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + language: String? = nil, + user: User14 + ) { + self.init( + id: id, language: language, user: user, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - language: String? = nil, - user: User14, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + language: String? = nil, + user: User14, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.language = language self._user = LazyReference(user) @@ -35,15 +48,15 @@ public struct UserSettings14: Model { self.updatedAt = updatedAt } public mutating func setUser(_ user: User14) { - self._user = LazyReference(user) + _user = LazyReference(user) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - language = try? values.decode(String?.self, forKey: .language) - _user = try values.decodeIfPresent(LazyReference.self, forKey: .user) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.language = try? values.decode(String?.self, forKey: .language) + self._user = try values.decodeIfPresent(LazyReference.self, forKey: .user) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -53,4 +66,4 @@ public struct UserSettings14: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel+Schema.swift index 654c541c4a..a93f3181c2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension EnumTestModel { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension EnumTestModel { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case enumVal case nullableEnumVal @@ -15,19 +22,19 @@ extension EnumTestModel { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let enumTestModel = EnumTestModel.keys - + model.pluralName = "EnumTestModels" - + model.attributes( .primaryKey(fields: [enumTestModel.id]) ) - + model.fields( .field(enumTestModel.id, is: .required, ofType: .string), .field(enumTestModel.enumVal, is: .required, ofType: .enum(type: TestEnum.self)), @@ -40,23 +47,23 @@ extension EnumTestModel { .field(enumTestModel.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension EnumTestModel: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == EnumTestModel { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == EnumTestModel { + var id: FieldPath { + string("id") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel.swift index 57a45cd219..de9368dd4d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct EnumTestModel: Model { public var nullableEnumNullableList: [TestEnum?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - enumVal: TestEnum, - nullableEnumVal: TestEnum? = nil, - enumList: [TestEnum] = [], - enumNullableList: [TestEnum]? = nil, - nullableEnumList: [TestEnum?] = [], - nullableEnumNullableList: [TestEnum?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + enumVal: TestEnum, + nullableEnumVal: TestEnum? = nil, + enumList: [TestEnum] = [], + enumNullableList: [TestEnum]? = nil, + nullableEnumList: [TestEnum?] = [], + nullableEnumNullableList: [TestEnum?]? = nil + ) { + self.init( + id: id, enumVal: enumVal, nullableEnumVal: nullableEnumVal, enumList: enumList, @@ -28,17 +38,20 @@ public struct EnumTestModel: Model { nullableEnumList: nullableEnumList, nullableEnumNullableList: nullableEnumNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - enumVal: TestEnum, - nullableEnumVal: TestEnum? = nil, - enumList: [TestEnum] = [], - enumNullableList: [TestEnum]? = nil, - nullableEnumList: [TestEnum?] = [], - nullableEnumNullableList: [TestEnum?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + enumVal: TestEnum, + nullableEnumVal: TestEnum? = nil, + enumList: [TestEnum] = [], + enumNullableList: [TestEnum]? = nil, + nullableEnumList: [TestEnum?] = [], + nullableEnumNullableList: [TestEnum?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.enumVal = enumVal self.nullableEnumVal = nullableEnumVal @@ -49,4 +62,4 @@ public struct EnumTestModel: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer+Schema.swift index 45a99508b6..77b79afd91 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ListIntContainer { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ListIntContainer { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case test case nullableInt @@ -15,19 +22,19 @@ extension ListIntContainer { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let listIntContainer = ListIntContainer.keys - + model.pluralName = "ListIntContainers" - + model.attributes( .primaryKey(fields: [listIntContainer.id]) ) - + model.fields( .field(listIntContainer.id, is: .required, ofType: .string), .field(listIntContainer.test, is: .required, ofType: .int), @@ -40,41 +47,41 @@ extension ListIntContainer { .field(listIntContainer.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ListIntContainer: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == ListIntContainer { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == ListIntContainer { + var id: FieldPath { + string("id") } - public var test: FieldPath { - int("test") + var test: FieldPath { + int("test") } - public var nullableInt: FieldPath { - int("nullableInt") + var nullableInt: FieldPath { + int("nullableInt") } - public var intList: FieldPath { - int("intList") + var intList: FieldPath { + int("intList") } - public var intNullableList: FieldPath { - int("intNullableList") + var intNullableList: FieldPath { + int("intNullableList") } - public var nullableIntList: FieldPath { - int("nullableIntList") + var nullableIntList: FieldPath { + int("nullableIntList") } - public var nullableIntNullableList: FieldPath { - int("nullableIntNullableList") + var nullableIntNullableList: FieldPath { + int("nullableIntNullableList") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer.swift index 040edd16e8..efb53081d8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct ListIntContainer: Model { public var nullableIntNullableList: [Int?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - test: Int, - nullableInt: Int? = nil, - intList: [Int] = [], - intNullableList: [Int]? = nil, - nullableIntList: [Int?] = [], - nullableIntNullableList: [Int?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + test: Int, + nullableInt: Int? = nil, + intList: [Int] = [], + intNullableList: [Int]? = nil, + nullableIntList: [Int?] = [], + nullableIntNullableList: [Int?]? = nil + ) { + self.init( + id: id, test: test, nullableInt: nullableInt, intList: intList, @@ -28,17 +38,20 @@ public struct ListIntContainer: Model { nullableIntList: nullableIntList, nullableIntNullableList: nullableIntNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - test: Int, - nullableInt: Int? = nil, - intList: [Int] = [], - intNullableList: [Int]? = nil, - nullableIntList: [Int?] = [], - nullableIntNullableList: [Int?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + test: Int, + nullableInt: Int? = nil, + intList: [Int] = [], + intNullableList: [Int]? = nil, + nullableIntList: [Int?] = [], + nullableIntNullableList: [Int?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.test = test self.nullableInt = nullableInt @@ -49,4 +62,4 @@ public struct ListIntContainer: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer+Schema.swift index 151cfaf8c7..505e667481 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ListStringContainer { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ListStringContainer { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case test case nullableString @@ -15,19 +22,19 @@ extension ListStringContainer { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let listStringContainer = ListStringContainer.keys - + model.pluralName = "ListStringContainers" - + model.attributes( .primaryKey(fields: [listStringContainer.id]) ) - + model.fields( .field(listStringContainer.id, is: .required, ofType: .string), .field(listStringContainer.test, is: .required, ofType: .string), @@ -40,41 +47,41 @@ extension ListStringContainer { .field(listStringContainer.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ListStringContainer: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == ListStringContainer { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == ListStringContainer { + var id: FieldPath { + string("id") } - public var test: FieldPath { - string("test") + var test: FieldPath { + string("test") } - public var nullableString: FieldPath { - string("nullableString") + var nullableString: FieldPath { + string("nullableString") } - public var stringList: FieldPath { - string("stringList") + var stringList: FieldPath { + string("stringList") } - public var stringNullableList: FieldPath { - string("stringNullableList") + var stringNullableList: FieldPath { + string("stringNullableList") } - public var nullableStringList: FieldPath { - string("nullableStringList") + var nullableStringList: FieldPath { + string("nullableStringList") } - public var nullableStringNullableList: FieldPath { - string("nullableStringNullableList") + var nullableStringNullableList: FieldPath { + string("nullableStringNullableList") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer.swift index cfe1107366..d08e28aa86 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct ListStringContainer: Model { public var nullableStringNullableList: [String?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - test: String, - nullableString: String? = nil, - stringList: [String] = [], - stringNullableList: [String]? = nil, - nullableStringList: [String?] = [], - nullableStringNullableList: [String?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + test: String, + nullableString: String? = nil, + stringList: [String] = [], + stringNullableList: [String]? = nil, + nullableStringList: [String?] = [], + nullableStringNullableList: [String?]? = nil + ) { + self.init( + id: id, test: test, nullableString: nullableString, stringList: stringList, @@ -28,17 +38,20 @@ public struct ListStringContainer: Model { nullableStringList: nullableStringList, nullableStringNullableList: nullableStringNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - test: String, - nullableString: String? = nil, - stringList: [String] = [], - stringNullableList: [String]? = nil, - nullableStringList: [String?] = [], - nullableStringNullableList: [String?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + test: String, + nullableString: String? = nil, + stringList: [String] = [], + stringNullableList: [String]? = nil, + nullableStringList: [String?] = [], + nullableStringNullableList: [String?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.test = test self.nullableString = nullableString @@ -49,4 +62,4 @@ public struct ListStringContainer: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested+Schema.swift index 1c83d051d7..d2cd8eeea4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested+Schema.swift @@ -1,25 +1,32 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Nested { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Nested { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case valueOne case valueTwo } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let nested = Nested.keys - + model.pluralName = "Nesteds" - + model.fields( .field(nested.valueOne, is: .optional, ofType: .int), .field(nested.valueTwo, is: .optional, ofType: .string) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested.swift index 37415d4550..19da9762a3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,4 +12,4 @@ import Foundation public struct Nested: Embeddable { var valueOne: Int? var valueTwo: String? -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel+Schema.swift index a01c7c3046..e92577edf2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension NestedTypeTestModel { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension NestedTypeTestModel { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case nestedVal case nullableNestedVal @@ -15,19 +22,19 @@ extension NestedTypeTestModel { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let nestedTypeTestModel = NestedTypeTestModel.keys - + model.pluralName = "NestedTypeTestModels" - + model.attributes( .primaryKey(fields: [nestedTypeTestModel.id]) ) - + model.fields( .field(nestedTypeTestModel.id, is: .required, ofType: .string), .field(nestedTypeTestModel.nestedVal, is: .required, ofType: .embedded(type: Nested.self)), @@ -40,23 +47,23 @@ extension NestedTypeTestModel { .field(nestedTypeTestModel.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension NestedTypeTestModel: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == NestedTypeTestModel { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == NestedTypeTestModel { + var id: FieldPath { + string("id") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel.swift index 2167581607..bd5c875239 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct NestedTypeTestModel: Model { public var nullableNestedNullableList: [Nested?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - nestedVal: Nested, - nullableNestedVal: Nested? = nil, - nestedList: [Nested] = [], - nestedNullableList: [Nested]? = nil, - nullableNestedList: [Nested?] = [], - nullableNestedNullableList: [Nested?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + nestedVal: Nested, + nullableNestedVal: Nested? = nil, + nestedList: [Nested] = [], + nestedNullableList: [Nested]? = nil, + nullableNestedList: [Nested?] = [], + nullableNestedNullableList: [Nested?]? = nil + ) { + self.init( + id: id, nestedVal: nestedVal, nullableNestedVal: nullableNestedVal, nestedList: nestedList, @@ -28,17 +38,20 @@ public struct NestedTypeTestModel: Model { nullableNestedList: nullableNestedList, nullableNestedNullableList: nullableNestedNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - nestedVal: Nested, - nullableNestedVal: Nested? = nil, - nestedList: [Nested] = [], - nestedNullableList: [Nested]? = nil, - nullableNestedList: [Nested?] = [], - nullableNestedNullableList: [Nested?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + nestedVal: Nested, + nullableNestedVal: Nested? = nil, + nestedList: [Nested] = [], + nestedNullableList: [Nested]? = nil, + nullableNestedList: [Nested?] = [], + nullableNestedNullableList: [Nested?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.nestedVal = nestedVal self.nullableNestedVal = nullableNestedVal @@ -49,4 +62,4 @@ public struct NestedTypeTestModel: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer+Schema.swift index a4db044062..0af1b206bc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ScalarContainer { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ScalarContainer { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case myString case myInt @@ -22,19 +29,19 @@ extension ScalarContainer { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let scalarContainer = ScalarContainer.keys - + model.pluralName = "ScalarContainers" - + model.attributes( .primaryKey(fields: [scalarContainer.id]) ) - + model.fields( .field(scalarContainer.id, is: .required, ofType: .string), .field(scalarContainer.myString, is: .optional, ofType: .string), @@ -54,62 +61,62 @@ extension ScalarContainer { .field(scalarContainer.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ScalarContainer: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == ScalarContainer { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == ScalarContainer { + var id: FieldPath { + string("id") } - public var myString: FieldPath { - string("myString") + var myString: FieldPath { + string("myString") } - public var myInt: FieldPath { - int("myInt") + var myInt: FieldPath { + int("myInt") } - public var myDouble: FieldPath { - double("myDouble") + var myDouble: FieldPath { + double("myDouble") } - public var myBool: FieldPath { - bool("myBool") + var myBool: FieldPath { + bool("myBool") } - public var myDate: FieldPath { - date("myDate") + var myDate: FieldPath { + date("myDate") } - public var myTime: FieldPath { - time("myTime") + var myTime: FieldPath { + time("myTime") } - public var myDateTime: FieldPath { - datetime("myDateTime") + var myDateTime: FieldPath { + datetime("myDateTime") } - public var myTimeStamp: FieldPath { - int("myTimeStamp") + var myTimeStamp: FieldPath { + int("myTimeStamp") } - public var myEmail: FieldPath { - string("myEmail") + var myEmail: FieldPath { + string("myEmail") } - public var myJSON: FieldPath { - string("myJSON") + var myJSON: FieldPath { + string("myJSON") } - public var myPhone: FieldPath { - string("myPhone") + var myPhone: FieldPath { + string("myPhone") } - public var myURL: FieldPath { - string("myURL") + var myURL: FieldPath { + string("myURL") } - public var myIPAddress: FieldPath { - string("myIPAddress") + var myIPAddress: FieldPath { + string("myIPAddress") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer.swift index 9559211652..ee87c57ecd 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -19,22 +26,25 @@ public struct ScalarContainer: Model { public var myIPAddress: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - myString: String? = nil, - myInt: Int? = nil, - myDouble: Double? = nil, - myBool: Bool? = nil, - myDate: Temporal.Date? = nil, - myTime: Temporal.Time? = nil, - myDateTime: Temporal.DateTime? = nil, - myTimeStamp: Int? = nil, - myEmail: String? = nil, - myJSON: String? = nil, - myPhone: String? = nil, - myURL: String? = nil, - myIPAddress: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + myString: String? = nil, + myInt: Int? = nil, + myDouble: Double? = nil, + myBool: Bool? = nil, + myDate: Temporal.Date? = nil, + myTime: Temporal.Time? = nil, + myDateTime: Temporal.DateTime? = nil, + myTimeStamp: Int? = nil, + myEmail: String? = nil, + myJSON: String? = nil, + myPhone: String? = nil, + myURL: String? = nil, + myIPAddress: String? = nil + ) { + self.init( + id: id, myString: myString, myInt: myInt, myDouble: myDouble, @@ -49,24 +59,27 @@ public struct ScalarContainer: Model { myURL: myURL, myIPAddress: myIPAddress, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - myString: String? = nil, - myInt: Int? = nil, - myDouble: Double? = nil, - myBool: Bool? = nil, - myDate: Temporal.Date? = nil, - myTime: Temporal.Time? = nil, - myDateTime: Temporal.DateTime? = nil, - myTimeStamp: Int? = nil, - myEmail: String? = nil, - myJSON: String? = nil, - myPhone: String? = nil, - myURL: String? = nil, - myIPAddress: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + myString: String? = nil, + myInt: Int? = nil, + myDouble: Double? = nil, + myBool: Bool? = nil, + myDate: Temporal.Date? = nil, + myTime: Temporal.Time? = nil, + myDateTime: Temporal.DateTime? = nil, + myTimeStamp: Int? = nil, + myEmail: String? = nil, + myJSON: String? = nil, + myPhone: String? = nil, + myURL: String? = nil, + myIPAddress: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.myString = myString self.myInt = myInt @@ -84,4 +97,4 @@ public struct ScalarContainer: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/TestEnum.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/TestEnum.swift index 8c0fdf51ef..774eca554f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/TestEnum.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/TestEnum.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,4 +12,4 @@ import Foundation public enum TestEnum: String, EnumPersistable { case valueOne = "VALUE_ONE" case valueTwo = "VALUE_TWO" -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadBlogPostComment8V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadBlogPostComment8V2Tests.swift index 5d370e3d08..5839fef4fa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadBlogPostComment8V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadBlogPostComment8V2Tests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBaseTest { @@ -21,20 +21,20 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas func testSaveBlog() async throws { await setup(withModels: BlogPostComment8V2Models()) - + let blog = Blog(name: "name") let savedBlog = try await createAndWaitForSync(blog) } - + func testSavePost() async throws { await setup(withModels: BlogPostComment8V2Models()) let blog = Blog(name: "name") let post = Post(name: "name", randomId: "randomId", blog: blog) let savedBlog = try await createAndWaitForSync(blog) let savedPost = try await createAndWaitForSync(post) - + } - + func testSaveComment() async throws { await setup(withModels: BlogPostComment8V2Models()) @@ -43,7 +43,7 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) } - + func testLazyLoad() async throws { await setup(withModels: BlogPostComment8V2Models()) @@ -54,63 +54,81 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) } - - func assertComment(_ comment: Comment, - hasEagerLoaded post: Post) async throws { - assertLazyReference(comment._post, - state: .loaded(model: post)) - + + func assertComment( + _ comment: Comment, + hasEagerLoaded post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) + guard let loadedPost = try await comment.post else { XCTFail("Failed to retrieve the post from the comment") return } XCTAssertEqual(loadedPost.id, post.id) - + try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertComment(_ comment: Comment, - canLazyLoad post: Post) async throws { - assertLazyReference(comment._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) + + func assertComment( + _ comment: Comment, + canLazyLoad post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)]) + ) guard let loadedPost = try await comment.post else { XCTFail("Failed to load the post from the comment") return } XCTAssertEqual(loadedPost.id, post.id) - assertLazyReference(comment._post, - state: .loaded(model: post)) + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertPost(_ post: Post, - canLazyLoad comment: Comment) async throws { + + func assertPost( + _ post: Post, + canLazyLoad comment: Comment + ) async throws { guard let comments = post.comments else { XCTFail("Missing comments on post") return } - assertList(comments, state: .isNotLoaded(associatedIds: [post.identifier], - associatedFields: ["post"])) - + assertList(comments, state: .isNotLoaded( + associatedIds: [post.identifier], + associatedFields: ["post"] + )) + try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) guard let comment = comments.first else { XCTFail("Missing lazy loaded comment from post") return } - + // further nested models should not be loaded - assertLazyReference(comment._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) + assertLazyReference( + comment._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)]) + ) } - + func testSaveWithoutPost() async throws { await setup(withModels: BlogPostComment8V2Models()) let comment = Comment(content: "content") let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: nil) + ) let post = Post(name: "name", randomId: "randomId") let savedPost = try await createAndWaitForSync(post) queriedComment.setPost(savedPost) @@ -118,7 +136,7 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas let queriedComment2 = try await query(for: saveCommentWithPost) try await assertComment(queriedComment2, canLazyLoad: post) } - + func testUpdateFromQueriedComment() async throws { await setup(withModels: BlogPostComment8V2Models()) let post = Post(name: "name", randomId: "randomId") @@ -126,24 +144,28 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) let queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)]) + ) let savedQueriedComment = try await updateAndWaitForSync(queriedComment) let queriedComment2 = try await query(for: savedQueriedComment) try await assertComment(queriedComment2, canLazyLoad: savedPost) } - + func testUpdateToNewPost() async throws { await setup(withModels: BlogPostComment8V2Models()) - + let post = Post(name: "name", randomId: "randomId") let comment = Comment(content: "content", post: post) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) - + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)]) + ) + let newPost = Post(name: "name") _ = try await createAndWaitForSync(newPost) queriedComment.setPost(newPost) @@ -151,28 +173,32 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas let queriedComment2 = try await query(for: saveCommentWithNewPost) try await assertComment(queriedComment2, canLazyLoad: newPost) } - + func testUpdateRemovePost() async throws { await setup(withModels: BlogPostComment8V2Models()) - + let post = Post(name: "name", randomId: "randomId") let comment = Comment(content: "content", post: post) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) - + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)]) + ) + queriedComment.setPost(nil) let saveCommentRemovePost = try await updateAndWaitForSync(queriedComment) let queriedCommentNoPost = try await query(for: saveCommentRemovePost) - assertLazyReference(queriedCommentNoPost._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedCommentNoPost._post, + state: .notLoaded(identifiers: nil) + ) } - + func testDelete() async throws { await setup(withModels: BlogPostComment8V2Models()) - + let post = Post(name: "name", randomId: "randomId") let comment = Comment(content: "content", post: post) let savedPost = try await createAndWaitForSync(post) @@ -181,7 +207,7 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas try await assertModelDoesNotExist(savedComment) try await assertModelDoesNotExist(savedPost) } - + func testObservePost() async throws { await setup(withModels: BlogPostComment8V2Models()) try await startAndWaitForReady() @@ -195,9 +221,9 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas version == 1, let receivedPost = try? mutationEvent.decodeModel(as: Post.self), receivedPost.id == post.id { - + try await createAndWaitForSync(comment) - + guard let comments = receivedPost.comments else { XCTFail("Lazy List does not exist") return @@ -208,23 +234,23 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveComment() async throws { await setup(withModels: BlogPostComment8V2Models()) try await startAndWaitForReady() @@ -244,18 +270,18 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: BlogPostComment8V2Models()) try await startAndWaitForReady() @@ -277,27 +303,27 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + snapshotReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryComment() async throws { await setup(withModels: BlogPostComment8V2Models()) try await startAndWaitForReady() - + let post = Post(name: "name", randomId: "randomId") let savedPost = try await createAndWaitForSync(post) let comment = Comment(content: "content", post: post) @@ -311,14 +337,14 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -348,15 +374,19 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas for try await mutationEvent in mutationEvents { if let receivedComment = try? mutationEvent.decodeModel(as: Comment.self), receivedComment.id == receivedComment.id { - assertLazyReference(receivedComment._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) + assertLazyReference( + receivedComment._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)]) + ) guard let loadedPost = try await comment.post else { XCTFail("Failed to load the post from the comment") return } XCTAssertEqual(loadedPost.id, post.id) - assertLazyReference(comment._post, - state: .loaded(model: post)) + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) mutationEventReceived.fulfill() } else { XCTFail("The model should be correctly decoded") @@ -367,7 +397,8 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas let deleteRequest = GraphQLRequest.deleteMutation( of: comment, modelSchema: Comment.schema, - version: 1) + version: 1 + ) do { let result = try await Amplify.API.mutate(request: deleteRequest) print(result) @@ -384,7 +415,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { typealias Blog = Blog8V2 typealias Post = Post8V2 typealias Comment = Comment8V2 - + struct BlogPostComment8V2Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadingBlogPostCmment8V2SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadingBlogPostCmment8V2SnapshotTests.swift index 9284c720e8..be5b7003b3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadingBlogPostCmment8V2SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadingBlogPostCmment8V2SnapshotTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { @@ -48,7 +48,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: blog, modelSchema: Blog.schema) let updateDocument = """ @@ -79,7 +79,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: blog, modelSchema: Blog.schema) let deleteDocument = """ @@ -110,7 +110,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Blog.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -141,7 +141,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Blog.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -172,7 +172,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Blog.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -203,7 +203,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Blog.self) let syncDocument = """ @@ -239,7 +239,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testPostSelectionSets() { setUpModelRegistrationOnly(withModels: BlogPostComment8V2Models()) continueAfterFailure = true @@ -285,7 +285,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: post, modelSchema: Post.schema) let updateDocument = """ @@ -327,7 +327,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: post, modelSchema: Post.schema) let deleteDocument = """ @@ -369,7 +369,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -393,7 +393,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -417,7 +417,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -441,7 +441,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -470,13 +470,13 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testCommentSelectionSets() { setUpModelRegistrationOnly(withModels: BlogPostComment8V2Models()) continueAfterFailure = true let post = Post(name: "name") let comment = Comment(content: "content", post: post) - + // Create let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) let createDocument = """ @@ -505,7 +505,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: comment, modelSchema: Comment.schema) let updateDocument = """ @@ -534,7 +534,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: comment, modelSchema: Comment.schema) let deleteDocument = """ @@ -563,7 +563,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Comment.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -586,7 +586,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -609,7 +609,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -632,7 +632,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Comment.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2+Schema.swift index 04bf6c0913..cf1926979a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Blog8V2 { +public extension Blog8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case customs @@ -13,19 +20,19 @@ extension Blog8V2 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let blog8V2 = Blog8V2.keys - + model.pluralName = "Blog8V2s" - + model.attributes( .primaryKey(fields: [blog8V2.id]) ) - + model.fields( .field(blog8V2.id, is: .required, ofType: .string), .field(blog8V2.name, is: .required, ofType: .string), @@ -36,32 +43,32 @@ extension Blog8V2 { .field(blog8V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Blog8V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Blog8V2 { - public var id: FieldPath { +public extension ModelPath where ModelType == Blog8V2 { + var id: FieldPath { string("id") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var notes: FieldPath { + var notes: FieldPath { string("notes") } - public var posts: ModelPath { + var posts: ModelPath { Post8V2.Path(name: "posts", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2.swift index 53a81844ff..c317d9f8c3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -10,27 +17,33 @@ public struct Blog8V2: Model { public var posts: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [] + ) { + self.init( + id: id, name: name, customs: customs, notes: notes, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.customs = customs diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2+Schema.swift index 09c2b3de65..1e6ae176b2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment8V2 { +public extension Comment8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let comment8V2 = Comment8V2.keys - + model.pluralName = "Comment8V2s" - + model.attributes( .index(fields: ["postId"], name: "commentByPost"), .primaryKey(fields: [comment8V2.id]) ) - + model.fields( .field(comment8V2.id, is: .required, ofType: .string), .field(comment8V2.content, is: .optional, ofType: .string), @@ -33,29 +40,29 @@ extension Comment8V2 { .field(comment8V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment8V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Comment8V2 { - public var id: FieldPath { +public extension ModelPath where ModelType == Comment8V2 { + var id: FieldPath { string("id") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var post: ModelPath { + var post: ModelPath { Post8V2.Path(name: "post", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2.swift index ab6e1c697a..6f141be4fc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Comment8V2: Model { public let id: String public var content: String? - internal var _post: LazyReference + var _post: LazyReference public var post: Post8V2? { get async throws { try await _post.get() @@ -13,21 +20,27 @@ public struct Comment8V2: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8V2? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct Comment8V2: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post8V2? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try? values.decode(String?.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try? values.decode(String?.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8+Schema.swift index 2c926d8ab8..b243eec04e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8+Schema.swift @@ -1,24 +1,31 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension MyCustomModel8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension MyCustomModel8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case desc case children } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let myCustomModel8 = MyCustomModel8.keys - + model.pluralName = "MyCustomModel8s" - + model.fields( .field(myCustomModel8.id, is: .required, ofType: .string), .field(myCustomModel8.name, is: .required, ofType: .string), @@ -26,4 +33,4 @@ extension MyCustomModel8 { .field(myCustomModel8.children, is: .optional, ofType: .embeddedCollection(of: MyNestedModel8.self)) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8.swift index 6fb7a2b02d..152b045540 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,4 +14,4 @@ public struct MyCustomModel8: Embeddable { var name: String var desc: String? var children: [MyNestedModel8?]? -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8+Schema.swift index da4f5f1040..871a8a25a7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8+Schema.swift @@ -1,27 +1,34 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension MyNestedModel8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension MyNestedModel8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case nestedName case notes } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let myNestedModel8 = MyNestedModel8.keys - + model.pluralName = "MyNestedModel8s" - + model.fields( .field(myNestedModel8.id, is: .required, ofType: .string), .field(myNestedModel8.nestedName, is: .required, ofType: .string), .field(myNestedModel8.notes, is: .optional, ofType: .embeddedCollection(of: String.self)) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8.swift index 9884b8a197..6a99c2e543 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -6,4 +13,4 @@ public struct MyNestedModel8: Embeddable { var id: String var nestedName: String var notes: [String?]? -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2+Schema.swift index b2d02ddfa0..0ea3d6a6f4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post8V2 { +public extension Post8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case randomId @@ -13,21 +20,21 @@ extension Post8V2 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let post8V2 = Post8V2.keys - + model.pluralName = "Post8V2s" - + model.attributes( .index(fields: ["blogId"], name: "postByBlog"), .index(fields: ["randomId"], name: "byRandom"), .primaryKey(fields: [post8V2.id]) ) - + model.fields( .field(post8V2.id, is: .required, ofType: .string), .field(post8V2.name, is: .required, ofType: .string), @@ -38,35 +45,35 @@ extension Post8V2 { .field(post8V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post8V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Post8V2 { - public var id: FieldPath { +public extension ModelPath where ModelType == Post8V2 { + var id: FieldPath { string("id") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var randomId: FieldPath { + var randomId: FieldPath { string("randomId") } - public var blog: ModelPath { + var blog: ModelPath { Blog8V2.Path(name: "blog", parent: self) } - public var comments: ModelPath { + var comments: ModelPath { Comment8V2.Path(name: "comments", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2.swift index 7e5805afb9..9d416ecf23 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -6,7 +13,7 @@ public struct Post8V2: Model { public let id: String public var name: String public var randomId: String? - internal var _blog: LazyReference + var _blog: LazyReference public var blog: Blog8V2? { get async throws { try await _blog.get() @@ -15,27 +22,33 @@ public struct Post8V2: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8V2? = nil, - comments: List? = []) { - self.init(id: id, - name: name, - randomId: randomId, - blog: blog, - comments: comments, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8V2? = nil, + comments: List? = [] + ) { + self.init( + id: id, + name: name, + randomId: randomId, + blog: blog, + comments: comments, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8V2? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8V2? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.randomId = randomId @@ -45,17 +58,17 @@ public struct Post8V2: Model { self.updatedAt = updatedAt } public mutating func setBlog(_ blog: Blog8V2? = nil) { - self._blog = LazyReference(blog) + _blog = LazyReference(blog) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - name = try values.decode(String.self, forKey: .name) - randomId = try? values.decode(String?.self, forKey: .randomId) - _blog = try values.decodeIfPresent(LazyReference.self, forKey: .blog) ?? LazyReference(identifiers: nil) - comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.name = try values.decode(String.self, forKey: .name) + self.randomId = try? values.decode(String?.self, forKey: .randomId) + self._blog = try values.decodeIfPresent(LazyReference.self, forKey: .blog) ?? LazyReference(identifiers: nil) + self.comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeySnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeySnapshotTests.swift index cc2b1f7291..f73a65a3a4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeySnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeySnapshotTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { - + func testPostSelectionSets() { setUpModelRegistrationOnly(withModels: PostCommentWithCompositeKeyModels()) continueAfterFailure = true @@ -35,7 +35,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: post, modelSchema: Post.schema) let updateDocument = """ @@ -53,7 +53,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: post, modelSchema: Post.schema) let deleteDocument = """ @@ -71,7 +71,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -89,7 +89,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -107,7 +107,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -125,7 +125,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -148,13 +148,13 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testCommentSelectionSets() { setUpModelRegistrationOnly(withModels: PostCommentWithCompositeKeyModels()) continueAfterFailure = true let post = Post(title: "title") let comment = Comment(content: "content", post: post) - + // Create let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) let createDocument = """ @@ -182,7 +182,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: comment, modelSchema: Comment.schema) let updateDocument = """ @@ -210,7 +210,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: comment, modelSchema: Comment.schema) let deleteDocument = """ @@ -238,7 +238,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Comment.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -262,7 +262,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -286,7 +286,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -310,7 +310,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Comment.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests.swift index d55cd9356f..64d7ff6b3b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests.swift @@ -5,18 +5,18 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLazyLoadBaseTest { func testLazyLoad() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) - + let post = Post(title: "title") let comment = Comment(content: "content", post: post) let savedPost = try await createAndWaitForSync(post) @@ -28,73 +28,91 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa let queriedPost = try await query(for: savedPost) try await assertPost(queriedPost, canLazyLoad: savedComment) } - - func assertComment(_ comment: Comment, - hasEagerLoaded post: Post) async throws { - assertLazyReference(comment._post, - state: .loaded(model: post)) - + + func assertComment( + _ comment: Comment, + hasEagerLoaded post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) + guard let loadedPost = try await comment.post else { XCTFail("Failed to retrieve the post from the comment") return } XCTAssertEqual(loadedPost.id, post.id) - + // retrieve loaded model guard let loadedPost = try await comment.post else { XCTFail("Failed to retrieve the loaded post from the comment") return } XCTAssertEqual(loadedPost.id, post.id) - + try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertComment(_ comment: Comment, - canLazyLoad post: Post) async throws { - assertLazyReference(comment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.id.stringValue, value: post.id), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) + + func assertComment( + _ comment: Comment, + canLazyLoad post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.id.stringValue, value: post.id), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) guard let loadedPost = try await comment.post else { XCTFail("Failed to load the post from the comment") return } XCTAssertEqual(loadedPost.id, post.id) - assertLazyReference(comment._post, - state: .loaded(model: post)) + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertPost(_ post: Post, - canLazyLoad comment: Comment) async throws { + + func assertPost( + _ post: Post, + canLazyLoad comment: Comment + ) async throws { guard let comments = post.comments else { XCTFail("Missing comments on post") return } - assertList(comments, state: .isNotLoaded(associatedIds: [post.identifier], - associatedFields: ["post"])) + assertList(comments, state: .isNotLoaded( + associatedIds: [post.identifier], + associatedFields: ["post"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) guard let comment = comments.first else { XCTFail("Missing lazy loaded comment from post") return } - assertLazyReference(comment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.id.stringValue, value: post.id), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) + assertLazyReference( + comment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.id.stringValue, value: post.id), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) } - + func testSaveWithoutPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let comment = Comment(content: "content") let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: nil) + ) let post = Post(title: "title") let savedPost = try await createAndWaitForSync(post) queriedComment.setPost(savedPost) @@ -102,7 +120,7 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa let queriedComment2 = try await query(for: saveCommentWithPost) try await assertComment(queriedComment2, canLazyLoad: post) } - + func testUpdateFromQueriedComment() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") @@ -110,30 +128,34 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) let queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.id.stringValue, value: post.id), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.id.stringValue, value: post.id), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) let savedQueriedComment = try await updateAndWaitForSync(queriedComment) let queriedComment2 = try await query(for: savedQueriedComment) try await assertComment(queriedComment2, canLazyLoad: savedPost) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) - + let post = Post(title: "title") let comment = Comment(content: "content", post: post) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.id.stringValue, value: post.id), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) - + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.id.stringValue, value: post.id), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) + let newPost = Post(title: "title") _ = try await createAndWaitForSync(newPost) queriedComment.setPost(newPost) @@ -141,31 +163,35 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa let queriedComment2 = try await query(for: saveCommentWithNewPost) try await assertComment(queriedComment2, canLazyLoad: newPost) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) - + let post = Post(title: "title") let comment = Comment(content: "content", post: post) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.id.stringValue, value: post.id), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) - + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.id.stringValue, value: post.id), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) + queriedComment.setPost(nil) let saveCommentRemovePost = try await updateAndWaitForSync(queriedComment) let queriedCommentNoPost = try await query(for: saveCommentRemovePost) - assertLazyReference(queriedCommentNoPost._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedCommentNoPost._post, + state: .notLoaded(identifiers: nil) + ) } - + func testDelete() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) - + let post = Post(title: "title") let comment = Comment(content: "content", post: post) let savedPost = try await createAndWaitForSync(post) @@ -174,7 +200,7 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa try await assertModelDoesNotExist(savedComment) try await assertModelDoesNotExist(savedPost) } - + func testObservePost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) try await startAndWaitForReady() @@ -188,7 +214,7 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa version == 1, let receivedPost = try? mutationEvent.decodeModel(as: Post.self), receivedPost.id == post.id { - + try await createAndWaitForSync(comment) guard let comments = receivedPost.comments else { XCTFail("Lazy List does not exist") @@ -200,23 +226,23 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveComment() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) try await startAndWaitForReady() @@ -236,18 +262,18 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) try await startAndWaitForReady() @@ -269,27 +295,27 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + snapshotReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryComment() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) try await startAndWaitForReady() - + let post = Post(title: "title") let savedPost = try await createAndWaitForSync(post) let comment = Comment(content: "content", post: post) @@ -303,14 +329,14 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -319,7 +345,7 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { typealias Post = PostWithCompositeKey typealias Comment = CommentWithCompositeKey - + struct PostCommentWithCompositeKeyModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey+Schema.swift index 9b70a40965..d5835f7876 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CommentWithCompositeKey { +public extension CommentWithCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let commentWithCompositeKey = CommentWithCompositeKey.keys - + model.pluralName = "CommentWithCompositeKeys" - + model.attributes( .index(fields: ["id", "content"], name: nil), .primaryKey(fields: [commentWithCompositeKey.id, commentWithCompositeKey.content]) ) - + model.fields( .field(commentWithCompositeKey.id, is: .required, ofType: .string), .field(commentWithCompositeKey.content, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension CommentWithCompositeKey { .field(commentWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension CommentWithCompositeKey: ModelIdentifiable { @@ -43,26 +50,28 @@ extension CommentWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CommentWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - content: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "content", value: content)]) +public extension CommentWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + content: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "content", value: content)]) } } -extension ModelPath where ModelType == CommentWithCompositeKey { - public var id: FieldPath { +public extension ModelPath where ModelType == CommentWithCompositeKey { + var id: FieldPath { string("id") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var post: ModelPath { + var post: ModelPath { PostWithCompositeKey.Path(name: "post", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey.swift index c3db0086aa..7e483fc203 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct CommentWithCompositeKey: Model { public let id: String public let content: String - internal var _post: LazyReference + var _post: LazyReference public var post: PostWithCompositeKey? { get async throws { try await _post.get() @@ -13,21 +20,27 @@ public struct CommentWithCompositeKey: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKey? = nil) { - self.init(id: id, - content: content, - post: post, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKey? = nil + ) { + self.init( + id: id, + content: content, + post: post, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKey? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKey? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct CommentWithCompositeKey: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: PostWithCompositeKey? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try values.decode(String.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try values.decode(String.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey+Schema.swift index 04c89f21f1..a7061afc79 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithCompositeKey { +public extension PostWithCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let postWithCompositeKey = PostWithCompositeKey.keys - + model.pluralName = "PostWithCompositeKeys" - + model.attributes( .index(fields: ["id", "title"], name: nil), .primaryKey(fields: [postWithCompositeKey.id, postWithCompositeKey.title]) ) - + model.fields( .field(postWithCompositeKey.id, is: .required, ofType: .string), .field(postWithCompositeKey.title, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension PostWithCompositeKey { .field(postWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PostWithCompositeKey: ModelIdentifiable { @@ -43,26 +50,28 @@ extension PostWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - title: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "title", value: title)]) +public extension PostWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + title: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "title", value: title)]) } } -extension ModelPath where ModelType == PostWithCompositeKey { - public var id: FieldPath { +public extension ModelPath where ModelType == PostWithCompositeKey { + var id: FieldPath { string("id") } - public var title: FieldPath { + var title: FieldPath { string("title") } - public var comments: ModelPath { + var comments: ModelPath { CommentWithCompositeKey.Path(name: "comments", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey.swift index e9de7de986..ac441cae5d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithCompositeKey: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagSnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagSnapshotTests.swift index fa0b254a08..a0af212826 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagSnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagSnapshotTests.swift @@ -5,19 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPostTagTests { - + func testPostSelectionSets() async throws { await setup(withModels: PostTagModels()) continueAfterFailure = true - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -40,11 +40,11 @@ extension AWSDataStoreLazyLoadPostTagTests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testTagSelectionSets() async throws { await setup(withModels: PostTagModels()) continueAfterFailure = true - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Tag.self) let syncDocument = """ @@ -67,11 +67,11 @@ extension AWSDataStoreLazyLoadPostTagTests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testPostTagSelectionSets() async throws { await setup(withModels: PostTagModels()) continueAfterFailure = true - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: PostTag.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagTests.swift index b750c45194..16ba9ce97c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { @@ -18,7 +18,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { await setup(withModels: PostTagModels()) try await startAndWaitForReady() } - + func testLazyLoad() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -27,7 +27,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let savedPost = try await createAndWaitForSync(post) let savedTag = try await createAndWaitForSync(tag) let savedPostTag = try await createAndWaitForSync(postTag) - + try await assertPost(savedPost, canLazyLoad: savedPostTag) try await assertTag(savedTag, canLazyLoad: savedPostTag) assertLazyReference( @@ -51,44 +51,54 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let queriedPostTag = try await query(for: savedPostTag) try await assertPostTag(queriedPostTag, canLazyLoadTag: savedTag, canLazyLoadPost: savedPost) } - - func assertPost(_ post: Post, - canLazyLoad postTag: PostTag) async throws { + + func assertPost( + _ post: Post, + canLazyLoad postTag: PostTag + ) async throws { guard let postTags = post.tags else { XCTFail("Missing postTags on post") return } - assertList(postTags, state: .isNotLoaded(associatedIds: [post.identifier], - associatedFields: ["postWithTagsCompositeKey"])) + assertList(postTags, state: .isNotLoaded( + associatedIds: [post.identifier], + associatedFields: ["postWithTagsCompositeKey"] + )) try await postTags.fetch() assertList(postTags, state: .isLoaded(count: 1)) } - - func assertTag(_ tag: Tag, - canLazyLoad postTag: PostTag) async throws { + + func assertTag( + _ tag: Tag, + canLazyLoad postTag: PostTag + ) async throws { guard let postTags = tag.posts else { XCTFail("Missing postTags on post") return } - assertList(postTags, state: .isNotLoaded(associatedIds: [tag.identifier], - associatedFields: ["tagWithCompositeKey"])) + assertList(postTags, state: .isNotLoaded( + associatedIds: [tag.identifier], + associatedFields: ["tagWithCompositeKey"] + )) try await postTags.fetch() assertList(postTags, state: .isLoaded(count: 1)) } - + func assertPostTag(_ postTag: PostTag, canLazyLoadTag tag: Tag, canLazyLoadPost post: Post) async throws { assertLazyReference( postTag._tagWithCompositeKey, state: .notLoaded(identifiers: [ .init(name: Tag.keys.id.stringValue, value: tag.id), .init(name: Tag.keys.name.stringValue, value: tag.name) - ])) + ]) + ) assertLazyReference( postTag._postWithTagsCompositeKey, state: .notLoaded(identifiers: [ .init(name: Post.keys.postId.stringValue, value: post.postId), .init(name: Post.keys.title.stringValue, value: post.title) - ])) + ]) + ) let loadedTag = try await postTag.tagWithCompositeKey assertLazyReference(postTag._tagWithCompositeKey, state: .loaded(model: loadedTag)) try await assertTag(loadedTag, canLazyLoad: postTag) @@ -96,7 +106,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { assertLazyReference(postTag._postWithTagsCompositeKey, state: .loaded(model: loadedPost)) try await assertPost(loadedPost, canLazyLoad: postTag) } - + func testUpdate() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -105,7 +115,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let savedPost = try await createAndWaitForSync(post) let savedTag = try await createAndWaitForSync(tag) let savedPostTag = try await createAndWaitForSync(postTag) - + // update the post tag with a new post var queriedPostTag = try await query(for: savedPostTag) let newPost = Post(postId: UUID().uuidString, title: "title") @@ -121,7 +131,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { ) let queriedPreviousPost = try await query(for: savedPost) try await assertPostWithNoPostTag(queriedPreviousPost) - + // update the post tag with a new tag var queriedPostTagWithNewPost = try await query(for: savedPostTagWithNewPost) let newTag = Tag(name: "name") @@ -138,29 +148,33 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let queriedPreviousTag = try await query(for: savedTag) try await assertTagWithNoPostTag(queriedPreviousTag) } - + func assertPostWithNoPostTag(_ post: Post) async throws { guard let postTags = post.tags else { XCTFail("Missing postTags on post") return } - assertList(postTags, state: .isNotLoaded(associatedIds: [post.identifier], - associatedFields: ["postWithTagsCompositeKey"])) + assertList(postTags, state: .isNotLoaded( + associatedIds: [post.identifier], + associatedFields: ["postWithTagsCompositeKey"] + )) try await postTags.fetch() assertList(postTags, state: .isLoaded(count: 0)) } - + func assertTagWithNoPostTag(_ tag: Tag) async throws { guard let postTags = tag.posts else { XCTFail("Missing postTags on post") return } - assertList(postTags, state: .isNotLoaded(associatedIds: [tag.identifier], - associatedFields: ["tagWithCompositeKey"])) + assertList(postTags, state: .isNotLoaded( + associatedIds: [tag.identifier], + associatedFields: ["tagWithCompositeKey"] + )) try await postTags.fetch() assertList(postTags, state: .isLoaded(count: 0)) } - + func testDeletePost() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -169,14 +183,14 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let savedPost = try await createAndWaitForSync(post) let savedTag = try await createAndWaitForSync(tag) let savedPostTag = try await createAndWaitForSync(postTag) - + try await deleteAndWaitForSync(savedPost) - + try await assertModelDoesNotExist(savedPost) try await assertModelExists(savedTag) try await assertModelDoesNotExist(savedPostTag) } - + func testDeleteTag() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -185,14 +199,14 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let savedPost = try await createAndWaitForSync(post) let savedTag = try await createAndWaitForSync(tag) let savedPostTag = try await createAndWaitForSync(postTag) - + try await deleteAndWaitForSync(savedTag) - + try await assertModelExists(savedPost) try await assertModelDoesNotExist(savedTag) try await assertModelDoesNotExist(savedPostTag) } - + func testDeletePostTag() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -201,14 +215,14 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let savedPost = try await createAndWaitForSync(post) let savedTag = try await createAndWaitForSync(tag) let savedPostTag = try await createAndWaitForSync(postTag) - + try await deleteAndWaitForSync(savedPostTag) - + try await assertModelExists(savedPost) try await assertModelExists(savedTag) try await assertModelDoesNotExist(savedPostTag) } - + func testObservePost() async throws { await setup(withModels: PostTagModels()) try await startAndWaitForReady() @@ -221,7 +235,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { version == 1, let receivedPost = try? mutationEvent.decodeModel(as: Post.self), receivedPost.postId == post.postId { - + guard let tags = receivedPost.tags else { XCTFail("Lazy List does not exist") return @@ -232,7 +246,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load \(error)") } XCTAssertEqual(tags.count, 0) - + mutationEventReceived.fulfill() } } @@ -243,16 +257,16 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveTag() async throws { await setup(withModels: PostTagModels()) try await startAndWaitForReady() let tag = Tag(name: "name") - + let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Tag.self) Task { @@ -271,7 +285,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load \(error)") } XCTAssertEqual(posts.count, 0) - + mutationEventReceived.fulfill() } } @@ -282,11 +296,11 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObservePostTag() async throws { await setup(withModels: PostTagModels()) try await startAndWaitForReady() @@ -294,10 +308,11 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let tag = Tag(name: "name") let savedPost = try await createAndWaitForSync(post) let savedTag = try await createAndWaitForSync(tag) - _ = savedPost; _ = savedTag + _ = savedPost + _ = savedTag let postTag = PostTag(postWithTagsCompositeKey: post, tagWithCompositeKey: tag) - + let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(PostTag.self) Task { @@ -306,24 +321,24 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { version == 1, let receivedPostTag = try? mutationEvent.decodeModel(as: PostTag.self), receivedPostTag.id == postTag.id { - + try await assertPostTag(receivedPostTag, canLazyLoadTag: tag, canLazyLoadPost: post) mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: postTag, modelSchema: PostTag.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: PostTagModels()) try await startAndWaitForReady() @@ -343,7 +358,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load \(error)") } XCTAssertEqual(tags.count, 0) - + snapshotReceived.fulfill() } } @@ -354,16 +369,16 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryTag() async throws { await setup(withModels: PostTagModels()) try await startAndWaitForReady() let tag = Tag(name: "name") - + let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Tag.self, where: Tag.keys.id == tag.id) Task { @@ -379,7 +394,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load \(error)") } XCTAssertEqual(posts.count, 0) - + snapshotReceived.fulfill() } } @@ -390,11 +405,11 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryPostTag() async throws { await setup(withModels: PostTagModels()) try await startAndWaitForReady() @@ -402,9 +417,9 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let tag = Tag(name: "name") try await createAndWaitForSync(post) try await createAndWaitForSync(tag) - + let postTag = PostTag(postWithTagsCompositeKey: post, tagWithCompositeKey: tag) - + let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: PostTag.self, where: PostTag.keys.id == postTag.id) Task { @@ -415,14 +430,14 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: postTag, modelSchema: PostTag.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -432,7 +447,7 @@ extension AWSDataStoreLazyLoadPostTagTests { typealias Post = PostWithTagsCompositeKey typealias Tag = TagWithCompositeKey typealias PostTag = PostTagsWithCompositeKey - + struct PostTagModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey+Schema.swift index 59cd80dd74..9ea2ee8d95 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostTagsWithCompositeKey { +public extension PostTagsWithCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case postWithTagsCompositeKey case tagWithCompositeKey case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let postTagsWithCompositeKey = PostTagsWithCompositeKey.keys - + model.pluralName = "PostTagsWithCompositeKeys" - + model.attributes( .index(fields: ["postWithTagsCompositeKeyPostId", "postWithTagsCompositeKeytitle"], name: "byPostWithTagsCompositeKey"), .index(fields: ["tagWithCompositeKeyId", "tagWithCompositeKeyname"], name: "byTagWithCompositeKey"), .primaryKey(fields: [postTagsWithCompositeKey.id]) ) - + model.fields( .field(postTagsWithCompositeKey.id, is: .required, ofType: .string), .belongsTo(postTagsWithCompositeKey.postWithTagsCompositeKey, is: .required, ofType: PostWithTagsCompositeKey.self, targetNames: ["postWithTagsCompositeKeyPostId", "postWithTagsCompositeKeytitle"]), @@ -34,29 +41,29 @@ extension PostTagsWithCompositeKey { .field(postTagsWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PostTagsWithCompositeKey: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == PostTagsWithCompositeKey { - public var id: FieldPath { +public extension ModelPath where ModelType == PostTagsWithCompositeKey { + var id: FieldPath { string("id") } - public var postWithTagsCompositeKey: ModelPath { + var postWithTagsCompositeKey: ModelPath { PostWithTagsCompositeKey.Path(name: "postWithTagsCompositeKey", parent: self) } - public var tagWithCompositeKey: ModelPath { + var tagWithCompositeKey: ModelPath { TagWithCompositeKey.Path(name: "tagWithCompositeKey", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey.swift index a248ebe072..45108cf5a8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey.swift @@ -1,16 +1,23 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation public struct PostTagsWithCompositeKey: Model { public let id: String - internal var _postWithTagsCompositeKey: LazyReference + var _postWithTagsCompositeKey: LazyReference public var postWithTagsCompositeKey: PostWithTagsCompositeKey { get async throws { try await _postWithTagsCompositeKey.require() } } - internal var _tagWithCompositeKey: LazyReference + var _tagWithCompositeKey: LazyReference public var tagWithCompositeKey: TagWithCompositeKey { get async throws { try await _tagWithCompositeKey.require() @@ -18,21 +25,27 @@ public struct PostTagsWithCompositeKey: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - postWithTagsCompositeKey: PostWithTagsCompositeKey, - tagWithCompositeKey: TagWithCompositeKey) { - self.init(id: id, - postWithTagsCompositeKey: postWithTagsCompositeKey, - tagWithCompositeKey: tagWithCompositeKey, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + postWithTagsCompositeKey: PostWithTagsCompositeKey, + tagWithCompositeKey: TagWithCompositeKey + ) { + self.init( + id: id, + postWithTagsCompositeKey: postWithTagsCompositeKey, + tagWithCompositeKey: tagWithCompositeKey, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - postWithTagsCompositeKey: PostWithTagsCompositeKey, - tagWithCompositeKey: TagWithCompositeKey, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + postWithTagsCompositeKey: PostWithTagsCompositeKey, + tagWithCompositeKey: TagWithCompositeKey, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self._postWithTagsCompositeKey = LazyReference(postWithTagsCompositeKey) self._tagWithCompositeKey = LazyReference(tagWithCompositeKey) @@ -40,18 +53,18 @@ public struct PostTagsWithCompositeKey: Model { self.updatedAt = updatedAt } public mutating func setPostWithTagsCompositeKey(_ postWithTagsCompositeKey: PostWithTagsCompositeKey) { - self._postWithTagsCompositeKey = LazyReference(postWithTagsCompositeKey) + _postWithTagsCompositeKey = LazyReference(postWithTagsCompositeKey) } public mutating func setTagWithCompositeKey(_ tagWithCompositeKey: TagWithCompositeKey) { - self._tagWithCompositeKey = LazyReference(tagWithCompositeKey) + _tagWithCompositeKey = LazyReference(tagWithCompositeKey) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - _postWithTagsCompositeKey = try values.decodeIfPresent(LazyReference.self, forKey: .postWithTagsCompositeKey) ?? LazyReference(identifiers: nil) - _tagWithCompositeKey = try values.decodeIfPresent(LazyReference.self, forKey: .tagWithCompositeKey) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self._postWithTagsCompositeKey = try values.decodeIfPresent(LazyReference.self, forKey: .postWithTagsCompositeKey) ?? LazyReference(identifiers: nil) + self._tagWithCompositeKey = try values.decodeIfPresent(LazyReference.self, forKey: .tagWithCompositeKey) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey+Schema.swift index 888c9b969a..eeb2570973 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithTagsCompositeKey { +public extension PostWithTagsCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case postId case title case tags case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let postWithTagsCompositeKey = PostWithTagsCompositeKey.keys - + model.pluralName = "PostWithTagsCompositeKeys" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [postWithTagsCompositeKey.postId, postWithTagsCompositeKey.title]) ) - + model.fields( .field(postWithTagsCompositeKey.postId, is: .required, ofType: .string), .field(postWithTagsCompositeKey.title, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension PostWithTagsCompositeKey { .field(postWithTagsCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PostWithTagsCompositeKey: ModelIdentifiable { @@ -43,26 +50,28 @@ extension PostWithTagsCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithTagsCompositeKey.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension PostWithTagsCompositeKey.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } } -extension ModelPath where ModelType == PostWithTagsCompositeKey { - public var postId: FieldPath { +public extension ModelPath where ModelType == PostWithTagsCompositeKey { + var postId: FieldPath { string("postId") } - public var title: FieldPath { + var title: FieldPath { string("title") } - public var tags: ModelPath { + var tags: ModelPath { PostTagsWithCompositeKey.Path(name: "tags", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey.swift index c739bc9c22..73e3e3cd7c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithTagsCompositeKey: Model { public var tags: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - tags: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + tags: List? = [] + ) { + self.init( + postId: postId, title: title, tags: tags, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - tags: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + tags: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.tags = tags self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey+Schema.swift index 95a6c9bf82..c6dc88f2f2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension TagWithCompositeKey { +public extension TagWithCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let tagWithCompositeKey = TagWithCompositeKey.keys - + model.pluralName = "TagWithCompositeKeys" - + model.attributes( .index(fields: ["id", "name"], name: nil), .primaryKey(fields: [tagWithCompositeKey.id, tagWithCompositeKey.name]) ) - + model.fields( .field(tagWithCompositeKey.id, is: .required, ofType: .string), .field(tagWithCompositeKey.name, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension TagWithCompositeKey { .field(tagWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension TagWithCompositeKey: ModelIdentifiable { @@ -43,26 +50,28 @@ extension TagWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension TagWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - name: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "name", value: name)]) +public extension TagWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + name: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "name", value: name)]) } } -extension ModelPath where ModelType == TagWithCompositeKey { - public var id: FieldPath { +public extension ModelPath where ModelType == TagWithCompositeKey { + var id: FieldPath { string("id") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var posts: ModelPath { + var posts: ModelPath { PostTagsWithCompositeKey.Path(name: "posts", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey.swift index 8d8bbf9f26..b913c944db 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct TagWithCompositeKey: Model { public var posts: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1SnapshotTests.swift index 426971f78f..1c75c040a8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1SnapshotTests.swift @@ -5,20 +5,22 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @testable import AWSPluginsCore extension AWSDataStoreLazyLoadProjectTeam1Tests { - + func testProjectSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam1Models()) continueAfterFailure = true - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) // Create let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) let createDocument = """ @@ -48,7 +50,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: project, modelSchema: Project.schema) let updateDocument = """ @@ -78,7 +80,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: project, modelSchema: Project.schema) let deleteDocument = """ @@ -108,7 +110,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -134,7 +136,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -160,7 +162,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -186,7 +188,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Project.self) let syncDocument = """ @@ -217,12 +219,12 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testTeamSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam1Models()) continueAfterFailure = true let team = Team(teamId: UUID().uuidString, name: "name") - + // Create let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) let createDocument = """ @@ -252,7 +254,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: team, modelSchema: Team.schema) let updateDocument = """ @@ -282,7 +284,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: team, modelSchema: Team.schema) let deleteDocument = """ @@ -312,7 +314,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Team.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -336,7 +338,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -360,7 +362,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -384,7 +386,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Team.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1Tests.swift index 0d0929e5f5..cad591c842 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1Tests.swift @@ -5,80 +5,88 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @testable import AWSPluginsCore class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: ProjectTeam1Models()) try await startAndWaitForReady() printDBPath() } - + func testSaveTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) try await assertModelExists(savedTeam) } - + func testSaveProject() async throws { await setup(withModels: ProjectTeam1Models()) - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await createAndWaitForSync(project) try await assertModelExists(savedProject) assertProjectDoesNotContainTeam(savedProject) } - + func testSaveProjectWithTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + // Project initializer variation #1 (pass both team reference and fields in) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - project1TeamTeamId: team.teamId, - project1TeamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + project1TeamTeamId: team.teamId, + project1TeamName: team.name + ) let savedProject = try await createAndWaitForSync(project) let queriedProject = try await query(for: savedProject) assertProject(queriedProject, hasTeam: savedTeam) - + // Project initializer variation #2 (pass only team reference) - let project2 = Project(projectId: UUID().uuidString, - name: "name", - team: team) + let project2 = Project( + projectId: UUID().uuidString, + name: "name", + team: team + ) let savedProject2 = try await createAndWaitForSync(project2) let queriedProject2 = try await query(for: savedProject2) assertProjectDoesNotContainTeam(queriedProject2) - + // Project initializer variation #3 (pass fields in) - let project3 = Project(projectId: UUID().uuidString, - name: "name", - project1TeamTeamId: team.teamId, - project1TeamName: team.name) + let project3 = Project( + projectId: UUID().uuidString, + name: "name", + project1TeamTeamId: team.teamId, + project1TeamName: team.name + ) let savedProject3 = try await createAndWaitForSync(project3) let queriedProject3 = try await query(for: savedProject3) assertProject(queriedProject3, hasTeam: savedTeam) } - + func testSaveProjectWithTeamThenAccessProjectFromTeam() async throws { await setup(withModels: ProjectTeam1Models()) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let projectWithTeam = initializeProjectWithTeam(savedTeam) let savedProjectWithTeam = try await createAndWaitForSync(projectWithTeam) let queriedProjectWithTeam = try await query(for: savedProjectWithTeam) assertProject(queriedProjectWithTeam, hasTeam: savedTeam) - + // For bi-directional has-one belongs-to, we require setting the FK on both sides // Thus, when querying for the team `queriedTeam`, the team does not have the project. var queriedTeam = try await query(for: savedTeam) @@ -87,7 +95,7 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { // Update the team with the project. queriedTeam.setProject(queriedProjectWithTeam) let savedTeamWithProject = try await updateAndWaitForSync(queriedTeam) - + assertLazyReference( savedTeamWithProject._project, state: .notLoaded(identifiers: [ @@ -100,11 +108,11 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { .init(name: Project.keys.projectId.stringValue, value: projectWithTeam.projectId), .init(name: Project.keys.name.stringValue, value: projectWithTeam.name) ])) - + let loadedProject = try await queriedTeamWithProject.project! XCTAssertEqual(loadedProject.projectId, projectWithTeam.projectId) } - + // One-to-One relationships do not create a foreign key for the Team or Project table // So the LazyModel does not have the FK value to be instantiated as metadata for lazy loading. // We only assert the FK fields on the Project exist and are equal to the Team's PK. @@ -112,12 +120,12 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { XCTAssertEqual(project.project1TeamTeamId, team.teamId) XCTAssertEqual(project.project1TeamName, team.name) } - + func assertProjectDoesNotContainTeam(_ project: Project) { XCTAssertNil(project.project1TeamTeamId) XCTAssertNil(project.project1TeamName) } - + func testSaveProjectWithTeamThenUpdate() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -130,13 +138,13 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { let updatedProject = try await updateAndWaitForSync(project) assertProject(updatedProject, hasTeam: savedTeam) } - + func testSaveProjectWithoutTeamUpdateProjectWithTeam() async throws { await setup(withModels: ProjectTeam1Models()) let project = Project(projectId: UUID().uuidString, name: "name") let savedProject = try await createAndWaitForSync(project) assertProjectDoesNotContainTeam(savedProject) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) var queriedProject = try await query(for: savedProject) @@ -145,7 +153,7 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNewTeam = try await updateAndWaitForSync(queriedProject) assertProject(savedProjectWithNewTeam, hasTeam: savedTeam) } - + func testSaveTeamSaveProjectWithTeamUpdateProjectToNoTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -159,7 +167,7 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNoTeam = try await updateAndWaitForSync(queriedProject) assertProjectDoesNotContainTeam(savedProjectWithNoTeam) } - + func testSaveProjectWithTeamUpdateProjectToNewTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -175,7 +183,7 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNewTeam = try await updateAndWaitForSync(queriedProject) assertProject(queriedProject, hasTeam: savedNewTeam) } - + func testDeleteTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -184,7 +192,7 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testDeleteProject() async throws { await setup(withModels: ProjectTeam1Models()) let project = Project(projectId: UUID().uuidString, name: "name") @@ -193,33 +201,33 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedProject) try await assertModelDoesNotExist(savedProject) } - + func testDeleteProjectWithTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) let savedProject = try await createAndWaitForSync(project) - + try await assertModelExists(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedProject) - + try await assertModelDoesNotExist(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testObserveProject() async throws { await setup(withModels: ProjectTeam1Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Project.self) Task { @@ -233,18 +241,18 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveTeam() async throws { await setup(withModels: ProjectTeam1Models()) try await startAndWaitForReady() @@ -257,30 +265,30 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { version == 1, let receivedTeam = try? mutationEvent.decodeModel(as: Team.self), receivedTeam.teamId == team.teamId { - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryProject() async throws { await setup(withModels: ProjectTeam1Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Project.self, where: Project.keys.projectId == project.projectId) Task { @@ -291,18 +299,18 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryTeam() async throws { await setup(withModels: ProjectTeam1Models()) try await startAndWaitForReady() @@ -317,14 +325,14 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -333,7 +341,7 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { extension AWSDataStoreLazyLoadProjectTeam1Tests { typealias Project = Project1 typealias Team = Team1 - + struct ProjectTeam1Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -341,12 +349,14 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { ModelRegistry.register(modelType: Team1.self) } } - + func initializeProjectWithTeam(_ team: Team) -> Project { - return Project(projectId: UUID().uuidString, - name: "name", - team: team, - project1TeamTeamId: team.teamId, - project1TeamName: team.name) + return Project( + projectId: UUID().uuidString, + name: "name", + team: team, + project1TeamTeamId: team.teamId, + project1TeamName: team.name + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1+Schema.swift index cb052507f7..68ffadac0f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project1 { +public extension Project1 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project1 { case project1TeamTeamId case project1TeamName } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let project1 = Project1.keys - + model.pluralName = "Project1s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project1.projectId, project1.name]) ) - + model.fields( .field(project1.projectId, is: .required, ofType: .string), .field(project1.name, is: .required, ofType: .string), @@ -37,9 +44,9 @@ extension Project1 { .field(project1.project1TeamName, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Project1: ModelIdentifiable { @@ -47,32 +54,34 @@ extension Project1: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project1.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project1.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } } -extension ModelPath where ModelType == Project1 { - public var projectId: FieldPath { +public extension ModelPath where ModelType == Project1 { + var projectId: FieldPath { string("projectId") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var team: ModelPath { + var team: ModelPath { Team1.Path(name: "team", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } - public var project1TeamTeamId: FieldPath { + var project1TeamTeamId: FieldPath { string("project1TeamTeamId") } - public var project1TeamName: FieldPath { + var project1TeamName: FieldPath { string("project1TeamName") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1.swift index a36917b1ba..550860a378 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Project1: Model { public let projectId: String public let name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team1? { get async throws { try await _team.get() @@ -15,27 +22,33 @@ public struct Project1: Model { public var updatedAt: Temporal.DateTime? public var project1TeamTeamId: String? public var project1TeamName: String? - - public init(projectId: String, - name: String, - team: Team1? = nil, - project1TeamTeamId: String? = nil, - project1TeamName: String? = nil) { - self.init(projectId: projectId, - name: name, - team: team, - createdAt: nil, - updatedAt: nil, - project1TeamTeamId: project1TeamTeamId, - project1TeamName: project1TeamName) + + public init( + projectId: String, + name: String, + team: Team1? = nil, + project1TeamTeamId: String? = nil, + project1TeamName: String? = nil + ) { + self.init( + projectId: projectId, + name: name, + team: team, + createdAt: nil, + updatedAt: nil, + project1TeamTeamId: project1TeamTeamId, + project1TeamName: project1TeamName + ) } - internal init(projectId: String, - name: String, - team: Team1? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project1TeamTeamId: String? = nil, - project1TeamName: String? = nil) { + init( + projectId: String, + name: String, + team: Team1? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project1TeamTeamId: String? = nil, + project1TeamName: String? = nil + ) { self.projectId = projectId self.name = name self._team = LazyReference(team) @@ -45,17 +58,17 @@ public struct Project1: Model { self.project1TeamName = project1TeamName } public mutating func setTeam(_ team: Team1? = nil) { - self._team = LazyReference(team) + _team = LazyReference(team) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - projectId = try values.decode(String.self, forKey: .projectId) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - project1TeamTeamId = try? values.decode(String?.self, forKey: .project1TeamTeamId) - project1TeamName = try? values.decode(String?.self, forKey: .project1TeamName) + self.projectId = try values.decode(String.self, forKey: .projectId) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.project1TeamTeamId = try? values.decode(String?.self, forKey: .project1TeamTeamId) + self.project1TeamName = try? values.decode(String?.self, forKey: .project1TeamName) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1+Schema.swift index 1ac9b09f53..c29406367b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team1 { +public extension Team1 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case teamId case name case project case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let team1 = Team1.keys - + model.pluralName = "Team1s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team1.teamId, team1.name]) ) - + model.fields( .field(team1.teamId, is: .required, ofType: .string), .field(team1.name, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension Team1 { .field(team1.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team1: ModelIdentifiable { @@ -43,26 +50,28 @@ extension Team1: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team1.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team1.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } } -extension ModelPath where ModelType == Team1 { - public var teamId: FieldPath { +public extension ModelPath where ModelType == Team1 { + var teamId: FieldPath { string("teamId") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var project: ModelPath { + var project: ModelPath { Project1.Path(name: "project", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1.swift index c29c0e2252..8483e5515c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Team1: Model { public let teamId: String public let name: String - internal var _project: LazyReference + var _project: LazyReference public var project: Project1? { get async throws { try await _project.get() @@ -13,21 +20,27 @@ public struct Team1: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String, - project: Project1? = nil) { - self.init(teamId: teamId, - name: name, - project: project, - createdAt: nil, - updatedAt: nil) + + public init( + teamId: String, + name: String, + project: Project1? = nil + ) { + self.init( + teamId: teamId, + name: name, + project: project, + createdAt: nil, + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - project: Project1? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + project: Project1? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self._project = LazyReference(project) @@ -35,15 +48,15 @@ public struct Team1: Model { self.updatedAt = updatedAt } public mutating func setProject(_ project: Project1? = nil) { - self._project = LazyReference(project) + _project = LazyReference(project) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - teamId = try values.decode(String.self, forKey: .teamId) - name = try values.decode(String.self, forKey: .name) - _project = try values.decodeIfPresent(LazyReference.self, forKey: .project) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.teamId = try values.decode(String.self, forKey: .teamId) + self.name = try values.decode(String.self, forKey: .name) + self._project = try values.decodeIfPresent(LazyReference.self, forKey: .project) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2SnapshotTests.swift index bd8e430e0d..8cc1c1d9c3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2SnapshotTests.swift @@ -5,20 +5,22 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadProjectTeam2Tests { - + func testProjectSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam2Models()) continueAfterFailure = true - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) // Create let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) let createDocument = """ @@ -48,7 +50,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: project, modelSchema: Project.schema) let updateDocument = """ @@ -78,7 +80,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: project, modelSchema: Project.schema) let deleteDocument = """ @@ -108,7 +110,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -134,7 +136,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -160,7 +162,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -186,7 +188,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Project.self) let syncDocument = """ @@ -217,12 +219,12 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testTeamSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam2Models()) continueAfterFailure = true let team = Team(teamId: UUID().uuidString, name: "name") - + // Create let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) let createDocument = """ @@ -240,7 +242,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: team, modelSchema: Team.schema) let updateDocument = """ @@ -258,7 +260,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: team, modelSchema: Team.schema) let deleteDocument = """ @@ -276,7 +278,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Team.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -294,7 +296,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -312,7 +314,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -330,7 +332,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Team.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2Tests.swift index 8a2344a0fd..d8e93f132c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2Tests.swift @@ -5,70 +5,78 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: ProjectTeam2Models()) try await startAndWaitForReady() printDBPath() } - + func testSaveTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) try await assertModelExists(savedTeam) } - + func testSaveProject() async throws { await setup(withModels: ProjectTeam2Models()) - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await createAndWaitForSync(project) try await assertModelExists(savedProject) assertProjectDoesNotContainTeam(savedProject) } - + func testSaveProjectWithTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + // Project initializer variation #1 (pass both team reference and fields in) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - project2TeamTeamId: team.teamId, - project2TeamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + project2TeamTeamId: team.teamId, + project2TeamName: team.name + ) let savedProject = try await createAndWaitForSync(project) let queriedProject = try await query(for: savedProject) assertProject(queriedProject, hasTeam: savedTeam) - + // Project initializer variation #2 (pass only team reference) - let project2 = Project(projectId: UUID().uuidString, - name: "name", - team: team) + let project2 = Project( + projectId: UUID().uuidString, + name: "name", + team: team + ) let savedProject2 = try await createAndWaitForSync(project2) let queriedProject2 = try await query(for: savedProject2) assertProjectDoesNotContainTeam(queriedProject2) - + // Project initializer variation #3 (pass fields in) - let project3 = Project(projectId: UUID().uuidString, - name: "name", - project2TeamTeamId: team.teamId, - project2TeamName: team.name) + let project3 = Project( + projectId: UUID().uuidString, + name: "name", + project2TeamTeamId: team.teamId, + project2TeamName: team.name + ) let savedProject3 = try await createAndWaitForSync(project3) let queriedProject3 = try await query(for: savedProject3) assertProject(queriedProject3, hasTeam: savedTeam) } - + // One-to-One relationships do not create a foreign key for the Team or Project table // So the LazyModel does not have the FK value to be instantiated as metadata for lazy loading. // We only assert the FK fields on the Project exist and are equal to the Team's PK. @@ -76,17 +84,17 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { XCTAssertEqual(project.project2TeamTeamId, team.teamId) XCTAssertEqual(project.project2TeamName, team.name) } - + func assertProjectDoesNotContainTeam(_ project: Project) { XCTAssertNil(project.project2TeamTeamId) XCTAssertNil(project.project2TeamName) } - + func testSaveProjectWithTeamThenUpdate() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + let project = initializeProjectWithTeam(team) let savedProject = try await createAndWaitForSync(project) assertProject(savedProject, hasTeam: savedTeam) @@ -95,13 +103,13 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { let updatedProject = try await updateAndWaitForSync(project) assertProject(updatedProject, hasTeam: savedTeam) } - + func testSaveProjectWithoutTeamUpdateProjectWithTeam() async throws { await setup(withModels: ProjectTeam2Models()) let project = Project(projectId: UUID().uuidString, name: "name") let savedProject = try await createAndWaitForSync(project) assertProjectDoesNotContainTeam(savedProject) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) var queriedProject = try await query(for: savedProject) @@ -110,7 +118,7 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNewTeam = try await updateAndWaitForSync(queriedProject) assertProject(savedProjectWithNewTeam, hasTeam: savedTeam) } - + func testSaveTeamSaveProjectWithTeamUpdateProjectToNoTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -124,7 +132,7 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNoTeam = try await updateAndWaitForSync(queriedProject) assertProjectDoesNotContainTeam(savedProjectWithNoTeam) } - + func testSaveProjectWithTeamUpdateProjectToNewTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -142,7 +150,7 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { let queriedProjectV2 = try await query(for: savedProject) assertProject(queriedProjectV2, hasTeam: savedNewTeam) } - + func testDeleteTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -151,7 +159,7 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testDeleteProject() async throws { await setup(withModels: ProjectTeam2Models()) let project = Project(projectId: UUID().uuidString, name: "name") @@ -160,33 +168,33 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedProject) try await assertModelDoesNotExist(savedProject) } - + func testDeleteProjectWithTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) let savedProject = try await createAndWaitForSync(project) - + try await assertModelExists(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedProject) - + try await assertModelDoesNotExist(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testObserveProject() async throws { await setup(withModels: ProjectTeam2Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Project.self) Task { @@ -200,18 +208,18 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveTeam() async throws { await setup(withModels: ProjectTeam2Models()) try await startAndWaitForReady() @@ -224,30 +232,30 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { version == 1, let receivedTeam = try? mutationEvent.decodeModel(as: Team.self), receivedTeam.teamId == team.teamId { - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryProject() async throws { await setup(withModels: ProjectTeam2Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Project.self, where: Project.keys.projectId == project.projectId) Task { @@ -258,18 +266,18 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryTeam() async throws { await setup(withModels: ProjectTeam2Models()) try await startAndWaitForReady() @@ -284,24 +292,24 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } } extension AWSDataStoreLazyLoadProjectTeam2Tests { - + typealias Project = Project2 typealias Team = Team2 - + struct ProjectTeam2Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -309,12 +317,14 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { ModelRegistry.register(modelType: Team2.self) } } - + func initializeProjectWithTeam(_ team: Team) -> Project { - return Project(projectId: UUID().uuidString, - name: "name", - team: team, - project2TeamTeamId: team.teamId, - project2TeamName: team.name) + return Project( + projectId: UUID().uuidString, + name: "name", + team: team, + project2TeamTeamId: team.teamId, + project2TeamName: team.name + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2+Schema.swift index 79361d58a5..4d90db0806 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project2 { +public extension Project2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -14,10 +21,10 @@ extension Project2 { case project2TeamName } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project2 = Project2.keys model.pluralName = "Project2s" @@ -37,10 +44,10 @@ extension Project2 { .field(project2.project2TeamName, is: .optional, ofType: .string) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Project2: ModelIdentifiable { @@ -48,10 +55,12 @@ extension Project2: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project2.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project2.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2.swift index 2e05879e89..d35250d7ab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Project2: Model { public let projectId: String public let name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team2? { get async throws { try await _team.get() @@ -16,26 +23,32 @@ public struct Project2: Model { public var project2TeamTeamId: String? public var project2TeamName: String? - public init(projectId: String, - name: String, - team: Team2? = nil, - project2TeamTeamId: String? = nil, - project2TeamName: String? = nil) { - self.init(projectId: projectId, - name: name, - team: team, - createdAt: nil, - updatedAt: nil, - project2TeamTeamId: project2TeamTeamId, - project2TeamName: project2TeamName) + public init( + projectId: String, + name: String, + team: Team2? = nil, + project2TeamTeamId: String? = nil, + project2TeamName: String? = nil + ) { + self.init( + projectId: projectId, + name: name, + team: team, + createdAt: nil, + updatedAt: nil, + project2TeamTeamId: project2TeamTeamId, + project2TeamName: project2TeamName + ) } - internal init(projectId: String, - name: String, - team: Team2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project2TeamTeamId: String? = nil, - project2TeamName: String? = nil) { + init( + projectId: String, + name: String, + team: Team2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project2TeamTeamId: String? = nil, + project2TeamName: String? = nil + ) { self.projectId = projectId self.name = name self._team = LazyReference(team) @@ -46,18 +59,18 @@ public struct Project2: Model { } public mutating func setTeam(_ team: Team2?) { - self._team = LazyReference(team) + _team = LazyReference(team) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - projectId = try values.decode(String.self, forKey: .projectId) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - project2TeamTeamId = try values.decode(String?.self, forKey: .project2TeamTeamId) - project2TeamName = try values.decode(String?.self, forKey: .project2TeamName) + self.projectId = try values.decode(String.self, forKey: .projectId) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.project2TeamTeamId = try values.decode(String?.self, forKey: .project2TeamTeamId) + self.project2TeamName = try values.decode(String?.self, forKey: .project2TeamName) } public func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2+Schema.swift index 58ae64d03a..bcb5656050 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case teamId case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team2 = Team2.keys - + model.pluralName = "Team2s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team2.teamId, team2.name]) ) - + model.fields( .field(team2.teamId, is: .required, ofType: .string), .field(team2.name, is: .required, ofType: .string), @@ -31,10 +38,10 @@ extension Team2 { .field(team2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team2: ModelIdentifiable { @@ -42,10 +49,12 @@ extension Team2: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team2.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team2.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2.swift index 90d68caa79..f58e821d6e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Team2: Model { public let name: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String) { - self.init(teamId: teamId, + + public init( + teamId: String, + name: String + ) { + self.init( + teamId: teamId, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4SnapshotTests.swift index 35fbad0e66..0eca4c64ce 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4SnapshotTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPostComment4Tests { - + func testPostSelectionSets() { setUpModelRegistrationOnly(withModels: PostComment4Models()) continueAfterFailure = true @@ -35,7 +35,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: post, modelSchema: Post.schema) let updateDocument = """ @@ -53,7 +53,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: post, modelSchema: Post.schema) let deleteDocument = """ @@ -71,7 +71,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -89,7 +89,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -107,7 +107,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -125,7 +125,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -148,16 +148,18 @@ extension AWSDataStoreLazyLoadPostComment4Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testCommentSelectionSets() { setUpModelRegistrationOnly(withModels: PostComment4Models()) continueAfterFailure = true let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) - + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) + // Create let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) let createDocument = """ @@ -177,7 +179,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: comment, modelSchema: Comment.schema) let updateDocument = """ @@ -197,7 +199,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: comment, modelSchema: Comment.schema) let deleteDocument = """ @@ -217,7 +219,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Comment.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -237,7 +239,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -257,7 +259,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -277,7 +279,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Comment.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4Tests.swift index 3a56f66da5..ec5123e7a7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4Tests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest { @@ -19,31 +19,35 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) } - + func testSaveComment() async throws { await setup(withModels: PostComment4Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) } - + func testLazyLoad() async throws { await setup(withModels: PostComment4Models()) let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) assertComment(savedComment, contains: savedPost) try await assertPost(savedPost, canLazyLoad: savedComment) - + // Assert on Queried Comment let queriedComment = try await query(for: savedComment) assertComment(queriedComment, contains: savedPost) @@ -52,25 +56,29 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest let queriedPost = try await query(for: savedPost) try await assertPost(queriedPost, canLazyLoad: savedComment) } - + func assertComment(_ comment: Comment, contains post: Post) { XCTAssertEqual(comment.post4CommentsPostId, post.postId) XCTAssertEqual(comment.post4CommentsTitle, post.title) } - + func assertCommentDoesNotContainPost(_ comment: Comment) { XCTAssertNil(comment.post4CommentsPostId) XCTAssertNil(comment.post4CommentsTitle) } - - func assertPost(_ post: Post, - canLazyLoad comment: Comment) async throws { + + func assertPost( + _ post: Post, + canLazyLoad comment: Comment + ) async throws { guard let comments = post.comments else { XCTFail("Missing comments on post") return } - assertList(comments, state: .isNotLoaded(associatedIds: [post.postId, post.title], - associatedFields: ["post4CommentsPostId", "post4CommentsTitle"])) + assertList(comments, state: .isNotLoaded( + associatedIds: [post.postId, post.title], + associatedFields: ["post4CommentsPostId", "post4CommentsTitle"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) guard let comment = comments.first else { @@ -79,7 +87,7 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest } assertComment(comment, contains: post) } - + func testSaveWithoutPost() async throws { await setup(withModels: PostComment4Models()) let comment = Comment(commentId: UUID().uuidString, content: "content") @@ -94,14 +102,16 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: saveCommentWithPost) assertComment(queriedComment2, contains: post) } - + func testUpdateFromQueriedComment() async throws { await setup(withModels: PostComment4Models()) let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) let queriedComment = try await query(for: savedComment) @@ -110,15 +120,17 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: savedQueriedComment) assertComment(queriedComment2, contains: savedPost) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostComment4Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) @@ -131,55 +143,61 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: saveCommentWithNewPost) assertComment(queriedComment2, contains: newPost) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostComment4Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) assertComment(queriedComment, contains: post) - + queriedComment.post4CommentsPostId = nil queriedComment.post4CommentsTitle = nil - + let saveCommentRemovePost = try await updateAndWaitForSync(queriedComment) let queriedCommentNoPost = try await query(for: saveCommentRemovePost) assertCommentDoesNotContainPost(queriedCommentNoPost) } - + func testDelete() async throws { await setup(withModels: PostComment4Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) try await deleteAndWaitForSync(savedPost) - + // The expected behavior when deleting a post should be that the // child models are deleted (comment) followed by the parent model (post). try await assertModelDoesNotExist(savedPost) // Is there a way to delete the children models in uni directional relationships? try await assertModelExists(savedComment) } - + func testObservePost() async throws { await setup(withModels: PostComment4Models()) try await startAndWaitForReady() let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Post.self) Task { @@ -194,27 +212,29 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveComment() async throws { await setup(withModels: PostComment4Models()) try await startAndWaitForReady() let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Comment.self) Task { @@ -228,26 +248,28 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: PostComment4Models()) try await startAndWaitForReady() let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Post.self, where: Post.keys.postId == post.postId) Task { @@ -259,28 +281,30 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryComment() async throws { await setup(withModels: PostComment4Models()) try await startAndWaitForReady() - + let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Comment.self, where: Comment.keys.commentId == comment.commentId) Task { @@ -291,14 +315,14 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -307,7 +331,7 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest extension AWSDataStoreLazyLoadPostComment4Tests { typealias Post = Post4 typealias Comment = Comment4 - + struct PostComment4Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4+Schema.swift index fb694e6cf4..358ed06707 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment4 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment4 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case commentId case content case createdAt @@ -12,20 +19,20 @@ extension Comment4 { case post4CommentsPostId case post4CommentsTitle } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment4 = Comment4.keys - + model.pluralName = "Comment4s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .primaryKey(fields: [comment4.commentId, comment4.content]) ) - + model.fields( .field(comment4.commentId, is: .required, ofType: .string), .field(comment4.content, is: .required, ofType: .string), @@ -35,9 +42,9 @@ extension Comment4 { .field(comment4.post4CommentsTitle, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment4: ModelIdentifiable { @@ -45,10 +52,12 @@ extension Comment4: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment4.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment4.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } } @@ -59,5 +68,5 @@ extension ModelPath where ModelType == Comment4 { var updatedAt: FieldPath { datetime("updatedAt") } var post4CommentsPostId: FieldPath { string("post4CommentsPostId") } var post4CommentsTitle: FieldPath { string("post4CommentsTitle") } - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4.swift index bf249d1211..593b1efc60 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Comment4: Model { public var updatedAt: Temporal.DateTime? public var post4CommentsPostId: String? public var post4CommentsTitle: String? - - public init(commentId: String, - content: String, - post4CommentsPostId: String? = nil, - post4CommentsTitle: String? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + post4CommentsPostId: String? = nil, + post4CommentsTitle: String? = nil + ) { + self.init( + commentId: commentId, content: content, createdAt: nil, updatedAt: nil, post4CommentsPostId: post4CommentsPostId, - post4CommentsTitle: post4CommentsTitle) + post4CommentsTitle: post4CommentsTitle + ) } - internal init(commentId: String, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - post4CommentsPostId: String? = nil, - post4CommentsTitle: String? = nil) { + init( + commentId: String, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + post4CommentsPostId: String? = nil, + post4CommentsTitle: String? = nil + ) { self.commentId = commentId self.content = content self.createdAt = createdAt @@ -34,4 +47,4 @@ public struct Comment4: Model { self.post4CommentsPostId = post4CommentsPostId self.post4CommentsTitle = post4CommentsTitle } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4+Schema.swift index 29a8d55288..1f104c79fe 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post4 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post4 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post4 = Post4.keys - + model.pluralName = "Post4s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post4.postId, post4.title]) ) - + model.fields( .field(post4.postId, is: .required, ofType: .string), .field(post4.title, is: .required, ofType: .string), @@ -33,10 +40,10 @@ extension Post4 { .field(post4.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post4: ModelIdentifiable { @@ -44,10 +51,12 @@ extension Post4: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post4.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post4.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4.swift index a50849704b..1d08640c37 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post4: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5SnapshotTests.swift index 4f49eda389..13736975dc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5SnapshotTests.swift @@ -5,20 +5,22 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadProjectTeam5Tests { - + func testProjectSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam5Models()) continueAfterFailure = true - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) // Create let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) let createDocument = """ @@ -48,7 +50,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: project, modelSchema: Project.schema) let updateDocument = """ @@ -78,7 +80,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: project, modelSchema: Project.schema) let deleteDocument = """ @@ -108,7 +110,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -134,7 +136,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -160,7 +162,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -186,7 +188,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Project.self) let syncDocument = """ @@ -217,12 +219,12 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testTeamSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam5Models()) continueAfterFailure = true let team = Team(teamId: UUID().uuidString, name: "name") - + // Create let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) let createDocument = """ @@ -252,7 +254,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: team, modelSchema: Team.schema) let updateDocument = """ @@ -282,7 +284,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: team, modelSchema: Team.schema) let deleteDocument = """ @@ -312,7 +314,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Team.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -336,7 +338,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -360,7 +362,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -384,7 +386,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Team.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5Tests.swift index ade3115dac..ec1c113f3f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5Tests.swift @@ -5,70 +5,78 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: ProjectTeam5Models()) try await startAndWaitForReady() printDBPath() } - + func testSaveTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) try await assertModelExists(savedTeam) } - + func testSaveProject() async throws { await setup(withModels: ProjectTeam5Models()) - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await createAndWaitForSync(project) try await assertModelExists(savedProject) assertProjectDoesNotContainTeam(savedProject) } - + func testSaveProjectWithTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + // Project initializer variation #1 (pass both team reference and fields in) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) let savedProject = try await createAndWaitForSync(project) let queriedProject = try await query(for: savedProject) assertProject(queriedProject, hasTeam: savedTeam) - + // Project initializer variation #2 (pass only team reference) - let project2 = Project(projectId: UUID().uuidString, - name: "name", - team: team) + let project2 = Project( + projectId: UUID().uuidString, + name: "name", + team: team + ) let savedProject2 = try await createAndWaitForSync(project2) let queriedProject2 = try await query(for: savedProject2) assertProjectDoesNotContainTeam(queriedProject2) - + // Project initializer variation #3 (pass fields in) - let project3 = Project(projectId: UUID().uuidString, - name: "name", - teamId: team.teamId, - teamName: team.name) + let project3 = Project( + projectId: UUID().uuidString, + name: "name", + teamId: team.teamId, + teamName: team.name + ) let savedProject3 = try await createAndWaitForSync(project3) let queriedProject3 = try await query(for: savedProject3) assertProject(queriedProject3, hasTeam: savedTeam) } - + // One-to-One relationships do not create a foreign key for the Team or Project table // So the LazyModel does not have the FK value to be instantiated as metadata for lazy loading. // We only assert the FK fields on the Project exist and are equal to the Team's PK. @@ -76,17 +84,17 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { XCTAssertEqual(project.teamId, team.teamId) XCTAssertEqual(project.teamName, team.name) } - + func assertProjectDoesNotContainTeam(_ project: Project) { XCTAssertNil(project.teamId) XCTAssertNil(project.teamName) } - + func testSaveProjectWithTeamThenUpdate() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + let project = initializeProjectWithTeam(team) let savedProject = try await createAndWaitForSync(project) assertProject(savedProject, hasTeam: savedTeam) @@ -95,13 +103,13 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { let updatedProject = try await updateAndWaitForSync(project) assertProject(updatedProject, hasTeam: savedTeam) } - + func testSaveProjectWithoutTeamUpdateProjectWithTeam() async throws { await setup(withModels: ProjectTeam5Models()) let project = Project(projectId: UUID().uuidString, name: "name") let savedProject = try await createAndWaitForSync(project) assertProjectDoesNotContainTeam(savedProject) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) var queriedProject = try await query(for: savedProject) @@ -110,7 +118,7 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNewTeam = try await updateAndWaitForSync(queriedProject) assertProject(savedProjectWithNewTeam, hasTeam: savedTeam) } - + func testSaveTeamSaveProjectWithTeamUpdateProjectToNoTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -124,7 +132,7 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNoTeam = try await updateAndWaitForSync(queriedProject) assertProjectDoesNotContainTeam(savedProjectWithNoTeam) } - + func testSaveProjectWithTeamUpdateProjectToNewTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -141,7 +149,7 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { _ = savedProjectWithNewTeam assertProject(queriedProject, hasTeam: savedNewTeam) } - + func testDeleteTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -150,7 +158,7 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testDeleteProject() async throws { await setup(withModels: ProjectTeam5Models()) let project = Project(projectId: UUID().uuidString, name: "name") @@ -159,37 +167,39 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedProject) try await assertModelDoesNotExist(savedProject) } - + func testDeleteProjectWithTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) let savedProject = try await createAndWaitForSync(project) - + try await assertModelExists(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedProject) - + try await assertModelDoesNotExist(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testObserveProject() async throws { await setup(withModels: ProjectTeam5Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Project.self) Task { @@ -203,18 +213,18 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveTeam() async throws { await setup(withModels: ProjectTeam5Models()) try await startAndWaitForReady() @@ -227,30 +237,30 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { version == 1, let receivedTeam = try? mutationEvent.decodeModel(as: Team.self), receivedTeam.teamId == team.teamId { - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryProject() async throws { await setup(withModels: ProjectTeam5Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Project.self, where: Project.keys.projectId == project.projectId) Task { @@ -261,18 +271,18 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryTeam() async throws { await setup(withModels: ProjectTeam5Models()) try await startAndWaitForReady() @@ -287,24 +297,24 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } } extension AWSDataStoreLazyLoadProjectTeam5Tests { - + typealias Project = Project5 typealias Team = Team5 - + struct ProjectTeam5Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -312,12 +322,14 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { ModelRegistry.register(modelType: Team5.self) } } - + func initializeProjectWithTeam(_ team: Team) -> Project { - return Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + return Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5+Schema.swift index c3b1a54883..d905b055ea 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project5 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Project5 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project5 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let project5 = Project5.keys - + model.pluralName = "Project5s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project5.projectId, project5.name]) ) - + model.fields( .field(project5.projectId, is: .required, ofType: .string), .field(project5.name, is: .required, ofType: .string), @@ -37,10 +44,10 @@ extension Project5 { .field(project5.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Project5: ModelIdentifiable { @@ -48,10 +55,12 @@ extension Project5: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project5.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project5.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5.swift index 3f72dfb0f0..60bec5a586 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Project5: Model { public let projectId: String public let name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team5? { get async throws { try await _team.get() @@ -15,27 +22,33 @@ public struct Project5: Model { public var teamName: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(projectId: String, - name: String, - team: Team5? = nil, - teamId: String? = nil, - teamName: String? = nil) { - self.init(projectId: projectId, - name: name, - team: team, - teamId: teamId, - teamName: teamName, - createdAt: nil, - updatedAt: nil) + + public init( + projectId: String, + name: String, + team: Team5? = nil, + teamId: String? = nil, + teamName: String? = nil + ) { + self.init( + projectId: projectId, + name: name, + team: team, + teamId: teamId, + teamName: teamName, + createdAt: nil, + updatedAt: nil + ) } - internal init(projectId: String, - name: String, - team: Team5? = nil, - teamId: String? = nil, - teamName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + projectId: String, + name: String, + team: Team5? = nil, + teamId: String? = nil, + teamName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.projectId = projectId self.name = name self._team = LazyReference(team) @@ -44,22 +57,22 @@ public struct Project5: Model { self.createdAt = createdAt self.updatedAt = updatedAt } - + public mutating func setTeam(_ team: Team5) { - self._team = LazyReference(team) + _team = LazyReference(team) } - + public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - projectId = try values.decode(String.self, forKey: .projectId) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - teamId = try values.decode(String?.self, forKey: .teamId) - teamName = try values.decode(String?.self, forKey: .teamName) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.projectId = try values.decode(String.self, forKey: .projectId) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.teamId = try values.decode(String?.self, forKey: .teamId) + self.teamName = try values.decode(String?.self, forKey: .teamName) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } - + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(projectId, forKey: .projectId) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5+Schema.swift index e27f517b2c..b80f7f952b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team5 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team5 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case teamId case name case project case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team5 = Team5.keys - + model.pluralName = "Team5s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team5.teamId, team5.name]) ) - + model.fields( .field(team5.teamId, is: .required, ofType: .string), .field(team5.name, is: .required, ofType: .string), @@ -33,10 +40,10 @@ extension Team5 { .field(team5.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team5: ModelIdentifiable { @@ -44,10 +51,12 @@ extension Team5: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team5.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team5.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5.swift index c3c868ed8a..d72b177b7c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Team5: Model { public let teamId: String public let name: String - internal var _project: LazyReference + var _project: LazyReference public var project: Project5? { get async throws { try await _project.get() @@ -13,37 +20,43 @@ public struct Team5: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String, - project: Project5? = nil) { - self.init(teamId: teamId, - name: name, - project: project, - createdAt: nil, - updatedAt: nil) + + public init( + teamId: String, + name: String, + project: Project5? = nil + ) { + self.init( + teamId: teamId, + name: name, + project: project, + createdAt: nil, + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - project: Project5? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + project: Project5? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self._project = LazyReference(project) self.createdAt = createdAt self.updatedAt = updatedAt } - + public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - teamId = try values.decode(String.self, forKey: .teamId) - name = try values.decode(String.self, forKey: .name) - _project = try values.decodeIfPresent(LazyReference.self, forKey: .project) ?? LazyReference(identifiers: nil) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.teamId = try values.decode(String.self, forKey: .teamId) + self.name = try values.decode(String.self, forKey: .name) + self._project = try values.decodeIfPresent(LazyReference.self, forKey: .project) ?? LazyReference(identifiers: nil) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } - + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(teamId, forKey: .teamId) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6SnapshotTests.swift index 923ac67866..e2bc3cbb4b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6SnapshotTests.swift @@ -5,20 +5,22 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadProjectTeam6Tests { - + func testProjectSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam6Models()) continueAfterFailure = true - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) // Create let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) let createDocument = """ @@ -48,7 +50,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: project, modelSchema: Project.schema) let updateDocument = """ @@ -78,7 +80,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: project, modelSchema: Project.schema) let deleteDocument = """ @@ -108,7 +110,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -134,7 +136,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -160,7 +162,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -186,7 +188,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Project.self) let syncDocument = """ @@ -217,12 +219,12 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testTeamSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam6Models()) continueAfterFailure = true let team = Team(teamId: UUID().uuidString, name: "name") - + // Create let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) let createDocument = """ @@ -240,7 +242,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: team, modelSchema: Team.schema) let updateDocument = """ @@ -258,7 +260,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: team, modelSchema: Team.schema) let deleteDocument = """ @@ -276,7 +278,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Team.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -294,7 +296,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -312,7 +314,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -330,7 +332,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Team.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6Tests.swift index 574f2c9d55..aeee6facfa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6Tests.swift @@ -5,70 +5,78 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: ProjectTeam6Models()) try await startAndWaitForReady() printDBPath() } - + func testSaveTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) try await assertModelExists(savedTeam) } - + func testSaveProject() async throws { await setup(withModels: ProjectTeam6Models()) - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await createAndWaitForSync(project) try await assertModelExists(savedProject) assertProjectDoesNotContainTeam(savedProject) } - + func testSaveProjectWithTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + // Project initializer variation #1 (pass both team reference and fields in) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) let savedProject = try await createAndWaitForSync(project) let queriedProject = try await query(for: savedProject) assertProject(queriedProject, hasTeam: savedTeam) - + // Project initializer variation #2 (pass only team reference) - let project2 = Project(projectId: UUID().uuidString, - name: "name", - team: team) + let project2 = Project( + projectId: UUID().uuidString, + name: "name", + team: team + ) let savedProject2 = try await createAndWaitForSync(project2) let queriedProject2 = try await query(for: savedProject2) assertProjectDoesNotContainTeam(queriedProject2) - + // Project initializer variation #3 (pass fields in) - let project3 = Project(projectId: UUID().uuidString, - name: "name", - teamId: team.teamId, - teamName: team.name) + let project3 = Project( + projectId: UUID().uuidString, + name: "name", + teamId: team.teamId, + teamName: team.name + ) let savedProject3 = try await createAndWaitForSync(project3) let queriedProject3 = try await query(for: savedProject3) assertProject(queriedProject3, hasTeam: savedTeam) } - + // One-to-One relationships do not create a foreign key for the Team or Project table // So the LazyModel does not have the FK value to be instantiated as metadata for lazy loading. // We only assert the FK fields on the Project exist and are equal to the Team's PK. @@ -76,17 +84,17 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { XCTAssertEqual(project.teamId, team.teamId) XCTAssertEqual(project.teamName, team.name) } - + func assertProjectDoesNotContainTeam(_ project: Project) { XCTAssertNil(project.teamId) XCTAssertNil(project.teamName) } - + func testSaveProjectWithTeamThenUpdate() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + let project = initializeProjectWithTeam(team) let savedProject = try await createAndWaitForSync(project) assertProject(savedProject, hasTeam: savedTeam) @@ -95,13 +103,13 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { let updatedProject = try await updateAndWaitForSync(project) assertProject(updatedProject, hasTeam: savedTeam) } - + func testSaveProjectWithoutTeamUpdateProjectWithTeam() async throws { await setup(withModels: ProjectTeam6Models()) let project = Project(projectId: UUID().uuidString, name: "name") let savedProject = try await createAndWaitForSync(project) assertProjectDoesNotContainTeam(savedProject) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) var queriedProject = try await query(for: savedProject) @@ -110,7 +118,7 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNewTeam = try await updateAndWaitForSync(queriedProject) assertProject(savedProjectWithNewTeam, hasTeam: savedTeam) } - + func testSaveTeamSaveProjectWithTeamUpdateProjectToNoTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -124,7 +132,7 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNoTeam = try await updateAndWaitForSync(queriedProject) assertProjectDoesNotContainTeam(savedProjectWithNoTeam) } - + func testSaveProjectWithTeamUpdateProjectToNewTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -140,7 +148,7 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNewTeam = try await updateAndWaitForSync(queriedProject) assertProject(queriedProject, hasTeam: savedNewTeam) } - + func testDeleteTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -149,7 +157,7 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testDeleteProject() async throws { await setup(withModels: ProjectTeam6Models()) let project = Project(projectId: UUID().uuidString, name: "name") @@ -158,33 +166,33 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedProject) try await assertModelDoesNotExist(savedProject) } - + func testDeleteProjectWithTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) let savedProject = try await createAndWaitForSync(project) - + try await assertModelExists(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedProject) - + try await assertModelDoesNotExist(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testObserveProject() async throws { await setup(withModels: ProjectTeam6Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Project.self) Task { @@ -198,18 +206,18 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveTeam() async throws { await setup(withModels: ProjectTeam6Models()) try await startAndWaitForReady() @@ -226,25 +234,25 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryProject() async throws { await setup(withModels: ProjectTeam6Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Project.self, where: Project.keys.projectId == project.projectId) Task { @@ -255,18 +263,18 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryTeam() async throws { await setup(withModels: ProjectTeam6Models()) try await startAndWaitForReady() @@ -281,24 +289,24 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } } extension AWSDataStoreLazyLoadProjectTeam6Tests { - + typealias Project = Project6 typealias Team = Team6 - + struct ProjectTeam6Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -306,12 +314,14 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { ModelRegistry.register(modelType: Team6.self) } } - + func initializeProjectWithTeam(_ team: Team) -> Project { - return Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + return Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6+Schema.swift index 380eecaa91..d87b3977f2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project6 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Project6 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project6 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let project6 = Project6.keys - + model.pluralName = "Project6s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project6.projectId, project6.name]) ) - + model.fields( .field(project6.projectId, is: .required, ofType: .string), .field(project6.name, is: .required, ofType: .string), @@ -37,10 +44,10 @@ extension Project6 { .field(project6.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Project6: ModelIdentifiable { @@ -48,10 +55,12 @@ extension Project6: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project6.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project6.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6.swift index 797d5f3ec3..c8a0ee3112 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Project6: Model { public let projectId: String public let name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team6? { get async throws { try await _team.get() @@ -15,27 +22,33 @@ public struct Project6: Model { public var teamName: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(projectId: String, - name: String, - team: Team6? = nil, - teamId: String? = nil, - teamName: String? = nil) { - self.init(projectId: projectId, - name: name, - team: team, - teamId: teamId, - teamName: teamName, - createdAt: nil, - updatedAt: nil) + + public init( + projectId: String, + name: String, + team: Team6? = nil, + teamId: String? = nil, + teamName: String? = nil + ) { + self.init( + projectId: projectId, + name: name, + team: team, + teamId: teamId, + teamName: teamName, + createdAt: nil, + updatedAt: nil + ) } - internal init(projectId: String, - name: String, - team: Team6? = nil, - teamId: String? = nil, - teamName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + projectId: String, + name: String, + team: Team6? = nil, + teamId: String? = nil, + teamName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.projectId = projectId self.name = name self._team = LazyReference(team) @@ -44,22 +57,22 @@ public struct Project6: Model { self.createdAt = createdAt self.updatedAt = updatedAt } - + public mutating func setTeam(_ team: Team6?) { - self._team = LazyReference(team) + _team = LazyReference(team) } - + public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - projectId = try values.decode(String.self, forKey: .projectId) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - teamId = try values.decode(String?.self, forKey: .teamId) - teamName = try values.decode(String?.self, forKey: .teamName) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.projectId = try values.decode(String.self, forKey: .projectId) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.teamId = try values.decode(String?.self, forKey: .teamId) + self.teamName = try values.decode(String?.self, forKey: .teamName) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } - + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(projectId, forKey: .projectId) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6+Schema.swift index 477021cd02..4e8fcda622 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team6 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team6 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case teamId case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team6 = Team6.keys - + model.pluralName = "Team6s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team6.teamId, team6.name]) ) - + model.fields( .field(team6.teamId, is: .required, ofType: .string), .field(team6.name, is: .required, ofType: .string), @@ -31,10 +38,10 @@ extension Team6 { .field(team6.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team6: ModelIdentifiable { @@ -42,10 +49,12 @@ extension Team6: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team6.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team6.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6.swift index 88da92235b..3a45fc3f04 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Team6: Model { public let name: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String) { - self.init(teamId: teamId, + + public init( + teamId: String, + name: String + ) { + self.init( + teamId: teamId, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AWSDataStoreLazyLoadBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AWSDataStoreLazyLoadBaseTest.swift index 7d8fa69431..08c9f517e4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AWSDataStoreLazyLoadBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AWSDataStoreLazyLoadBaseTest.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSAPIPlugin +import AWSPluginsCore +import Combine import Foundation import XCTest -import Combine @testable import AWSDataStorePlugin -import AWSPluginsCore -import AWSAPIPlugin #if !os(watchOS) @testable import DataStoreHostApp @@ -19,15 +19,15 @@ import AWSAPIPlugin class AWSDataStoreLazyLoadBaseTest: XCTestCase { var amplifyConfig: AmplifyConfiguration! - + var apiOnly: Bool = false var modelsOnly: Bool = false var clearOnTearDown: Bool = false - + override func setUp() { continueAfterFailure = false } - + override func tearDown() async throws { if !(apiOnly || modelsOnly) { try await clearDataStore() @@ -35,19 +35,19 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { await Amplify.reset() try await Task.sleep(seconds: 1) } - + func setupConfig() { let basePath = "testconfiguration" let baseFileName = "AWSDataStoreCategoryPluginLazyLoadIntegrationTests" let configFile = "\(basePath)/\(baseFileName)-amplifyconfiguration" - + do { amplifyConfig = try TestConfigHelper.retrieveAmplifyConfiguration(forResource: configFile) } catch { XCTFail("Error during setup: \(error)") } } - + func apiEndpointName() throws -> String { guard let apiPlugin = amplifyConfig.api?.plugins["awsAPIPlugin"], case .object(let value) = apiPlugin else { @@ -55,68 +55,78 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { } return value.keys.first! } - + /// Setup DataStore with given models /// - Parameter models: DataStore models - func setup(withModels models: AmplifyModelRegistration, - logLevel: LogLevel = .verbose, - clearOnTearDown: Bool = false) async { + func setup( + withModels models: AmplifyModelRegistration, + logLevel: LogLevel = .verbose, + clearOnTearDown: Bool = false + ) async { self.clearOnTearDown = clearOnTearDown do { setupConfig() Amplify.Logging.logLevel = logLevel - + #if os(watchOS) try Amplify.add(plugin: AWSDataStorePlugin( modelRegistration: models, configuration: .custom( errorHandler: { error in Amplify.Logging.error("DataStore ErrorHandler error: \(error)")}, syncMaxRecords: 100, - disableSubscriptions: { false }))) + disableSubscriptions: { false } + ) + )) #else try Amplify.add(plugin: AWSDataStorePlugin( modelRegistration: models, configuration: .custom( errorHandler: { error in Amplify.Logging.error("DataStore ErrorHandler error: \(error)")}, - syncMaxRecords: 100))) + syncMaxRecords: 100 + ) + )) #endif try Amplify.add(plugin: AWSAPIPlugin(sessionFactory: AmplifyURLSessionFactory())) try Amplify.configure(amplifyConfig) - + try await Amplify.DataStore.start() } catch { XCTFail("Error during setup: \(error)") } } - - func setUpDataStoreOnly(withModels models: AmplifyModelRegistration, - logLevel: LogLevel = .verbose, - clearOnTearDown: Bool = false) async { + + func setUpDataStoreOnly( + withModels models: AmplifyModelRegistration, + logLevel: LogLevel = .verbose, + clearOnTearDown: Bool = false + ) async { self.clearOnTearDown = clearOnTearDown do { setupConfig() Amplify.Logging.logLevel = logLevel - + #if os(watchOS) try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, configuration: .subscriptionsDisabled)) #else try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models)) #endif - + try Amplify.configure(amplifyConfig) - + try await deleteMutationEvents() } catch { XCTFail("Error during setup: \(error)") } } - - func setUpModelRegistrationOnly(withModels models: AmplifyModelRegistration, - logLevel: LogLevel = .verbose) { + + func setUpModelRegistrationOnly( + withModels models: AmplifyModelRegistration, + logLevel: LogLevel = .verbose + ) { modelsOnly = true models.registerModels(registry: ModelRegistry.self) } - + func setupAPIOnly(withModels models: AmplifyModelRegistration, logLevel: LogLevel = .verbose) async { apiOnly = true do { @@ -128,15 +138,15 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { XCTFail("Error during setup: \(error)") } } - + func deleteMutationEvents() async throws { try await Amplify.DataStore.delete(MutationEvent.self, where: QueryPredicateConstant.all) } - + func clearDataStore() async throws { try await Amplify.DataStore.clear() } - + func startAndWaitForReady() async throws { var requests: Set = [] let dataStoreReady = expectation(description: "DataStore `ready` event received") @@ -153,16 +163,16 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { try await startDataStore() await fulfillment(of: [dataStoreReady], timeout: 60) } - + func startDataStore() async throws { try await Amplify.DataStore.start() } - + func printDBPath() { let dbPath = DataStoreDebugger.dbFilePath print("DBPath: \(dbPath)") } - + @discardableResult func createAndWaitForSync(_ model: M) async throws -> M { var requests: Set = [] @@ -182,7 +192,7 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { await fulfillment(of: [modelSynced], timeout: 100) return savedModel } - + @discardableResult func updateAndWaitForSync(_ model: M, assertVersion: Int? = nil) async throws -> M { var requests: Set = [] @@ -195,7 +205,7 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { .filter { $0.mutationType == MutationEvent.MutationType.update.rawValue } .compactMap(\.version) .filter { version in - assertVersion.map({ $0 == version }) ?? true + assertVersion.map { $0 == version } ?? true } .sink { _ in modelSynced.fulfill() @@ -207,7 +217,7 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { return updatedModel } - func deleteAndWaitForSync(_ model: M) async throws { + func deleteAndWaitForSync(_ model: some Model) async throws { var requests: Set = [] let modelSynced = expectation(description: "delete model was synced successfully") let dataStoreEvents = HubPayload.EventName.DataStore.self @@ -224,13 +234,13 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { try await Amplify.DataStore.delete(model) await fulfillment(of: [modelSynced], timeout: 10) } - + enum AssertListState { case isNotLoaded(associatedIds: [String], associatedFields: [String]) case isLoaded(count: Int) } - - func assertList(_ list: List, state: AssertListState) { + + func assertList(_ list: List, state: AssertListState) { switch state { case .isNotLoaded(let expectedAssociatedIds, let expectedAssociatedFields): if case .notLoaded(let associatedIdentifiers, let associatedFields) = list.listProvider.getState() { @@ -247,14 +257,16 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { } } } - + enum AssertLazyModelState { case notLoaded(identifiers: [LazyReferenceIdentifier]?) case loaded(model: M?) } - - func assertLazyReference(_ lazyModel: LazyReference, - state: AssertLazyModelState) { + + func assertLazyReference( + _ lazyModel: LazyReference, + state: AssertLazyModelState + ) { switch state { case .notLoaded(let expectedIdentifiers): if case .notLoaded(let identifiers) = lazyModel.modelProvider.getState() { @@ -264,7 +276,7 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { } case .loaded(let expectedModel): if case .loaded(let model) = lazyModel.modelProvider.getState() { - guard let expectedModel = expectedModel, let model = model else { + guard let expectedModel, let model else { XCTAssertNil(model) return } @@ -274,40 +286,48 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { } } } - - func assertModelExists(_ model: M) async throws { + + func assertModelExists(_ model: some Model) async throws { let modelExists = try await modelExists(model) XCTAssertTrue(modelExists) } - - func assertModelDoesNotExist(_ model: M) async throws { + + func assertModelDoesNotExist(_ model: some Model) async throws { let modelExists = try await modelExists(model) XCTAssertFalse(modelExists) } - + func modelExists(_ model: M) async throws -> Bool { let identifierName = model.schema.primaryKey.sqlName let queryPredicate: QueryPredicate = field(identifierName).eq(model.identifier) - - let queriedModels = try await Amplify.DataStore.query(M.self, - where: queryPredicate) - let metadataId = MutationSyncMetadata.identifier(modelName: model.modelName, - modelId: model.identifier) - guard let metadata = try await Amplify.DataStore.query(MutationSyncMetadata.self, - byId: metadataId) else { + + let queriedModels = try await Amplify.DataStore.query( + M.self, + where: queryPredicate + ) + let metadataId = MutationSyncMetadata.identifier( + modelName: model.modelName, + modelId: model.identifier + ) + guard let metadata = try await Amplify.DataStore.query( + MutationSyncMetadata.self, + byId: metadataId + ) else { XCTFail("Could not retrieve metadata for model \(model)") throw "Could not retrieve metadata for model \(model)" } - + return !(metadata.deleted && queriedModels.isEmpty) } - + func query(for model: M) async throws -> M { let identifierName = model.schema.primaryKey.sqlName let queryPredicate: QueryPredicate = field(identifierName).eq(model.identifier) - - let queriedModels = try await Amplify.DataStore.query(M.self, - where: queryPredicate) + + let queriedModels = try await Amplify.DataStore.query( + M.self, + where: queryPredicate + ) if queriedModels.count > 1 { XCTFail("Expected to find one model, found \(queriedModels.count). \(queriedModels)") throw "Expected to find one model, found \(queriedModels.count). \(queriedModels)" @@ -320,21 +340,21 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { } } -struct DataStoreDebugger { - +enum DataStoreDebugger { + static var dbFilePath: URL? { getAdapter()?.dbFilePath } - + static func getAdapter() -> SQLiteStorageEngineAdapter? { if let dataStorePlugin = tryGetPlugin(), let storageEngine = dataStorePlugin.storageEngine as? StorageEngine, let adapter = storageEngine.storageAdapter as? SQLiteStorageEngineAdapter { return adapter } - + print("Could not get `SQLiteStorageEngineAdapter` from DataStore") return nil } - + static func tryGetPlugin() -> AWSDataStorePlugin? { do { return try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as? AWSDataStorePlugin diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AmplifyModels.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AmplifyModels.swift index fa01b38420..798732052f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AmplifyModels.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AmplifyModels.swift @@ -1,12 +1,19 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation // Contains the set of classes that conforms to the `Model` protocol. -final public class AmplifyModels: AmplifyModelRegistration { +public final class AmplifyModels: AmplifyModelRegistration { public let version: String = "248b0ffa3d44f144554beab3bf489b20" - + public func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post4V2.self) ModelRegistry.register(modelType: Comment4V2.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreAuthBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreAuthBaseTest.swift index 155915a31b..0a61ea2fe6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreAuthBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreAuthBaseTest.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import XCTest -import Combine +import AWSCognitoAuthPlugin import AWSDataStorePlugin import AWSPluginsCore +import Combine +import Foundation +import XCTest @testable import AWSAPIPlugin -import AWSCognitoAuthPlugin #if !os(watchOS) @testable import DataStoreHostApp @@ -48,13 +48,13 @@ class DataStoreAuthBaseTestURLSessionFactory: URLSessionBehaviorFactory { result.insert(.apiKey) } - if let authHeaderValue = authHeaderValue, + if let authHeaderValue, case let .success(claims) = AWSAuthService().getTokenClaims(tokenString: authHeaderValue), let cognitoIss = claims["iss"] as? String, cognitoIss.contains("cognito") { result.insert(.amazonCognitoUserPools) } - if let authHeaderValue = authHeaderValue, + if let authHeaderValue, authHeaderValue.starts(with: "AWS4-HMAC-SHA256") { result.insert(.awsIAM) } @@ -89,9 +89,11 @@ class DataStoreAuthBaseTestURLSessionFactory: URLSessionBehaviorFactory { configuration.tlsMaximumSupportedProtocolVersion = .TLSv13 configuration.protocolClasses?.insert(Sniffer.self, at: 0) - let session = URLSession(configuration: configuration, - delegate: urlSessionDelegate, - delegateQueue: nil) + let session = URLSession( + configuration: configuration, + delegate: urlSessionDelegate, + delegateQueue: nil + ) return AmplifyURLSession(session: session) } @@ -203,9 +205,11 @@ class AWSDataStoreAuthBaseTest: XCTestCase { #else let datastoreConfig = DataStoreConfiguration.custom(authModeStrategy: testType.authStrategy) #endif - - try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, - configuration: datastoreConfig)) + + try Amplify.add(plugin: AWSDataStorePlugin( + modelRegistration: models, + configuration: datastoreConfig + )) let apiPlugin = apiPluginFactory() @@ -238,40 +242,46 @@ class AWSDataStoreAuthBaseTest: XCTestCase { extension AWSDataStoreAuthBaseTest { /// Signin given user /// - Parameter user - func signIn(user: TestUser?, - file: StaticString = #file, - line: UInt = #line) async { - guard let user = user else { + func signIn( + user: TestUser?, + file: StaticString = #file, + line: UInt = #line + ) async { + guard let user else { XCTFail("Invalid user", file: file, line: line) return } let signInInvoked = expectation(description: "sign in completed") do { - _ = try await Amplify.Auth.signIn(username: user.username, - password: user.password, - options: nil) + _ = try await Amplify.Auth.signIn( + username: user.username, + password: user.password, + options: nil + ) signInInvoked.fulfill() - } catch(let error) { + } catch (let error) { XCTFail("Signin failure \(error)", file: file, line: line) signInInvoked.fulfill() // won't count as pass } await fulfillment(of: [signInInvoked], timeout: TestCommonConstants.networkTimeout) - + let signedIn = await isSignedIn() XCTAssert(signedIn, file: file, line: line) } /// Signout current signed-in user - func signOut(file: StaticString = #file, - line: UInt = #line) async { + func signOut( + file: StaticString = #file, + line: UInt = #line + ) async { let signoutInvoked = expectation(description: "sign out completed") Task { _ = await Amplify.Auth.signOut() signoutInvoked.fulfill() } - + await fulfillment(of: [signoutInvoked], timeout: TestCommonConstants.networkTimeout) - + let signedIn = await isSignedIn() XCTAssert(!signedIn, file: file, line: line) } @@ -284,10 +294,10 @@ extension AWSDataStoreAuthBaseTest { let authSession = try await Amplify.Auth.fetchAuthSession() resultOptional = authSession.isSignedIn checkIsSignedInCompleted.fulfill() - } catch(let error) { + } catch (let error) { fatalError("Failed to get auth session \(error)") } - + await fulfillment(of: [checkIsSignedInCompleted], timeout: TestCommonConstants.networkTimeout) guard let result = resultOptional else { XCTFail("Could not get isSignedIn for user") @@ -313,7 +323,7 @@ extension AWSDataStoreAuthBaseTest { case .failure(let error): XCTFail("Failed to get auth session \(error)") } - } catch(let error) { + } catch (let error) { XCTFail("Failed to get auth session \(error)") } @@ -342,7 +352,7 @@ extension AWSDataStoreAuthBaseTest { case .failure(let error): XCTFail("Failed to get auth session \(error)") } - } catch(let error) { + } catch (let error) { XCTFail("Failed to get auth session \(error)") } await fulfillment(of: [retrieveIdentityCompleted], timeout: TestCommonConstants.networkTimeout) @@ -354,10 +364,12 @@ extension AWSDataStoreAuthBaseTest { return result } - func queryModel(_ model: M.Type, - byId id: String, - file: StaticString = #file, - line: UInt = #line) async -> M? { + func queryModel( + _ model: M.Type, + byId id: String, + file: StaticString = #file, + line: UInt = #line + ) async -> M? { var queriedModel: M? let queriedInvoked = expectation(description: "Model queried") @@ -365,10 +377,10 @@ extension AWSDataStoreAuthBaseTest { let model = try await Amplify.DataStore.query(M.self, byId: id) queriedModel = model queriedInvoked.fulfill() - } catch(let error) { + } catch (let error) { XCTFail("Failed to query model \(error)", file: file, line: line) } - + await fulfillment(of: [queriedInvoked], timeout: TestCommonConstants.networkTimeout) return queriedModel } @@ -381,9 +393,11 @@ extension AWSDataStoreAuthBaseTest { /// - modelType: model type /// - expectation: success XCTestExpectation /// - onFailure: on failure callback - func assertQuerySuccess(modelType: M.Type, - _ expectations: AuthTestExpectations, - onFailure: @escaping (_ error: DataStoreError) -> Void) async { + func assertQuerySuccess( + modelType: (some Model).Type, + _ expectations: AuthTestExpectations, + onFailure: @escaping (_ error: DataStoreError) -> Void + ) async { Amplify.Publisher.create { try await Amplify.DataStore.query(modelType) }.sink { @@ -395,14 +409,18 @@ extension AWSDataStoreAuthBaseTest { XCTAssertNotNil(posts) expectations.query.fulfill() }.store(in: &requests) - await fulfillment(of: [expectations.query], - timeout: 60) + await fulfillment( + of: [expectations.query], + timeout: 60 + ) } /// Asserts that DataStore is in a ready state and subscriptions are established /// - Parameter events: DataStore Hub events - func assertDataStoreReady(_ expectations: AuthTestExpectations, - expectedModelSynced: Int = 1) async { + func assertDataStoreReady( + _ expectations: AuthTestExpectations, + expectedModelSynced: Int = 1 + ) async { var modelSyncedCount = 0 let dataStoreEvents = HubPayload.EventName.DataStore.self Amplify @@ -430,13 +448,17 @@ extension AWSDataStoreAuthBaseTest { do { try await Amplify.DataStore.start() - } catch(let error) { + } catch (let error) { XCTFail("Failure due to error: \(error)") } - await fulfillment(of: [expectations.subscriptionsEstablished, - expectations.modelsSynced, - expectations.ready], - timeout: 60) + await fulfillment( + of: [ + expectations.subscriptionsEstablished, + expectations.modelsSynced, + expectations.ready + ], + timeout: 60 + ) } /// Assert that a save and a delete mutation complete successfully. @@ -444,9 +466,11 @@ extension AWSDataStoreAuthBaseTest { /// - model: model instance saved and then deleted /// - expectations: test expectations /// - onFailure: failure callback - func assertMutations(model: M, - _ expectations: AuthTestExpectations, - onFailure: @escaping (_ error: DataStoreError) -> Void) async { + func assertMutations( + model: some Model, + _ expectations: AuthTestExpectations, + onFailure: @escaping (_ error: DataStoreError) -> Void + ) async { Amplify .Hub .publisher(for: .dataStore) @@ -497,7 +521,7 @@ extension AWSDataStoreAuthBaseTest { await fulfillment(of: [expectations.mutationDelete, expectations.mutationDeleteProcessed], timeout: 60) } - + func assertUsedAuthTypes( testId: String, authTypes: [AWSAuthorizationType], @@ -509,7 +533,7 @@ extension AWSDataStoreAuthBaseTest { DataStoreAuthBaseTestURLSessionFactory.subject .filter { $0.0 == testId } .map { $0.1 } - .collect(.byTime(DispatchQueue.global(), .milliseconds(3500))) + .collect(.byTime(DispatchQueue.global(), .milliseconds(3_500))) .sink { let result = $0.reduce(Set()) { partialResult, data in partialResult.union(data) @@ -534,11 +558,12 @@ extension AWSDataStoreAuthBaseTest { var mutationDeleteProcessed: XCTestExpectation var ready: XCTestExpectation var expectations: [XCTestExpectation] { - return [subscriptionsEstablished, - modelsSynced, - query, - mutationSave, - mutationSaveProcessed + return [ + subscriptionsEstablished, + modelsSynced, + query, + mutationSave, + mutationSaveProcessed ] } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthCombinationTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthCombinationTests.swift index 9ba5f8e61a..a32789dad4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthCombinationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthCombinationTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @@ -17,8 +17,10 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { /// When: DataStore start is called /// Then: DataStore is successfully initialized. func testDataStoreReadyState() async { - await setup(withModels: PrivatePublicComboModels(), - testType: .multiAuth) + await setup( + withModels: PrivatePublicComboModels(), + testType: .multiAuth + ) await signIn(user: user1) let expectations = makeExpectations() @@ -31,7 +33,7 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { do { try await Amplify.DataStore.start() startExpectation.fulfill() - } catch(let error) { + } catch (let error) { XCTFail("DataStore start failure \(error)") } } @@ -44,12 +46,13 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { expectations.mutationDeleteProcessed.fulfill() await fulfillment(of: [ - startExpectation, - expectations.query, - expectations.mutationSave, - expectations.mutationSaveProcessed, - expectations.mutationDelete, - expectations.mutationDeleteProcessed], timeout: TestCommonConstants.networkTimeout) + startExpectation, + expectations.query, + expectations.mutationSave, + expectations.mutationSaveProcessed, + expectations.mutationDelete, + expectations.mutationDeleteProcessed + ], timeout: TestCommonConstants.networkTimeout) } /// Given: a user signed in with IAM @@ -59,9 +62,11 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { /// or PrivatePublicComboUPPost are sent with IAM auth for authenticated users. func testOperationsForPrivatePublicComboUPPost() async { let testId = UUID().uuidString - await setup(withModels: PrivatePublicComboModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePublicComboModels(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -70,14 +75,19 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePublicComboUPPost.self, - expectations, onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicComboUPPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicComboUPPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicComboUPPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -93,9 +103,11 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { let testId = UUID().uuidString let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey, .amazonCognitoUserPools]) - await setup(withModels: PrivatePublicComboModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePublicComboModels(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -103,15 +115,20 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { await assertDataStoreReady(expectations) // Query - await assertQuerySuccess(modelType: PrivatePublicComboAPIPost.self, - expectations, onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicComboAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicComboAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicComboAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -128,9 +145,11 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { /// from syncing and DataStore getting to a “ready” state. func testOperationsForPrivatePublicComboAPIPost() async { let testId = UUID().uuidString - await setup(withModels: PrivatePublicComboModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePublicComboModels(), + testType: .multiAuth, + testId: testId + ) let expectations = makeExpectations() @@ -139,14 +158,19 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: PrivatePublicComboAPIPost.self, - expectations, onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicComboAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicComboAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicComboAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests+Models.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests+Models.swift index 32170dde44..ab0b7eb465 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests+Models.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests+Models.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Foundation import Combine +import Foundation +import XCTest @testable import Amplify diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests.swift index fc9264598c..4163e90aff 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Foundation import Combine +import Foundation +import XCTest @testable import Amplify @@ -29,8 +29,10 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: OwnerUPPost.self, - expectations) { error in + await assertQuerySuccess( + modelType: OwnerUPPost.self, + expectations + ) { error in XCTFail("Error query \(error)") } @@ -68,14 +70,18 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: GroupUPPost.self, - expectations) { error in + await assertQuerySuccess( + modelType: GroupUPPost.self, + expectations + ) { error in XCTFail("Error query \(error)") } // Mutation - await assertMutations(model: GroupUPPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupUPPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -110,11 +116,12 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { await fulfillment(of: [authTypeExpecation], timeout: 5) await fulfillment(of: [ - expectations.query, - expectations.mutationSave, - expectations.mutationSaveProcessed, - expectations.mutationDelete, - expectations.mutationDeleteProcessed], timeout: TestCommonConstants.networkTimeout) + expectations.query, + expectations.mutationSave, + expectations.mutationSaveProcessed, + expectations.mutationDelete, + expectations.mutationDeleteProcessed + ], timeout: TestCommonConstants.networkTimeout) } @@ -139,14 +146,18 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) - await assertQuerySuccess(modelType: PrivateUPPost.self, - expectations) { error in + await assertQuerySuccess( + modelType: PrivateUPPost.self, + expectations + ) { error in XCTFail("Error query \(error)") } // Mutations - await assertMutations(model: PrivateUPPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivateUPPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -169,14 +180,19 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) - await assertQuerySuccess(modelType: PrivateIAMPost.self, - expectations, onFailure: { error in + await assertQuerySuccess( + modelType: PrivateIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivateIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivateIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -198,14 +214,19 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: PublicIAMPost.self, - expectations, onFailure: { error in + await assertQuerySuccess( + modelType: PublicIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PublicIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PublicIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -227,14 +248,19 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: PublicAPIPost.self, - expectations, onFailure: { error in + await assertQuerySuccess( + modelType: PublicAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PublicAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PublicAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthThreeRulesTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthThreeRulesTests.swift index 1ac6d4a481..861672c2d8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthThreeRulesTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthThreeRulesTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @@ -24,9 +24,11 @@ class AWSDataStoreMultiAuthThreeRulesTests: AWSDataStoreAuthBaseTest { /// fail with User Pool auth but succeed with IAM auth for an authenticated user. func testOwnerPrivatePublicUserPoolsIAMAPIKeyAuthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: OwnerPrivatePublicUserPoolsAPIKeyModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: OwnerPrivatePublicUserPoolsAPIKeyModels(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -36,15 +38,19 @@ class AWSDataStoreMultiAuthThreeRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: OwnerPrivatePublicUPIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPrivatePublicUPIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPrivatePublicUPIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPrivatePublicUPIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -57,9 +63,11 @@ class AWSDataStoreMultiAuthThreeRulesTests: AWSDataStoreAuthBaseTest { /// - DataStore is successfully initialized, sync/mutation/subscription network requests are sent with API Key func testOwnerPrivatePublicUserPoolsIAMAPIKeyUnauthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: OwnerPrivatePublicUserPoolsAPIKeyModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: OwnerPrivatePublicUserPoolsAPIKeyModels(), + testType: .multiAuth, + testId: testId + ) let expectations = makeExpectations() @@ -68,15 +76,19 @@ class AWSDataStoreMultiAuthThreeRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: OwnerPrivatePublicUPIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPrivatePublicUPIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPrivatePublicUPIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPrivatePublicUPIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -94,9 +106,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// with Cognito auth for authenticated users func testGroupPrivatePublicUserPoolsIAMAPIKeyAuthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: GroupPrivatePublicUserPoolsAPIKeyModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: GroupPrivatePublicUserPoolsAPIKeyModels(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -106,15 +120,19 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: GroupPrivatePublicUPIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: GroupPrivatePublicUPIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: GroupPrivatePublicUPIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPrivatePublicUPIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -127,9 +145,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// - DataStore is successfully initialized, sync/mutation/subscription network requests are sent with API Key func testGroupPrivatePublicUserPoolsIAMAPIKeyUnauthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: GroupPrivatePublicUserPoolsAPIKeyModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: GroupPrivatePublicUserPoolsAPIKeyModels(), + testType: .multiAuth, + testId: testId + ) let expectations = makeExpectations() @@ -138,14 +158,18 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: GroupPrivatePublicUPIAMAPIPost.self, - expectations) { error in + await assertQuerySuccess( + modelType: GroupPrivatePublicUPIAMAPIPost.self, + expectations + ) { error in XCTFail("Error query \(error)") } // Mutation - await assertMutations(model: GroupPrivatePublicUPIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPrivatePublicUPIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -162,9 +186,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// with Cognito func testPrivatePrivatePublicUserPoolsIAMIAMAuthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: PrivatePrivatePublicUserPoolsIAMIAM(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePrivatePublicUserPoolsIAMIAM(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -174,14 +200,18 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePrivatePublicUPIAMIAMPost.self, - expectations) { error in + await assertQuerySuccess( + modelType: PrivatePrivatePublicUPIAMIAMPost.self, + expectations + ) { error in XCTFail("Error query \(error)") } // Mutation - await assertMutations(model: PrivatePrivatePublicUPIAMIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePrivatePublicUPIAMIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -194,9 +224,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// - DataStore is successfully initialized, sync/mutation/subscription network requests are sent with IAM func testPrivatePrivatePublicUserPoolsIAMIAMUnauthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: PrivatePrivatePublicUserPoolsIAMIAM(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePrivatePublicUserPoolsIAMIAM(), + testType: .multiAuth, + testId: testId + ) let expectations = makeExpectations() @@ -205,15 +237,19 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: PrivatePrivatePublicUPIAMIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePrivatePublicUPIAMIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePrivatePublicUPIAMIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePrivatePublicUPIAMIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -230,9 +266,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// with Cognito func testPrivatePrivatePublicUserPoolsIAMApiKeyAuthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: PrivatePrivatePublicUserPoolsIAMAPiKey(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePrivatePublicUserPoolsIAMAPiKey(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -242,15 +280,19 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePrivatePublicUPIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePrivatePublicUPIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePrivatePublicUPIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePrivatePublicUPIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -265,9 +307,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// User Pool auth but succeed with IAM auth for an authenticated user. func testPrivatePrivatePublicUserPoolsIAMApiKeyUnauthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: PrivatePrivatePublicUserPoolsIAMAPiKey(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePrivatePublicUserPoolsIAMAPiKey(), + testType: .multiAuth, + testId: testId + ) let expectations = makeExpectations() @@ -276,15 +320,19 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: PrivatePrivatePublicUPIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePrivatePublicUPIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePrivatePublicUPIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePrivatePublicUPIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -301,9 +349,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// with Cognito func testPrivatePublicPublicUserPoolsAPIKeyIAMAuthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: PrivatePublicPublicUserPoolsAPIKeyIAM(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePublicPublicUserPoolsAPIKeyIAM(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -313,15 +363,19 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePublicPublicUPAPIIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicPublicUPAPIIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicPublicUPAPIIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicPublicUPAPIIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -336,9 +390,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// public IAM auth but succeed with API key auth. func testPrivatePublicPublicUserPoolsAPIKeyIAMUnauthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: PrivatePublicPublicUserPoolsAPIKeyIAM(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePublicPublicUserPoolsAPIKeyIAM(), + testType: .multiAuth, + testId: testId + ) let expectations = makeExpectations() @@ -347,15 +403,19 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: PrivatePublicPublicUPAPIIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicPublicUPAPIIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutations - await assertMutations(model: PrivatePublicPublicUPAPIIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicPublicUPAPIIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests+Models.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests+Models.swift index b9bac33555..971cd9e2ac 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests+Models.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests+Models.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension AWSDataStoreMultiAuthTwoRulesTests { struct OwnerPrivateUserPoolsIAMModels: AmplifyModelRegistration { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests.swift index 29e7979f38..97c1616418 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation +import AWSAPIPlugin import Combine +import Foundation import XCTest -import AWSAPIPlugin @testable import Amplify @@ -30,15 +30,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { await assertDataStoreReady(expectations) let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) - await assertQuerySuccess(modelType: OwnerPrivateUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPrivateUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: model, - expectations) { error in + await assertMutations( + model: model, + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -63,15 +67,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: OwnerPublicUPAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPublicUPAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPublicUPAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPublicUPAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -92,15 +100,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: OwnerPublicUPAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPublicUPAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPublicUPAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPublicUPAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -125,15 +137,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: OwnerPublicUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPublicUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPublicUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPublicUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } await fulfillment(of: [authTypeExpecation], timeout: 5) @@ -153,15 +169,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: OwnerPublicUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPublicUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPublicUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPublicUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -205,15 +225,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: OwnerPublicOIDAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPublicOIDAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPublicOIDAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPublicOIDAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -238,15 +262,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: GroupPrivateUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: GroupPrivateUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: GroupPrivateUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPrivateUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -272,15 +300,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: GroupPublicUPAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: GroupPublicUPAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: GroupPublicUPAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPublicUPAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -301,15 +333,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: GroupPublicUPAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: GroupPublicUPAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: GroupPublicUPAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPublicUPAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -335,15 +371,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: GroupPublicUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: GroupPublicUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: GroupPublicUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPublicUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -364,15 +404,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: GroupPublicUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: GroupPublicUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: GroupPublicUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPublicUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -397,15 +441,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePrivateUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePrivateUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePrivateUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePrivateUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -431,15 +479,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePublicUPAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicUPAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicUPAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicUPAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -460,15 +512,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: PrivatePublicUPAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicUPAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicUPAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicUPAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -495,15 +551,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePublicUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -524,15 +584,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: PrivatePublicUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -559,15 +623,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: PrivatePublicIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -589,15 +657,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { await assertDataStoreReady(expectations) let authTypeExpectations = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: PrivatePublicIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -621,15 +693,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpectation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: PublicPublicIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PublicPublicIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PublicPublicIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PublicPublicIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -642,11 +718,11 @@ extension AWSDataStoreMultiAuthTwoRulesTests { class TestAuthProviderFactory: APIAuthProviderFactory { class TestOIDCAuthProvider: AmplifyOIDCAuthProvider { - + func getLatestAuthToken() async throws -> String { throw DataStoreError.unknown("Not implemented", "Expected, we're testing unauthorized users.") } - + func getUserPoolAccessToken() async throws -> String { throw DataStoreError.unknown("Not implemented", "Expected, we're testing unauthorized users.") } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost+Schema.swift index 9c6dd62b10..dc834af993 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension GroupPrivatePublicUPIAMAPIPost { +public extension GroupPrivatePublicUPIAMAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let groupPrivatePublicUPIAMAPIPost = GroupPrivatePublicUPIAMAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost.swift index 7d4be15c66..bb0626f7b2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost.swift @@ -15,17 +15,23 @@ public struct GroupPrivatePublicUPIAMAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost+Schema.swift index c0ab2e2ec9..9ce386430e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension GroupPrivateUPIAMPost { +public extension GroupPrivateUPIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let groupPrivateUPIAMPost = GroupPrivateUPIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost.swift index ce3958ecc4..e30b70e1b9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost.swift @@ -15,17 +15,23 @@ public struct GroupPrivateUPIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost+Schema.swift index 16f97e6c85..5d125de36a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension GroupPublicUPAPIPost { +public extension GroupPublicUPAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let groupPublicUPAPIPost = GroupPublicUPAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost.swift index 3fb53d6f6f..adeacc180b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost.swift @@ -15,17 +15,23 @@ public struct GroupPublicUPAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost+Schema.swift index 201e5f3b04..9552dd07c4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension GroupPublicUPIAMPost { +public extension GroupPublicUPIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let groupPublicUPIAMPost = GroupPublicUPIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost.swift index a7342cb275..24c83bd79e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost.swift @@ -15,17 +15,23 @@ public struct GroupPublicUPIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost+Schema.swift index fecc21dc17..b193f72c4f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension GroupUPPost { +public extension GroupUPPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let groupUPPost = GroupUPPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost.swift index 550fece3a5..0d6f9e0d85 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost.swift @@ -15,17 +15,23 @@ public struct GroupUPPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost+Schema.swift index 216581701c..ad3e29ba99 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerOIDCPost { +public extension OwnerOIDCPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerOIDCPost = OwnerOIDCPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost.swift index 4840da2d1f..90b0a99de1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost.swift @@ -15,17 +15,23 @@ public struct OwnerOIDCPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost+Schema.swift index ab2ee1c581..9ba53e8530 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerPrivatePublicUPIAMAPIPost { +public extension OwnerPrivatePublicUPIAMAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerPrivatePublicUPIAMAPIPost = OwnerPrivatePublicUPIAMAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost.swift index e4ec5102df..3f1a5e0a30 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost.swift @@ -15,17 +15,23 @@ public struct OwnerPrivatePublicUPIAMAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost+Schema.swift index 9cb3394fa0..964a9c198f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerPrivateUPIAMPost { +public extension OwnerPrivateUPIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerPrivateUPIAMPost = OwnerPrivateUPIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost.swift index 0d97d19833..7afb326a25 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost.swift @@ -15,17 +15,23 @@ public struct OwnerPrivateUPIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost+Schema.swift index 9c92fdf569..3db935e968 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerPublicOIDAPIPost { +public extension OwnerPublicOIDAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerPublicOIDAPIPost = OwnerPublicOIDAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost.swift index 5f7ba8a80c..5ea950fffb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost.swift @@ -15,17 +15,23 @@ public struct OwnerPublicOIDAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost+Schema.swift index d631bee47b..4d7221f4fb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerPublicUPAPIPost { +public extension OwnerPublicUPAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerPublicUPAPIPost = OwnerPublicUPAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost.swift index fc38cf0020..e3c8be119f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost.swift @@ -15,17 +15,23 @@ public struct OwnerPublicUPAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost+Schema.swift index 52989229f2..6bf59cc538 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerPublicUPIAMPost { +public extension OwnerPublicUPIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerPublicUPIAMPost = OwnerPublicUPIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost.swift index 83534f1a61..530800fd2c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost.swift @@ -15,17 +15,23 @@ public struct OwnerPublicUPIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost+Schema.swift index dca06b5ae9..e8fe2536d3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerUPPost { +public extension OwnerUPPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerUPPost = OwnerUPPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost.swift index 367434a454..f095fe95cf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost.swift @@ -15,17 +15,23 @@ public struct OwnerUPPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost+Schema.swift index 3e0a1da20e..a46fbcbb77 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivateIAMPost { +public extension PrivateIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privateIAMPost = PrivateIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost.swift index 479195fb93..fd80fd22d4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost.swift @@ -15,17 +15,23 @@ public struct PrivateIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost+Schema.swift index ff4f34d012..12c20b2cfc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePrivatePublicUPIAMAPIPost { +public extension PrivatePrivatePublicUPIAMAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePrivatePublicUPIAMAPIPost = PrivatePrivatePublicUPIAMAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost.swift index 658b9d43c6..e63b3652e9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost.swift @@ -15,17 +15,23 @@ public struct PrivatePrivatePublicUPIAMAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost+Schema.swift index 3523034148..07cc137671 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePrivatePublicUPIAMIAMPost { +public extension PrivatePrivatePublicUPIAMIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePrivatePublicUPIAMIAMPost = PrivatePrivatePublicUPIAMIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost.swift index 5ff60a442b..24e0b02774 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost.swift @@ -15,17 +15,23 @@ public struct PrivatePrivatePublicUPIAMIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost+Schema.swift index 900106d620..1699d1be57 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePrivateUPIAMPost { +public extension PrivatePrivateUPIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePrivateUPIAMPost = PrivatePrivateUPIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost.swift index c08743f094..fee351c261 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost.swift @@ -15,17 +15,23 @@ public struct PrivatePrivateUPIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost+Schema.swift index 4dabee89d7..334005238f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePublicComboAPIPost { +public extension PrivatePublicComboAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePublicComboAPIPost = PrivatePublicComboAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost.swift index 1328daac10..207a986053 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost.swift @@ -15,17 +15,23 @@ public struct PrivatePublicComboAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost+Schema.swift index 0ede943be2..b62b24cad1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePublicComboUPPost { +public extension PrivatePublicComboUPPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePublicComboUPPost = PrivatePublicComboUPPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost.swift index 2360d03013..30d0f3155c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost.swift @@ -15,17 +15,23 @@ public struct PrivatePublicComboUPPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost+Schema.swift index 6579e31a8f..e2d70b39fe 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePublicIAMAPIPost { +public extension PrivatePublicIAMAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePublicIAMAPIPost = PrivatePublicIAMAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost.swift index 5f88dd6717..8dbf482e12 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost.swift @@ -15,17 +15,23 @@ public struct PrivatePublicIAMAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost+Schema.swift index 414e3a7444..8aa139b622 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePublicPublicUPAPIIAMPost { +public extension PrivatePublicPublicUPAPIIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePublicPublicUPAPIIAMPost = PrivatePublicPublicUPAPIIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost.swift index 83f0d3a703..f2dcc38d1a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost.swift @@ -15,17 +15,23 @@ public struct PrivatePublicPublicUPAPIIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost+Schema.swift index 592a83f6f6..0c62cf4dd7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePublicUPAPIPost { +public extension PrivatePublicUPAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePublicUPAPIPost = PrivatePublicUPAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost.swift index 8d1d35ba3d..72a2f40e67 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost.swift @@ -15,17 +15,23 @@ public struct PrivatePublicUPAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost+Schema.swift index 0e160491aa..9c19e8f941 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePublicUPIAMPost { +public extension PrivatePublicUPIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePublicUPIAMPost = PrivatePublicUPIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost.swift index c902b2daf6..400d87d87b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost.swift @@ -15,17 +15,23 @@ public struct PrivatePublicUPIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost+Schema.swift index 33606dc7c9..ee15a2eafc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivateUPPost { +public extension PrivateUPPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privateUPPost = PrivateUPPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost.swift index d487bdedf5..e4c15445e4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost.swift @@ -15,17 +15,23 @@ public struct PrivateUPPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost+Schema.swift index 6412e25a65..a49f4b29e9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PublicAPIPost { +public extension PublicAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let publicAPIPost = PublicAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost.swift index e5f10b107e..ef4dd44811 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost.swift @@ -15,17 +15,23 @@ public struct PublicAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost+Schema.swift index d51b761442..054e275734 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PublicIAMPost { +public extension PublicIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let publicIAMPost = PublicIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost.swift index a6132c5ad2..5d1daea252 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost.swift @@ -15,17 +15,23 @@ public struct PublicIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost+Schema.swift index 9473b113d6..00d7f9dfaa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PublicPublicIAMAPIPost { +public extension PublicPublicIAMAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let publicPublicIAMAPIPost = PublicPublicIAMAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost.swift index 58f3770c1b..8895229fc8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost.swift @@ -15,17 +15,23 @@ public struct PublicPublicIAMAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2+Schema.swift index e51bfa5402..f798199559 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project1V2 { +public extension Project1V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team @@ -20,10 +20,10 @@ extension Project1V2 { case project1V2TeamId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project1V2 = Project1V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2.swift index 34440bbb51..7cf9f9a23f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2.swift @@ -17,23 +17,29 @@ public struct Project1V2: Model { public var updatedAt: Temporal.DateTime? public var project1V2TeamId: String? - public init(id: String = UUID().uuidString, - name: String? = nil, - team: Team1V2? = nil, - project1V2TeamId: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team1V2? = nil, + project1V2TeamId: String? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, updatedAt: nil, - project1V2TeamId: project1V2TeamId) + project1V2TeamId: project1V2TeamId + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team1V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project1V2TeamId: String? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team1V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project1V2TeamId: String? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2+Schema.swift index 8ed0f54ddf..2fa869b077 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Team1V2 { +public extension Team1V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team1V2 = Team1V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2.swift index ed29653b08..9e547cc972 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2.swift @@ -15,17 +15,23 @@ public struct Team1V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2+Schema.swift index 286ca57848..b1d25f76ab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project2V2 { +public extension Project2V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case teamID @@ -20,10 +20,10 @@ extension Project2V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project2V2 = Project2V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2.swift index fed160bd8c..adc2cfc7fc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2.swift @@ -17,23 +17,29 @@ public struct Project2V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2V2? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2V2? = nil + ) { + self.init( + id: id, name: name, teamID: teamID, team: team, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.teamID = teamID diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2+Schema.swift index 43e0f11b00..0db2c5e78b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Team2V2 { +public extension Team2V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team2V2 = Team2V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2.swift index 7f13b3927a..9b8e27a8b3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2.swift @@ -15,17 +15,23 @@ public struct Team2V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2+Schema.swift index cee3850f92..023f2e2d90 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment3V2 { +public extension Comment3V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case postID case content @@ -19,10 +19,10 @@ extension Comment3V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment3V2 = Comment3V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2.swift index 52f14a06fe..6f0647dd70 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2.swift @@ -16,20 +16,26 @@ public struct Comment3V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - postID: String, - content: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + postID: String, + content: String + ) { + self.init( + id: id, postID: postID, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - postID: String, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + postID: String, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.postID = postID self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2+Schema.swift index f377adf509..e8525efd3a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post3V2 { +public extension Post3V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension Post3V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post3V2 = Post3V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2.swift index 365ff8bc83..bfd3f9db93 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2.swift @@ -16,20 +16,26 @@ public struct Post3V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift index 41081acbfc..a2efc3dd3f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment3aV2 { +public extension Comment3aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt @@ -19,10 +19,10 @@ extension Comment3aV2 { case post3aV2CommentsId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment3aV2 = Comment3aV2.keys model.pluralName = "Comment3aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2.swift index 883bbd6eb8..362732db79 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2.swift @@ -16,20 +16,26 @@ public struct Comment3aV2: Model { public var updatedAt: Temporal.DateTime? public var post3aV2CommentsId: String? - public init(id: String = UUID().uuidString, - content: String, - post3aV2CommentsId: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String, + post3aV2CommentsId: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, updatedAt: nil, - post3aV2CommentsId: post3aV2CommentsId) + post3aV2CommentsId: post3aV2CommentsId + ) } - internal init(id: String = UUID().uuidString, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - post3aV2CommentsId: String? = nil) { + init( + id: String = UUID().uuidString, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + post3aV2CommentsId: String? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift index 3b33c9960e..067713be06 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post3aV2 { +public extension Post3aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension Post3aV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post3aV2 = Post3aV2.keys model.pluralName = "Post3aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2.swift index 5332fcf81a..78361ec783 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2.swift @@ -16,20 +16,26 @@ public struct Post3aV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2+Schema.swift index db568413b1..90683b5561 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment4V2 { +public extension Comment4V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post @@ -19,10 +19,10 @@ extension Comment4V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment4V2 = Comment4V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2.swift index 5873d993e4..0d4073d6b4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2.swift @@ -16,20 +16,26 @@ public struct Comment4V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2+Schema.swift index c0fa5fdfbb..e010e1c080 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post4V2 { +public extension Post4V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension Post4V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post4V2 = Post4V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2.swift index 7978edceb7..9106744759 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2.swift @@ -16,20 +16,26 @@ public struct Post4V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift index 5142fd05de..63cb47ada7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project4aV2 { +public extension Project4aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team @@ -20,10 +20,10 @@ extension Project4aV2 { case project4aV2TeamId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project4aV2 = Project4aV2.keys model.pluralName = "Project4aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2.swift index 51b873975c..4777b1dcda 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2.swift @@ -21,23 +21,29 @@ public class Project4aV2: Model { public var updatedAt: Temporal.DateTime? public var project4aV2TeamId: String? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String? = nil, team: Team4aV2? = nil, - project4aV2TeamId: String? = nil) { - self.init(id: id, + project4aV2TeamId: String? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, updatedAt: nil, - project4aV2TeamId: project4aV2TeamId) + project4aV2TeamId: project4aV2TeamId + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team4aV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project4aV2TeamId: String? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team4aV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project4aV2TeamId: String? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift index 9b7cae724e..18ccef180d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Team4aV2 { +public extension Team4aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case project @@ -19,10 +19,10 @@ extension Team4aV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team4aV2 = Team4aV2.keys model.pluralName = "Team4aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2.swift index 71d880f56b..7abfb7100b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2.swift @@ -16,20 +16,26 @@ public class Team4aV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String, - project: Project4aV2? = nil) { - self.init(id: id, + project: Project4aV2? = nil + ) { + self.init( + id: id, name: name, project: project, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - project: Project4aV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + project: Project4aV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.project = project diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift index 236d2be094..e3f4983c80 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project4bV2 { +public extension Project4bV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team @@ -20,10 +20,10 @@ extension Project4bV2 { case project4bV2TeamId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project4bV2 = Project4bV2.keys model.pluralName = "Project4bV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2.swift index 2369a6c57b..9b280c61df 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2.swift @@ -17,23 +17,29 @@ public class Project4bV2: Model { public var updatedAt: Temporal.DateTime? public var project4bV2TeamId: String? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String? = nil, team: Team4bV2? = nil, - project4bV2TeamId: String? = nil) { - self.init(id: id, + project4bV2TeamId: String? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, updatedAt: nil, - project4bV2TeamId: project4bV2TeamId) + project4bV2TeamId: project4bV2TeamId + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team4bV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project4bV2TeamId: String? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team4bV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project4bV2TeamId: String? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift index 311044fad2..eb0ec1c290 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Team4bV2 { +public extension Team4bV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case project @@ -19,10 +19,10 @@ extension Team4bV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team4bV2 = Team4bV2.keys model.pluralName = "Team4bV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2.swift index 644c856c81..b1831b611b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2.swift @@ -16,20 +16,26 @@ public class Team4bV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String, - project: Project4bV2? = nil) { - self.init(id: id, + project: Project4bV2? = nil + ) { + self.init( + id: id, name: name, project: project, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - project: Project4bV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + project: Project4bV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.project = project diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2+Schema.swift index 84a32e2cb8..9528d2576d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post5V2 { +public extension Post5V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case editors @@ -19,10 +19,10 @@ extension Post5V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post5V2 = Post5V2.keys model.pluralName = "Post5V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2.swift index 3165ee7f99..1090df258b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2.swift @@ -16,20 +16,26 @@ public struct Post5V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - editors: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + editors: List? = [] + ) { + self.init( + id: id, title: title, editors: editors, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - editors: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + editors: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.editors = editors diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift index cdbcd3e07d..23a7be5848 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension PostEditor5V2 { +public extension PostEditor5V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post5V2 case user5V2 @@ -19,10 +19,10 @@ extension PostEditor5V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let postEditor5V2 = PostEditor5V2.keys model.pluralName = "PostEditor5V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2.swift index f78bbe9420..dabb434aac 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2.swift @@ -16,20 +16,26 @@ public struct PostEditor5V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - post5V2: Post5V2, - user5V2: User5V2) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + post5V2: Post5V2, + user5V2: User5V2 + ) { + self.init( + id: id, post5V2: post5V2, user5V2: user5V2, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - post5V2: Post5V2, - user5V2: User5V2, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + post5V2: Post5V2, + user5V2: User5V2, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.post5V2 = post5V2 self.user5V2 = user5V2 diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2+Schema.swift index 5c35bd5ad9..a15d33b3ab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension User5V2 { +public extension User5V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case username case posts @@ -19,10 +19,10 @@ extension User5V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let user5V2 = User5V2.keys model.pluralName = "User5V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2.swift index 7329a37803..dbf049a0f0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2.swift @@ -16,20 +16,26 @@ public struct User5V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - username: String, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + username: String, + posts: List? = [] + ) { + self.init( + id: id, username: username, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - username: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + username: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.username = username self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2+Schema.swift index 0c2d801a88..280cafde47 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Blog6V2 { +public extension Blog6V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts @@ -19,10 +19,10 @@ extension Blog6V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog6V2 = Blog6V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2.swift index 1d1c62c34c..b4cbf30247 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2.swift @@ -16,20 +16,26 @@ public struct Blog6V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2+Schema.swift index 2d8fe7959c..cb476aa8cc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment6V2 { +public extension Comment6V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post case content @@ -19,10 +19,10 @@ extension Comment6V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment6V2 = Comment6V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2.swift index f975f70fb2..027da3fbc5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2.swift @@ -16,20 +16,26 @@ public struct Comment6V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - post: Post6V2? = nil, - content: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + post: Post6V2? = nil, + content: String + ) { + self.init( + id: id, post: post, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - post: Post6V2? = nil, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + post: Post6V2? = nil, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.post = post self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2+Schema.swift index 5e96bf8cd9..8322b709e5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post6V2 { +public extension Post6V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case blog @@ -20,10 +20,10 @@ extension Post6V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post6V2 = Post6V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2.swift index bebe11af46..c955a6e87e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2.swift @@ -17,23 +17,29 @@ public struct Post6V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - blog: Blog6V2? = nil, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + blog: Blog6V2? = nil, + comments: List? = [] + ) { + self.init( + id: id, title: title, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - blog: Blog6V2? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + blog: Blog6V2? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.blog = blog diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2+Schema.swift index 84fa41ace3..5e2f6f64ca 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Blog7V2 { +public extension Blog7V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts @@ -19,10 +19,10 @@ extension Blog7V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog7V2 = Blog7V2.keys model.pluralName = "Blog7V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2.swift index e963392ee5..537cd210a4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2.swift @@ -16,20 +16,26 @@ public struct Blog7V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2+Schema.swift index 0f71ceb037..077286678f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment7V2 { +public extension Comment7V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post @@ -19,10 +19,10 @@ extension Comment7V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment7V2 = Comment7V2.keys model.pluralName = "Comment7V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2.swift index 317bef7b62..fa9b8c14ec 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2.swift @@ -16,20 +16,26 @@ public struct Comment7V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post7V2? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post7V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post7V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post7V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2+Schema.swift index e16552145c..18d5da8dc9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post7V2 { +public extension Post7V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case blog @@ -20,10 +20,10 @@ extension Post7V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post7V2 = Post7V2.keys model.pluralName = "Post7V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2.swift index a1cb3dfb84..e6fe9a9aab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2.swift @@ -17,23 +17,29 @@ public struct Post7V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - blog: Blog7V2? = nil, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + blog: Blog7V2? = nil, + comments: List? = [] + ) { + self.init( + id: id, title: title, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - blog: Blog7V2? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + blog: Blog7V2? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.blog = blog diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift index d77a61d5ee..aa10f9edd5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Attendee8V2 { +public extension Attendee8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case meetings case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let attendee8V2 = Attendee8V2.keys model.pluralName = "Attendee8V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2.swift index bdb90d7726..1ae9221f59 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2.swift @@ -15,17 +15,23 @@ public struct Attendee8V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - meetings: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + meetings: List? = [] + ) { + self.init( + id: id, meetings: meetings, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - meetings: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + meetings: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.meetings = meetings self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift index ea734e16d1..540f9e81b7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Meeting8V2 { +public extension Meeting8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case attendees @@ -19,10 +19,10 @@ extension Meeting8V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let meeting8V2 = Meeting8V2.keys model.pluralName = "Meeting8V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2.swift index 84abbbdd0c..8101985510 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2.swift @@ -16,20 +16,26 @@ public struct Meeting8V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - attendees: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + attendees: List? = [] + ) { + self.init( + id: id, title: title, attendees: attendees, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - attendees: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + attendees: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.attendees = attendees diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2+Schema.swift index 72355ba4ea..303c84d91b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Registration8V2 { +public extension Registration8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case meeting case attendee @@ -19,10 +19,10 @@ extension Registration8V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let registration8V2 = Registration8V2.keys model.pluralName = "Registration8V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2.swift index f9d2aa3b4b..3c572b4969 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2.swift @@ -16,20 +16,26 @@ public struct Registration8V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - meeting: Meeting8V2, - attendee: Attendee8V2) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + meeting: Meeting8V2, + attendee: Attendee8V2 + ) { + self.init( + id: id, meeting: meeting, attendee: attendee, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - meeting: Meeting8V2, - attendee: Attendee8V2, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + meeting: Meeting8V2, + attendee: Attendee8V2, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.meeting = meeting self.attendee = attendee diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift index f760ef2c9c..fae219e308 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CustomerMultipleSecondaryIndexV2 { +public extension CustomerMultipleSecondaryIndexV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case phoneNumber @@ -21,10 +21,10 @@ extension CustomerMultipleSecondaryIndexV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerMultipleSecondaryIndexV2 = CustomerMultipleSecondaryIndexV2.keys model.pluralName = "CustomerMultipleSecondaryIndexV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift index 7e92f12052..1c4e60e2d5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift @@ -18,26 +18,32 @@ public struct CustomerMultipleSecondaryIndexV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - age: Int, - accountRepresentativeID: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + age: Int, + accountRepresentativeID: String + ) { + self.init( + id: id, name: name, phoneNumber: phoneNumber, age: age, accountRepresentativeID: accountRepresentativeID, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - age: Int, - accountRepresentativeID: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + age: Int, + accountRepresentativeID: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.phoneNumber = phoneNumber diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift index 3058f7d566..1118ef8ca6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CustomerSecondaryIndexV2 { +public extension CustomerSecondaryIndexV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case phoneNumber @@ -20,10 +20,10 @@ extension CustomerSecondaryIndexV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerSecondaryIndexV2 = CustomerSecondaryIndexV2.keys model.pluralName = "CustomerSecondaryIndexV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2.swift index e6e0d76c04..195405ac60 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2.swift @@ -17,23 +17,29 @@ public struct CustomerSecondaryIndexV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - accountRepresentativeID: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + accountRepresentativeID: String + ) { + self.init( + id: id, name: name, phoneNumber: phoneNumber, accountRepresentativeID: accountRepresentativeID, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - accountRepresentativeID: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + accountRepresentativeID: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.phoneNumber = phoneNumber diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift index 40e8c0f7ce..021d8bfa84 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CustomerWithMultipleFieldsinPK { +public extension CustomerWithMultipleFieldsinPK { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case dob case date @@ -25,10 +25,10 @@ extension CustomerWithMultipleFieldsinPK { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerWithMultipleFieldsinPK = CustomerWithMultipleFieldsinPK.keys model.pluralName = "CustomerWithMultipleFieldsinPKs" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift index 32293d9975..0ae721e741 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift @@ -22,16 +22,19 @@ public struct CustomerWithMultipleFieldsinPK: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - date: Temporal.Date, - time: Temporal.Time, - phoneNumber: Int, - priority: Priority, - height: Double, - firstName: String? = nil, - lastName: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + date: Temporal.Date, + time: Temporal.Time, + phoneNumber: Int, + priority: Priority, + height: Double, + firstName: String? = nil, + lastName: String? = nil + ) { + self.init( + id: id, dob: dob, date: date, time: time, @@ -41,19 +44,22 @@ public struct CustomerWithMultipleFieldsinPK: Model { firstName: firstName, lastName: lastName, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - date: Temporal.Date, - time: Temporal.Time, - phoneNumber: Int, - priority: Priority, - height: Double, - firstName: String? = nil, - lastName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + date: Temporal.Date, + time: Temporal.Time, + phoneNumber: Int, + priority: Priority, + height: Double, + firstName: String? = nil, + lastName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.dob = dob self.date = date diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift index 03ace0efac..9f21d12e70 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Blog8 { +public extension Blog8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case customs @@ -21,10 +21,10 @@ extension Blog8 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog8 = Blog8.keys model.pluralName = "Blog8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8.swift index 92c1ccae48..48aa59e7fc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8.swift @@ -18,26 +18,32 @@ public struct Blog8: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [] + ) { + self.init( + id: id, name: name, customs: customs, notes: notes, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.customs = customs diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift index 6258c76ca6..f2e773e8ee 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment8 { +public extension Comment8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post @@ -19,10 +19,10 @@ extension Comment8 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment8 = Comment8.keys model.pluralName = "Comment8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8.swift index 4a0042140e..d6fa843ba3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8.swift @@ -16,20 +16,26 @@ public struct Comment8: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift index 27f611af59..85693fb8fa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension MyCustomModel8 { +public extension MyCustomModel8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case desc case children } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let myCustomModel8 = MyCustomModel8.keys model.pluralName = "MyCustomModel8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift index 1d18ede96f..206fee3987 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension MyNestedModel8 { +public extension MyNestedModel8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case nestedName case notes } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let myNestedModel8 = MyNestedModel8.keys model.pluralName = "MyNestedModel8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift index bd21917eb4..5cf1fb9e29 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post8 { +public extension Post8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case randomId @@ -21,10 +21,10 @@ extension Post8 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post8 = Post8.keys model.pluralName = "Post8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8.swift index 306eb3395b..09bec3b160 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8.swift @@ -18,26 +18,32 @@ public struct Post8: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8? = nil, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8? = nil, + comments: List? = [] + ) { + self.init( + id: id, name: name, randomId: randomId, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.randomId = randomId diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift index 5d527c5bdf..59af4deb74 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension SchemaDrift { +public extension SchemaDrift { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case enumValue case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let schemaDrift = SchemaDrift.keys model.pluralName = "SchemaDrifts" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift index dfac48fda6..b6159e7589 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift @@ -30,17 +30,23 @@ public struct SchemaDrift: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - enumValue: EnumDrift? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + enumValue: EnumDrift? = nil + ) { + self.init( + id: id, enumValue: enumValue, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - enumValue: EnumDrift? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + enumValue: EnumDrift? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.enumValue = enumValue self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift index 716f4848fe..2ed40a52b9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension TodoCustomTimestampV2 { +public extension TodoCustomTimestampV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdOn case updatedOn } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todoCustomTimestampV2 = TodoCustomTimestampV2.keys model.pluralName = "TodoCustomTimestampV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2.swift index 4bad844e17..97842a31a0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2.swift @@ -15,17 +15,23 @@ public struct TodoCustomTimestampV2: Model { public var createdOn: Temporal.DateTime? public var updatedOn: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdOn: nil, - updatedOn: nil) + updatedOn: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdOn: Temporal.DateTime? = nil, - updatedOn: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdOn: Temporal.DateTime? = nil, + updatedOn: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdOn = createdOn diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift index 6de5d45ae2..0e390adf51 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension TodoWithDefaultValueV2 { +public extension TodoWithDefaultValueV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todoWithDefaultValueV2 = TodoWithDefaultValueV2.keys model.pluralName = "TodoWithDefaultValueV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2.swift index dd622e15fc..75c66e59c2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2.swift @@ -15,17 +15,23 @@ public struct TodoWithDefaultValueV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreInternal.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreInternal.swift index 84e7fb7f9b..beae3433c0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreInternal.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreInternal.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import Foundation @testable import Amplify @testable import AWSDataStorePlugin -import Foundation -struct DataStoreInternal { +enum DataStoreInternal { static var dbFilePath: URL? { getAdapter()?.dbFilePath } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreTestBase.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreTestBase.swift index 35e47870b0..cfe22f662d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreTestBase.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation import XCTest -import Amplify class DataStoreTestBase: XCTestCase { func saveModel(_ model: M) async throws -> M { @@ -18,7 +18,7 @@ class DataStoreTestBase: XCTestCase { return try await Amplify.DataStore.query(modelType, byId: id) } - func deleteModel(_ model: M) async throws { + func deleteModel(_ model: some Model) async throws { try await Amplify.DataStore.delete(model) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/SyncEngineIntegrationV2TestBase.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/SyncEngineIntegrationV2TestBase.swift index 7ff6649ed0..14dae15b13 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/SyncEngineIntegrationV2TestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/SyncEngineIntegrationV2TestBase.swift @@ -54,11 +54,15 @@ class SyncEngineIntegrationV2TestBase: DataStoreTestBase { sessionFactory: AmplifyURLSessionFactory() )) #if os(watchOS) - try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, - configuration: .custom(syncMaxRecords: 100, disableSubscriptions: { false }))) + try Amplify.add(plugin: AWSDataStorePlugin( + modelRegistration: models, + configuration: .custom(syncMaxRecords: 100, disableSubscriptions: { false }) + )) #else - try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, - configuration: .custom(syncMaxRecords: 100))) + try Amplify.add(plugin: AWSDataStorePlugin( + modelRegistration: models, + configuration: .custom(syncMaxRecords: 100) + )) #endif } catch { XCTFail(String(describing: error)) @@ -99,8 +103,10 @@ class SyncEngineIntegrationV2TestBase: DataStoreTestBase { let eventReceived = expectation(description: "DataStore \(eventName) event") var token: UnsubscribeToken! - token = Amplify.Hub.listen(to: .dataStore, - eventName: eventName) { _ in + token = Amplify.Hub.listen( + to: .dataStore, + eventName: eventName + ) { _ in eventReceived.fulfill() Amplify.Hub.removeListener(token) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionOptionalAssociations.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionOptionalAssociations.swift index 86c9fdc040..47855ad01f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionOptionalAssociations.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionOptionalAssociations.swift @@ -205,7 +205,7 @@ class DataStoreConnectionOptionalAssociations: SyncEngineIntegrationV2TestBase { XCTAssertEqual(queriedComment.post?.blog?.id, blog.id) XCTAssertNotNil(queriedPost.blog) XCTAssertEqual(queriedPost.blog?.id, blog.id) - + queriedComment.post = nil // A mock GraphQL request is created to assert that the request variables contains the "postId" // with the value `nil` which is sent to the API to persist the removal of the association. @@ -217,7 +217,7 @@ class DataStoreConnectionOptionalAssociations: SyncEngineIntegrationV2TestBase { XCTFail("Failed to retrieve input object from GraphQL variables") return } - + guard try await saveComment(queriedComment) != nil else { XCTFail("Failed to update comment") return @@ -226,15 +226,15 @@ class DataStoreConnectionOptionalAssociations: SyncEngineIntegrationV2TestBase { XCTFail("Failed to query comment without post") return } - + XCTAssertNil(queriedCommentWithoutPost.post) - + queriedPost.blog = nil guard try await savePost(queriedPost) != nil else { XCTFail("Failed to update post") return } - + guard let queriedPostWithoutBlog = try await queryPost(id: post.id) else { XCTFail("Failed to query post") return @@ -251,7 +251,7 @@ class DataStoreConnectionOptionalAssociations: SyncEngineIntegrationV2TestBase { func saveComment(_ comment: Comment8? = nil, withPost post: Post8? = nil) async throws -> Comment8? { let commentToSave: Comment8 - if let comment = comment { + if let comment { commentToSave = comment } else { commentToSave = Comment8(content: "content", post: post) @@ -279,7 +279,7 @@ class DataStoreConnectionOptionalAssociations: SyncEngineIntegrationV2TestBase { func savePost(_ post: Post8? = nil, withBlog blog: Blog8? = nil) async throws -> Post8? { let postToSave: Post8 - if let post = post { + if let post { postToSave = post } else { postToSave = Post8(name: "name", randomId: "randomId", blog: blog) @@ -307,16 +307,20 @@ class DataStoreConnectionOptionalAssociations: SyncEngineIntegrationV2TestBase { func saveBlog(_ blog: Blog8? = nil) async throws -> Blog8? { let blogToSave: Blog8 - if let blog = blog { + if let blog { blogToSave = blog } else { - let nestedModel = MyNestedModel8(id: UUID().uuidString, - nestedName: "nestedName", - notes: ["notes1", "notes2"]) - let customModel = MyCustomModel8(id: UUID().uuidString, - name: "name", - desc: "desc", - children: [nestedModel]) + let nestedModel = MyNestedModel8( + id: UUID().uuidString, + nestedName: "nestedName", + notes: ["notes1", "notes2"] + ) + let customModel = MyCustomModel8( + id: UUID().uuidString, + name: "name", + desc: "desc", + children: [nestedModel] + ) blogToSave = Blog8(name: "name", customs: [customModel], notes: ["notes1", "notes2"]) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario1V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario1V2Tests.swift index 4bdfa9c164..0ab86a8ab8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario1V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario1V2Tests.swift @@ -47,10 +47,12 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { let team = Team1V2(name: "name1") // TODO: No need to add the `team` into the project, it is using explicit field `project1V2TeamId` let project = Project1V2(team: team, project1V2TeamId: team.id) - + let syncedTeamReceived = expectation(description: "received team from sync path") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -68,10 +70,12 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { _ = try await Amplify.DataStore.save(team) await fulfillment(of: [syncedTeamReceived], timeout: TestCommonConstants.networkTimeout) - + let syncProjectReceived = expectation(description: "received project from sync path") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -84,12 +88,12 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { syncProjectReceived.fulfill() } } - + guard try await HubListenerTestUtilities.waitForListener(with: hubListener, timeout: 5.0) else { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(project) await fulfillment(of: [syncProjectReceived], timeout: TestCommonConstants.networkTimeout) @@ -109,18 +113,22 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { let anotherTeam = Team1V2(name: "name1") // TODO: No need to add the `team` into the project, it is using explicit field `project1V2TeamId` var project = Project1V2(team: team, project1V2TeamId: team.id) - let expectedUpdatedProject = Project1V2(id: project.id, - name: project.name, - team: anotherTeam, // Not needed - project1V2TeamId: anotherTeam.id) - + let expectedUpdatedProject = Project1V2( + id: project.id, + name: project.name, + team: anotherTeam, // Not needed + project1V2TeamId: anotherTeam.id + ) + _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(anotherTeam) _ = try await Amplify.DataStore.save(project) - + let syncUpdatedProjectReceived = expectation(description: "received updated project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -156,14 +164,16 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { func testCreateUpdateDeleteAndGetProjectReturnsNil() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team1V2(name: "name") var project = Project1V2(team: team, project1V2TeamId: team.id) let createReceived = expectation(description: "received created items from cloud") createReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -192,8 +202,10 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let updateReceived = expectation(description: "received update project from sync path") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -211,15 +223,17 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + project.name = "updatedName" _ = try await Amplify.DataStore.save(project) await fulfillment(of: [updateReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "Delete notification received") deleteReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -242,7 +256,7 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { return } _ = try await Amplify.DataStore.delete(project) - + // TODO: Delete Team should not be necessary, cascade delete should delete the team when deleting the project. // Once cascade works for hasOne, the following code can be removed. _ = try await Amplify.DataStore.delete(team) @@ -260,11 +274,13 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { let team = Team1V2(name: "name") let project = Project1V2(team: team, project1V2TeamId: team.id) - + let createReceived = expectation(description: "received created items from cloud") createReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -288,16 +304,18 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "Delete notification received") deleteReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -335,14 +353,14 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { func testDeleteWithValidCondition() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team1V2(name: "name") let project = Project1V2(team: team, project1V2TeamId: team.id) _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + _ = try await Amplify.DataStore.delete(project, where: Project1V2.keys.team.eq(team.id)) - + let queriedProject = try await Amplify.DataStore.query(Project1V2.self, byId: project.id) XCTAssertNil(queriedProject) } @@ -350,7 +368,7 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { func testDeleteWithInvalidCondition() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team1V2(name: "name") let project = Project1V2(team: team, project1V2TeamId: team.id) _ = try await Amplify.DataStore.save(team) @@ -379,7 +397,7 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { let project = Project1V2(team: team, project1V2TeamId: team.id) _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + let predicate = Project1V2.keys.team.eq(team.id) let projects = try await Amplify.DataStore.query(Project1V2.self, where: predicate) XCTAssertEqual(projects.count, 1) @@ -389,8 +407,10 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { } extension Team1V2: Equatable { - public static func == (lhs: Team1V2, - rhs: Team1V2) -> Bool { + public static func == ( + lhs: Team1V2, + rhs: Team1V2 + ) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario2V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario2V2Tests.swift index 5c30589420..12b8d98210 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario2V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario2V2Tests.swift @@ -49,9 +49,11 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { let team = Team2V2(name: "name1") let project = Project2V2(teamID: team.id, team: team) let syncedTeamReceived = expectation(description: "received team from sync event") - - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -66,13 +68,15 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(team) await fulfillment(of: [syncedTeamReceived], timeout: TestCommonConstants.networkTimeout) - + let syncProjectReceived = expectation(description: "received project from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -84,7 +88,7 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { syncProjectReceived.fulfill() } } - + _ = try await Amplify.DataStore.save(project) await fulfillment(of: [syncProjectReceived], timeout: TestCommonConstants.networkTimeout) @@ -103,14 +107,16 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { let anotherTeam = Team2V2(name: "name1") var project = Project2V2(teamID: team.id, team: team) let expectedUpdatedProject = Project2V2(id: project.id, name: project.name, teamID: anotherTeam.id) - + _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(anotherTeam) _ = try await Amplify.DataStore.save(project) - + let syncUpdatedProjectReceived = expectation(description: "received updated project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -121,7 +127,7 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { syncUpdatedProjectReceived.fulfill() } } - + guard try await HubListenerTestUtilities.waitForListener(with: hubListener, timeout: 5.0) else { XCTFail("Listener not registered for hub") return @@ -143,14 +149,16 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { func testCreateUpdateDeleteAndGetProjectReturnsNil() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team2V2(name: "name") var project = Project2V2(teamID: team.id, team: team) - + let createReceived = expectation(description: "received created items from cloud") createReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -169,7 +177,7 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { } } } - + guard try await HubListenerTestUtilities.waitForListener(with: hubListener, timeout: 5.0) else { XCTFail("Listener not registered for hub") return @@ -178,10 +186,12 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let updateReceived = expectation(description: "received update project from sync path") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -199,15 +209,17 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + project.name = "updatedName" _ = try await Amplify.DataStore.save(project) await fulfillment(of: [updateReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "received deleted project from sync path") deleteReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -234,7 +246,7 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { // Once cascade works for hasOne, the following code can be removed. _ = try await Amplify.DataStore.delete(team) await fulfillment(of: [deleteReceived], timeout: TestCommonConstants.networkTimeout) - + let queriedProject = try await Amplify.DataStore.query(Project2V2.self, byId: project.id) XCTAssertNil(queriedProject) @@ -248,12 +260,14 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { let team = Team2V2(name: "name") let project = Project2V2(teamID: team.id, team: team) - + let createReceived = expectation(description: "received created items from cloud") createReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -276,16 +290,18 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "Delete notification received") deleteReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -326,12 +342,12 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { let team = Team2V2(name: "name") let project = Project2V2(teamID: team.id, team: team) - + _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + _ = try await Amplify.DataStore.delete(project, where: Project2V2.keys.team.eq(team.id)) - + let queriedProject = try await Amplify.DataStore.query(Project2V2.self, byId: project.id) XCTAssertNil(queriedProject) } @@ -339,12 +355,12 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { func testDeleteWithInvalidCondition() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team2V2(name: "name") let project = Project2V2(teamID: team.id, team: team) _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + do { _ = try await Amplify.DataStore.delete(project, where: Project2V2.keys.teamID.eq("invalidTeamId")) XCTFail("Should have failed") @@ -356,7 +372,7 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { } catch { throw error } - + let queriedProject = try await Amplify.DataStore.query(Project2V2.self, byId: project.id) XCTAssertNotNil(queriedProject) } @@ -364,15 +380,15 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { func testDeleteAlreadyDeletedItemWithCondition() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team2V2(name: "name") let project = Project2V2(teamID: team.id, team: team) - + _ = try await Amplify.DataStore.delete(project) - + let queriedProjectOptional = try await Amplify.DataStore.query(Project2V2.self, byId: project.id) XCTAssertNil(queriedProjectOptional) - + _ = try await Amplify.DataStore.delete(project, where: Project2V2.keys.teamID == team.id) } @@ -384,7 +400,7 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { let project = Project2V2(teamID: team.id, team: team) _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + let predicate = Project2V2.keys.teamID.eq(team.id) let projects = try await Amplify.DataStore.query(Project2V2.self, where: predicate) XCTAssertEqual(projects.count, 1) @@ -394,8 +410,10 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { } extension Team2V2: Equatable { - public static func == (lhs: Team2V2, - rhs: Team2V2) -> Bool { + public static func == ( + lhs: Team2V2, + rhs: Team2V2 + ) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3V2Tests.swift index 2ca3fa52a2..e82fc6d841 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3V2Tests.swift @@ -48,8 +48,10 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let comment = Comment3V2(postID: post.id, content: "content") let syncedPostReceived = expectation(description: "received post from sync event") let syncCommentReceived = expectation(description: "received comment from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -67,11 +69,11 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) await fulfillment(of: [syncedPostReceived, syncCommentReceived], timeout: TestCommonConstants.networkTimeout) - + let queriedComment = try await Amplify.DataStore.query(Comment3V2.self, byId: comment.id) XCTAssertEqual(queriedComment, comment) } @@ -84,7 +86,7 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let comment = Comment3V2(postID: post.id, content: "content") _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + let queriedPostOptional = try await Amplify.DataStore.query(Post3V2.self, byId: post.id) guard let queriedPost = queriedPostOptional else { XCTFail("Could not get post") @@ -123,9 +125,9 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let comment = Comment3V2(postID: post.id, content: "content") _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + _ = try await Amplify.DataStore.delete(comment) - + let queriedComment = try await Amplify.DataStore.query(Comment3V2.self, byId: comment.id) XCTAssertNil(queriedComment) } @@ -138,7 +140,7 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let comment = Comment3V2(postID: post.id, content: "content") _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + let predicate = Comment3V2.keys.postID.eq(post.id) let queriedComments = try await Amplify.DataStore.query(Comment3V2.self, where: predicate) XCTAssertEqual(queriedComments.count, 1) @@ -151,8 +153,10 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let post = Post3V2(title: "title") let createReceived = expectation(description: "received post from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -180,8 +184,10 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { var post = Post3V2(title: "title") let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -201,12 +207,14 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { } _ = try await Amplify.DataStore.save(post) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let updatedTitle = "updatedTitle" post.title = updatedTitle let updateReceived = expectation(description: "received updated post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -230,10 +238,12 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() let post = Post3V2(title: "title") - + let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -255,8 +265,10 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let deleteReceived = expectation(description: "received deleted post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -274,7 +286,7 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.delete(post) await fulfillment(of: [deleteReceived], timeout: TestCommonConstants.networkTimeout) } @@ -285,11 +297,13 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let post = Post3V2(title: "title") let comment = Comment3V2(postID: post.id, content: "content") - + let createReceived = expectation(description: "received created from sync event") createReceived.expectedFulfillmentCount = 2 // 1 post and 1 comment - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -319,8 +333,10 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "received deleted from sync event") deleteReceived.expectedFulfillmentCount = 2 // 1 post and 1 comment - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -340,7 +356,7 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { } } } - + _ = try await Amplify.DataStore.delete(post) // TODO: Deleting the comment should not be necessary. Cascade delete is not working _ = try await Amplify.DataStore.delete(comment) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3aV2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3aV2Tests.swift index 18fae1693e..bb56879cb8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3aV2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3aV2Tests.swift @@ -47,8 +47,10 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let comment = Comment3aV2(content: "content", post3aV2CommentsId: post.id) let syncedPostReceived = expectation(description: "received post from sync event") let syncCommentReceived = expectation(description: "received comment from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -66,12 +68,12 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + await fulfillment(of: [syncedPostReceived, syncCommentReceived], timeout: TestCommonConstants.networkTimeout) - + let queriedComment = try await Amplify.DataStore.query(Comment3aV2.self, byId: comment.id) XCTAssertEqual(queriedComment, comment) } @@ -82,22 +84,22 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let post = Post3aV2(title: "title") let comment = Comment3aV2(content: "content", post3aV2CommentsId: post.id) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + let queriedPostOptional = try await Amplify.DataStore.query(Post3aV2.self, byId: post.id) guard let queriedPost = queriedPostOptional else { XCTFail("Could not get post") return } XCTAssertEqual(queriedPost.id, post.id) - + guard let comments = queriedPost.comments else { XCTFail("Could not get comments") return } - + try await comments.fetch() XCTAssertEqual(comments.count, 1) XCTAssertEqual(comments[0], comment) @@ -110,11 +112,11 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let post = Post3aV2(title: "title") var comment = Comment3aV2(content: "content", post3aV2CommentsId: post.id) let anotherPost = Post3aV2(title: "title") - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) _ = try await Amplify.DataStore.save(anotherPost) - + comment.post3aV2CommentsId = anotherPost.id let updatedComment = try await Amplify.DataStore.save(comment) XCTAssertEqual(updatedComment.post3aV2CommentsId, anotherPost.id) @@ -123,15 +125,15 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { func testDeleteAndGetComment() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let post = Post3aV2(title: "title") let comment = Comment3aV2(content: "content", post3aV2CommentsId: post.id) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + _ = try await Amplify.DataStore.delete(comment) - + let queriedComment = try await Amplify.DataStore.query(Comment3aV2.self, byId: comment.id) XCTAssertNil(queriedComment) } @@ -142,10 +144,10 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let post = Post3aV2(title: "title") let comment = Comment3aV2(content: "content", post3aV2CommentsId: post.id) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + let predicate = Comment3aV2.keys.post3aV2CommentsId.eq(post.id) let queriedComments = try await Amplify.DataStore.query(Comment3aV2.self, where: predicate) XCTAssertEqual(queriedComments.count, 1) @@ -158,8 +160,10 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let post = Post3aV2(title: "title") let createReceived = expectation(description: "received post from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -174,7 +178,7 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(post) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) @@ -188,8 +192,10 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { var post = Post3aV2(title: "title") let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -207,19 +213,21 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(post) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let updateReceived = expectation(description: "received updated post from sync event") let updatedTitle = "updatedTitle" - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return } - + if let syncedPost = try? mutationEvent.decodeModel() as? Post3aV2, syncedPost == post { if mutationEvent.mutationType == GraphQLMutationType.update.rawValue { @@ -229,12 +237,12 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { } } } - + guard try await HubListenerTestUtilities.waitForListener(with: hubListener, timeout: 5.0) else { XCTFail("Listener not registered for hub") return } - + post.title = updatedTitle _ = try await Amplify.DataStore.save(post) await fulfillment(of: [updateReceived], timeout: TestCommonConstants.networkTimeout) @@ -245,10 +253,12 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() let post = Post3aV2(title: "title") - + let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -270,8 +280,10 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let deleteReceived = expectation(description: "received deleted post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -290,11 +302,11 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.delete(post) await fulfillment(of: [deleteReceived], timeout: TestCommonConstants.networkTimeout) } - + func testDeletePostCascadeToComments() async throws { await setUp(withModels: TestModelRegistration()) @@ -302,11 +314,13 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let post = Post3aV2(title: "title") let comment = Comment3aV2(content: "content", post3aV2CommentsId: post.id) - + let createReceived = expectation(description: "received created from sync event") createReceived.expectedFulfillmentCount = 2 // 1 post and 1 comment - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -336,8 +350,10 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "received deleted from sync event") deleteReceived.expectedFulfillmentCount = 2 // 1 post and 1 comment - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -361,7 +377,7 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.delete(post) // TODO: Deleting the comment should not be necessary. Cascade delete is not working _ = try await Amplify.DataStore.delete(comment) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario4V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario4V2Tests.swift index 0b2c2e9714..eeadeb9498 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario4V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario4V2Tests.swift @@ -63,7 +63,7 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { func testCreateCommentAndGetPostWithComments() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let post = Post4V2(title: "title") let comment = Comment4V2(content: "content", post: post) @@ -76,7 +76,7 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { return } XCTAssertEqual(queriedPost.id, post.id) - + guard let queriedComments = queriedPost.comments else { XCTFail("Could not get comments") return @@ -89,15 +89,15 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { func testUpdateComment() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let post = Post4V2(title: "title") var comment = Comment4V2(content: "content", post: post) let anotherPost = Post4V2(title: "title") - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) _ = try await Amplify.DataStore.save(anotherPost) - + comment.post = anotherPost let updatedComment = try await Amplify.DataStore.save(comment) XCTAssertEqual(updatedComment.post, anotherPost) @@ -106,10 +106,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { func testDeleteAndGetComment() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let post = Post4V2(title: "title") let comment = Comment4V2(content: "content", post: post) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) @@ -121,13 +121,13 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { func testListCommentsByPostID() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let post = Post4V2(title: "title") let comment = Comment4V2(content: "content", post: post) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + let predicate = Comment4V2.keys.post.eq(post.id) let comments = try await Amplify.DataStore.query(Comment4V2.self, where: predicate) XCTAssertEqual(comments.count, 1) @@ -140,8 +140,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { let post = Post4V2(title: "title") let createReceived = expectation(description: "received post from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -152,7 +154,7 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { createReceived.fulfill() } } - + guard try await HubListenerTestUtilities.waitForListener(with: hubListener, timeout: 5.0) else { XCTFail("Listener not registered for hub") return @@ -170,8 +172,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { var post = Post4V2(title: "title") let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -194,8 +198,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { let updatedTitle = "updatedTitle" let updateReceived = expectation(description: "received updated post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -214,7 +220,7 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + post.title = updatedTitle _ = try await Amplify.DataStore.save(post) await fulfillment(of: [updateReceived], timeout: TestCommonConstants.networkTimeout) @@ -225,10 +231,12 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() let post = Post4V2(title: "title") - + let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -250,8 +258,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let deleteReceived = expectation(description: "received deleted post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -280,11 +290,13 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { let post = Post4V2(title: "title") let comment = Comment4V2(content: "content", post: post) - + let createReceived = expectation(description: "received created from sync event") createReceived.expectedFulfillmentCount = 2 // 1 post and 1 comment - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -314,8 +326,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "received deleted from sync event") deleteReceived.expectedFulfillmentCount = 2 // 1 post and 1 comment - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -345,8 +359,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { } extension Post4V2: Equatable { - public static func == (lhs: Post4V2, - rhs: Post4V2) -> Bool { + public static func == ( + lhs: Post4V2, + rhs: Post4V2 + ) -> Bool { return lhs.id == rhs.id && lhs.title == rhs.title } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario5V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario5V2Tests.swift index 6cafde9e9a..673b3d8902 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario5V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario5V2Tests.swift @@ -45,15 +45,15 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { func testListPostEditorByPost() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let post = Post5V2(title: "title") let user = User5V2(username: "username") let postEditor = PostEditor5V2(post5V2: post, user5V2: user) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(user) _ = try await Amplify.DataStore.save(postEditor) - + let predicateByPostId = PostEditor5V2.keys.post5V2.eq(post.id) let queriedPostEditor = try await Amplify.DataStore.query(PostEditor5V2.self, where: predicateByPostId) XCTAssertNotNil(queriedPostEditor) @@ -65,11 +65,11 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let post = Post5V2(title: "title") let user = User5V2(username: "username") let postEditor = PostEditor5V2(post5V2: post, user5V2: user) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(user) _ = try await Amplify.DataStore.save(postEditor) - + let predicateByUserId = PostEditor5V2.keys.user5V2.eq(user.id) let queriedPostEditor = try await Amplify.DataStore.query(PostEditor5V2.self, where: predicateByUserId) XCTAssertNotNil(queriedPostEditor) @@ -81,18 +81,18 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let post = Post5V2(title: "title") let user = User5V2(username: "username") let postEditor = PostEditor5V2(post5V2: post, user5V2: user) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(user) _ = try await Amplify.DataStore.save(postEditor) - + let queriedPostOptional = try await Amplify.DataStore.query(Post5V2.self, byId: post.id) guard let queriedPost = queriedPostOptional else { XCTFail("Missing queried post") return } XCTAssertEqual(queriedPost.id, post.id) - + guard let editors = queriedPost.editors else { XCTFail("Missing editors") return @@ -107,11 +107,11 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let post = Post5V2(title: "title") let user = User5V2(username: "username") let postEditor = PostEditor5V2(post5V2: post, user5V2: user) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(user) _ = try await Amplify.DataStore.save(postEditor) - + let queriedUserOptional = try await Amplify.DataStore.query(User5V2.self, byId: user.id) guard let queriedUser = queriedUserOptional else { XCTFail("Missing queried user") @@ -132,8 +132,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let post = Post5V2(title: "title") let createReceived = expectation(description: "received post from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -161,8 +163,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { var post = Post5V2(title: "title") let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -186,8 +190,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let updateReceived = expectation(description: "received updated post from sync event") let updatedTitle = "updatedTitle" post.title = updatedTitle - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -202,7 +208,7 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { } } } - + _ = try await Amplify.DataStore.save(post) await fulfillment(of: [updateReceived], timeout: TestCommonConstants.networkTimeout) } @@ -213,8 +219,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let post = Post5V2(title: "title") let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -236,8 +244,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let deleteReceived = expectation(description: "received deleted post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -270,8 +280,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let createReceived = expectation(description: "received created from sync event") createReceived.expectedFulfillmentCount = 3 // 1 post, 1 user, 1 postEditor - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -308,8 +320,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "received deleted from sync event") deleteReceived.expectedFulfillmentCount = 2 // 1 post, 1 postEditor - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario6V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario6V2Tests.swift index 6fd35b638c..8ffb6b6a85 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario6V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario6V2Tests.swift @@ -58,7 +58,8 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { let post1 = await savePost(title: "title", blog: blog), let _ = await savePost(title: "title", blog: blog), let comment1post1 = await saveComment(post: post1, content: "content"), - let comment2post1 = await saveComment(post: post1, content: "content") else { + let comment2post1 = await saveComment(post: post1, content: "content") + else { XCTFail("Could not create blog, posts, and comments") return } @@ -70,27 +71,27 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { } XCTAssertEqual(queriedBlog.id, blog.id) resultPosts = queriedBlog.posts - + guard let posts = resultPosts else { XCTFail("Could not get posts") return } - + try await posts.fetch() XCTAssertEqual(posts.count, 2) - guard let fetchedPost = posts.first(where: { (post) -> Bool in + guard let fetchedPost = posts.first(where: { post -> Bool in post.id == post1.id }), let comments = fetchedPost.comments else { XCTFail("Could not set up - failed to get a post and its comments") return } - + try await comments.fetch() XCTAssertEqual(comments.count, 2) - XCTAssertTrue(comments.contains(where: { (comment) -> Bool in + XCTAssertTrue(comments.contains(where: { comment -> Bool in comment.id == comment1post1.id })) - XCTAssertTrue(comments.contains(where: { (comment) -> Bool in + XCTAssertTrue(comments.contains(where: { comment -> Bool in comment.id == comment2post1.id })) if let post = comments[0].post { @@ -104,7 +105,8 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, post, and comment") return } @@ -138,11 +140,12 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, post, and comment") return } - + let queriedPostOptional = try await Amplify.DataStore.query(Post6V2.self, byId: post.id) guard let queriedPost = queriedPostOptional else { XCTFail("Could not get post") @@ -160,7 +163,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { if let postsInEagerlyLoadedBlog = eagerlyLoadedBlog.posts { try await postsInEagerlyLoadedBlog.fetch() XCTAssertEqual(postsInEagerlyLoadedBlog.count, 1) - XCTAssertTrue(postsInEagerlyLoadedBlog.contains(where: {(postIn) -> Bool in + XCTAssertTrue(postsInEagerlyLoadedBlog.contains(where: {postIn -> Bool in postIn.id == post.id })) XCTAssertEqual(postsInEagerlyLoadedBlog[0].id, post.id) @@ -195,7 +198,8 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { let createReceived = expectation(description: "Create notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -216,7 +220,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + let queriedBlogOptional = try await Amplify.DataStore.query(Blog6V2.self, byId: blog.id) guard let queriedBlog = queriedBlogOptional else { XCTFail("Could not get blog") @@ -232,16 +236,18 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { guard let blog = await saveBlog(name: "name"), let post1 = await savePost(title: "title", blog: blog), - let post2 = await savePost(title: "title", blog: blog) else { + let post2 = await savePost(title: "title", blog: blog) + else { XCTFail("Could not create blog, posts") return } - + let createReceived = expectation(description: "Create notification received") createReceived.expectedFulfillmentCount = 3 // 3 models (1 blog and 2 posts) let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -276,7 +282,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + var resultPosts: List? let queriedBlogOptional = try await Amplify.DataStore.query(Blog6V2.self, byId: blog.id) guard let queriedBlog = queriedBlogOptional else { @@ -297,19 +303,21 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { func testSaveBlogPostComment() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, posts, and comments") return } - + let createReceived = expectation(description: "Create notification received") createReceived.expectedFulfillmentCount = 3 // 3 models (1 blog and 1 post and 1 comment) let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -344,7 +352,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + var resultPosts: List? let queriedBlogOptional = try await Amplify.DataStore.query(Blog6V2.self, byId: blog.id) guard let queriedBlog = queriedBlogOptional else { @@ -353,14 +361,14 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { } XCTAssertEqual(queriedBlog.id, blog.id) resultPosts = queriedBlog.posts - + guard let posts = resultPosts else { XCTFail("Could not get posts") return } try await posts.fetch() XCTAssertEqual(posts.count, 1) - guard let fetchedPost = posts.first(where: { (postFetched) -> Bool in + guard let fetchedPost = posts.first(where: { postFetched -> Bool in postFetched.id == post.id }), let comments = fetchedPost.comments else { XCTFail("Could not set up - failed to get a post and its comments") @@ -368,7 +376,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { } try await comments.fetch() XCTAssertEqual(comments.count, 1) - XCTAssertTrue(comments.contains(where: { (commentFetched) -> Bool in + XCTAssertTrue(comments.contains(where: { commentFetched -> Bool in commentFetched.id == comment.id })) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) @@ -379,7 +387,8 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, posts, and comments") return } @@ -387,7 +396,8 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 blog and 1 post and 1 comment) var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -423,7 +433,8 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { deleteReceived.expectedFulfillmentCount = 3 // 3 models due to cascade delete behavior hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -450,7 +461,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.delete(blog) await fulfillment(of: [deleteReceived], timeout: TestCommonConstants.networkTimeout) @@ -461,7 +472,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { var result: Blog6V2? do { result = try await Amplify.DataStore.save(blog) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result @@ -472,7 +483,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { var result: Post6V2? do { result = try await Amplify.DataStore.save(post) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result @@ -483,7 +494,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { var result: Comment6V2? do { result = try await Amplify.DataStore.save(comment) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario7V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario7V2Tests.swift index 965c4ffe53..23de02b50b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario7V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario7V2Tests.swift @@ -53,7 +53,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { let post1 = await savePost(title: "title", blog: blog), let _ = await savePost(title: "title", blog: blog), let comment1post1 = await saveComment(post: post1, content: "content"), - let comment2post1 = await saveComment(post: post1, content: "content") else { + let comment2post1 = await saveComment(post: post1, content: "content") + else { XCTFail("Could not create blog, posts, and comments") return } @@ -64,28 +65,28 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { return } XCTAssertEqual(queriedBlog.id, blog.id) - + resultPosts = queriedBlog.posts guard let posts = resultPosts else { XCTFail("Could not get posts") return } - + try await posts.fetch() XCTAssertEqual(posts.count, 2) - guard let fetchedPost = posts.first(where: { (post) -> Bool in + guard let fetchedPost = posts.first(where: { post -> Bool in post.id == post1.id }), let comments = fetchedPost.comments else { XCTFail("Could not set up - failed to get a post and its comments") return } - + try await comments.fetch() XCTAssertEqual(comments.count, 2) - XCTAssertTrue(comments.contains(where: { (comment) -> Bool in + XCTAssertTrue(comments.contains(where: { comment -> Bool in comment.id == comment1post1.id })) - XCTAssertTrue(comments.contains(where: { (comment) -> Bool in + XCTAssertTrue(comments.contains(where: { comment -> Bool in comment.id == comment2post1.id })) if let post = comments[0].post { @@ -99,7 +100,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, post, and comment") return } @@ -133,7 +135,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, post, and comment") return } @@ -155,7 +158,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { if let postsInEagerlyLoadedBlog = eagerlyLoadedBlog.posts { try await postsInEagerlyLoadedBlog.fetch() XCTAssertEqual(postsInEagerlyLoadedBlog.count, 1) - XCTAssertTrue(postsInEagerlyLoadedBlog.contains(where: {(postIn) -> Bool in + XCTAssertTrue(postsInEagerlyLoadedBlog.contains(where: {postIn -> Bool in postIn.id == post.id })) XCTAssertEqual(postsInEagerlyLoadedBlog[0].id, post.id) @@ -190,7 +193,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { let createReceived = expectation(description: "Create notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -225,7 +229,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post1 = await savePost(title: "title", blog: blog), - let post2 = await savePost(title: "title", blog: blog) else { + let post2 = await savePost(title: "title", blog: blog) + else { XCTFail("Could not create blog, posts") return } @@ -233,7 +238,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 blog and 2 posts) let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -277,7 +283,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { } XCTAssertEqual(queriedBlog.id, blog.id) resultPosts = queriedBlog.posts - + guard let posts = resultPosts else { XCTFail("Could not get posts") return @@ -292,7 +298,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, posts, and comments") return } @@ -300,7 +307,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 blog and 1 post and 1 comment) let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -335,7 +343,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + var resultPosts: List? let queriedBlogOptional = try await Amplify.DataStore.query(Blog7V2.self, byId: blog.id) guard let queriedBlog = queriedBlogOptional else { @@ -344,14 +352,14 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { } XCTAssertEqual(queriedBlog.id, blog.id) resultPosts = queriedBlog.posts - + guard let posts = resultPosts else { XCTFail("Could not get posts") return } try await posts.fetch() XCTAssertEqual(posts.count, 1) - guard let fetchedPost = posts.first(where: { (postFetched) -> Bool in + guard let fetchedPost = posts.first(where: { postFetched -> Bool in postFetched.id == post.id }), let comments = fetchedPost.comments else { XCTFail("Could not set up - failed to get a post and its comments") @@ -359,7 +367,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { } try await comments.fetch() XCTAssertEqual(comments.count, 1) - XCTAssertTrue(comments.contains(where: { (commentFetched) -> Bool in + XCTAssertTrue(comments.contains(where: { commentFetched -> Bool in commentFetched.id == comment.id })) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) @@ -370,14 +378,17 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), - var post = await savePost(title: "title", blog: blog) else { + var post = await savePost(title: "title", blog: blog) + else { XCTFail("Could not create blog and post") return } let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -400,8 +411,10 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { let updateReceived = expectation(description: "received updated post from sync event") let updatedTitle = "updatedTitle" post.title = updatedTitle - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -428,14 +441,17 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), - let post = await savePost(title: "title", blog: blog) else { + let post = await savePost(title: "title", blog: blog) + else { XCTFail("Could not create blog and post") return } - + let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -454,10 +470,12 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { return } await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "received deleted post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -484,14 +502,17 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, posts, and comments") return } let createReceived = expectation(description: "received created from sync event") createReceived.expectedFulfillmentCount = 3 // 1 blog, 1 post, 1 comment - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -527,8 +548,10 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "received deleted from sync event") deleteReceived.expectedFulfillmentCount = 3 // 1 blog, 1 post, 1 comment - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -566,7 +589,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { var result: Blog7V2? do { result = try await Amplify.DataStore.save(blog) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result @@ -577,7 +600,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { var result: Post7V2? do { result = try await Amplify.DataStore.save(post) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result @@ -588,7 +611,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { var result: Comment7V2? do { result = try await Amplify.DataStore.save(comment) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario8V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario8V2Tests.swift index 03734fc643..c2e60d2d2a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario8V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario8V2Tests.swift @@ -55,7 +55,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let attendee = await saveAttendee(), let meeting = await saveMeeting(), - let registration = await saveRegistration(meeting: meeting, attendee: attendee) else { + let registration = await saveRegistration(meeting: meeting, attendee: attendee) + else { XCTFail("Could not create attendee, meeting, registration") return } @@ -63,7 +64,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 attendee and 1 meeting and 1 registration) let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -107,7 +109,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } try await queriedAttendee.meetings?.fetch() XCTAssertEqual(queriedAttendee.meetings?.count, 1) - + let queriedMeetingOptional = try await Amplify.DataStore.query(Meeting8V2.self, byId: meeting.id) guard let queriedMeeting = queriedMeetingOptional else { XCTFail("Could not get meeting") @@ -131,7 +133,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 4 // 4 models (2 attendees and 1 meeting and 1 registration) var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -169,11 +172,12 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { return } await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let updateReceived = expectation(description: "Update notification received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -193,12 +197,12 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + registration.attendee = attendee2 let updatedRegistration = try await Amplify.DataStore.save(registration) XCTAssertEqual(updatedRegistration.attendee.id, attendee2.id) await fulfillment(of: [updateReceived], timeout: TestCommonConstants.networkTimeout) - + var queriedAttendeeOptional = try await Amplify.DataStore.query(Attendee8V2.self, byId: attendee.id) guard let queriedAttendee = queriedAttendeeOptional else { XCTFail("Could not get attendee") @@ -206,7 +210,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } try await queriedAttendee.meetings?.fetch() XCTAssertEqual(queriedAttendee.meetings?.count, 0) - + queriedAttendeeOptional = try await Amplify.DataStore.query(Attendee8V2.self, byId: attendee2.id) guard let queriedAttendee = queriedAttendeeOptional else { XCTFail("Could not get attendee") @@ -221,7 +225,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let attendee = await saveAttendee(), let meeting = await saveMeeting(), - let registration = await saveRegistration(meeting: meeting, attendee: attendee) else { + let registration = await saveRegistration(meeting: meeting, attendee: attendee) + else { XCTFail("Could not create attendee, meeting, registration") return } @@ -229,7 +234,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 attendee and 1 meeting and 1 registration) var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -265,11 +271,12 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { return } await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteRegistrationRecieved = expectation(description: "Delete registration received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -289,7 +296,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } let _ = try await Amplify.DataStore.delete(registration) await fulfillment(of: [deleteRegistrationRecieved], timeout: TestCommonConstants.networkTimeout) - + let queriedAttendeeOptional = try await Amplify.DataStore.query(Attendee8V2.self, byId: attendee.id) guard let queriedAttendee = queriedAttendeeOptional else { XCTFail("Could not get attendee") @@ -297,7 +304,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } try await queriedAttendee.meetings?.fetch() XCTAssertEqual(queriedAttendee.meetings?.count, 0) - + let queriedMeetingOptional = try await Amplify.DataStore.query(Meeting8V2.self, byId: meeting.id) guard let queriedMeeting = queriedMeetingOptional else { XCTFail("Could not get meeting") @@ -312,7 +319,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let attendee = await saveAttendee(), let meeting = await saveMeeting(), - let registration = await saveRegistration(meeting: meeting, attendee: attendee) else { + let registration = await saveRegistration(meeting: meeting, attendee: attendee) + else { XCTFail("Could not create attendee, meeting, registration") return } @@ -320,7 +328,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 attendee and 1 meeting and 1 registration) var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -356,12 +365,13 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { return } await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "Delete received") deleteReceived.expectedFulfillmentCount = 2 // attendee and registration hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -391,13 +401,13 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } } } - + _ = try await Amplify.DataStore.delete(attendee) await fulfillment(of: [deleteReceived], timeout: TestCommonConstants.networkTimeout) - + let queriedAttendeeOptional = try await Amplify.DataStore.query(Attendee8V2.self, byId: attendee.id) XCTAssertNil(queriedAttendeeOptional) - + let queriedMeetingOptional = try await Amplify.DataStore.query(Meeting8V2.self, byId: meeting.id) guard let queriedMeeting = queriedMeetingOptional else { XCTFail("Could not get meeting") @@ -412,7 +422,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let attendee = await saveAttendee(), let meeting = await saveMeeting(), - let registration = await saveRegistration(meeting: meeting, attendee: attendee) else { + let registration = await saveRegistration(meeting: meeting, attendee: attendee) + else { XCTFail("Could not create attendee, meeting, registration") return } @@ -420,7 +431,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 attendee and 1 meeting and 1 registration) var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -456,12 +468,13 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { return } await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "Delete received") deleteReceived.expectedFulfillmentCount = 2 // meeting and registration hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -482,10 +495,10 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } } } - + _ = try await Amplify.DataStore.delete(meeting) await fulfillment(of: [deleteReceived], timeout: TestCommonConstants.networkTimeout) - + let queriedAttendeeOptional = try await Amplify.DataStore.query(Attendee8V2.self, byId: attendee.id) guard let queriedAttendee = queriedAttendeeOptional else { XCTFail("Could not get meeting") @@ -493,7 +506,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } try await queriedAttendee.meetings?.fetch() XCTAssertEqual(queriedAttendee.meetings?.count, 0) - + let queriedMeetingOptional = try await Amplify.DataStore.query(Meeting8V2.self, byId: meeting.id) XCTAssertNil(queriedMeetingOptional) } @@ -503,7 +516,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { var result: Attendee8V2? do { result = try await Amplify.DataStore.save(attendee) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result @@ -514,7 +527,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { var result: Meeting8V2? do { result = try await Amplify.DataStore.save(meeting) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result @@ -525,7 +538,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { var result: Registration8V2? do { result = try await Amplify.DataStore.save(registration) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithCustomTimestampTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithCustomTimestampTests.swift index cae0ffcc0a..f9dfac98f8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithCustomTimestampTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithCustomTimestampTests.swift @@ -45,7 +45,8 @@ class DataStoreModelWithCustomTimestampTests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "Delete notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithDefaultValueTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithDefaultValueTests.swift index 9a4643ff8c..d074a5bcb3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithDefaultValueTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithDefaultValueTests.swift @@ -39,14 +39,16 @@ class DataStoreModelWithDefaultValueTests: SyncEngineIntegrationV2TestBase { let createReceived = expectation(description: "Create notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return } guard let todoEvent = try? mutationEvent.decodeModel() as? TodoWithDefaultValueV2, - todoEvent.id == todo.id else { + todoEvent.id == todo.id + else { return } @@ -90,14 +92,16 @@ class DataStoreModelWithDefaultValueTests: SyncEngineIntegrationV2TestBase { let createReceived = expectation(description: "Create notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return } guard let todoEvent = try? mutationEvent.decodeModel() as? TodoWithDefaultValueV2, - todoEvent.id == todo.id else { + todoEvent.id == todo.id + else { return } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithSecondaryIndexTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithSecondaryIndexTests.swift index 88545d49c8..105871d894 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithSecondaryIndexTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithSecondaryIndexTests.swift @@ -44,7 +44,8 @@ class DataStoreModelWithSecondaryIndexTests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "Delete notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreSchemaDriftTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreSchemaDriftTests.swift index e52dad6dd6..68f9d815b7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreSchemaDriftTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreSchemaDriftTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Combine +import XCTest @testable import Amplify @testable import AWSDataStorePlugin @@ -60,11 +60,13 @@ class DataStoreSchemaDriftTests: SyncEngineIntegrationV2TestBase { input.updateValue("THREE", forKey: "enumValue") var variables = [String: Any]() variables.updateValue(input, forKey: "input") - let requestWithEnumThree = GraphQLRequest(document: request.document, - variables: variables, - responseType: request.responseType, - decodePath: request.decodePath, - options: request.options) + let requestWithEnumThree = GraphQLRequest( + document: request.document, + variables: variables, + responseType: request.responseType, + decodePath: request.decodePath, + options: request.options + ) Amplify.API.mutate(request: requestWithEnumThree) { result in switch result { case .success(let response): diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSession.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSession.swift index 8beaab3986..774ab441f7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSession.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSession.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Amplify import AWSAPIPlugin +import Foundation enum AmplifyURLSessionState { case active @@ -26,7 +25,7 @@ class AmplifyURLSessionNoOperationDataTask: URLSessionDataTaskBehavior { } static let shared: AmplifyURLSessionNoOperationDataTask = - AmplifyURLSessionNoOperationDataTask(taskBehaviorIdentifier: -1) + .init(taskBehaviorIdentifier: -1) func cancel() { } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSessionFactory.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSessionFactory.swift index f99be07eaf..bc77388b51 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSessionFactory.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSessionFactory.swift @@ -5,9 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import AWSAPIPlugin +import Foundation class AmplifyURLSessionFactory: URLSessionBehaviorFactory { func makeSession(withDelegate delegate: URLSessionBehaviorDelegate?) -> URLSessionBehavior { @@ -15,10 +14,12 @@ class AmplifyURLSessionFactory: URLSessionBehaviorFactory { let configuration = URLSessionConfiguration.default configuration.tlsMinimumSupportedProtocolVersion = .TLSv12 configuration.tlsMaximumSupportedProtocolVersion = .TLSv13 - - let session = URLSession(configuration: configuration, - delegate: urlSessionDelegate, - delegateQueue: nil) + + let session = URLSession( + configuration: configuration, + delegate: urlSessionDelegate, + delegateQueue: nil + ) return AmplifyURLSession(session: session) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/DataStoreHubEvent.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/DataStoreHubEvent.swift index cce3a2ae39..932873d300 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/DataStoreHubEvent.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/DataStoreHubEvent.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSDataStorePlugin +import Foundation /// Initialize with `HubPayload`'s `eventName: String` and `data: Any?` fields to return an enum of events with their /// expected payloads in their respective types diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/HubListenerTestUtilities.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/HubListenerTestUtilities.swift index a6376c3805..ccf59e7852 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/HubListenerTestUtilities.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/HubListenerTestUtilities.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import Amplify import Foundation +@testable import Amplify -struct HubListenerTestUtilities { +enum HubListenerTestUtilities { /// Blocks current thread until the listener with `token` is attached to the plugin. Returns `true` if the listener /// becomes present before the `timeout` expires, `false` otherwise. @@ -17,11 +17,13 @@ struct HubListenerTestUtilities { /// - Parameter plugin: the plugin on which the listener will be checked /// - Parameter timeout: the maximum length of time to wait for the listener to be registered /// - Throws: if the plugin cannot be cast to `AWSHubPlugin` - static func waitForListener(with token: UnsubscribeToken, - plugin: HubCategoryPlugin? = nil, - timeout: TimeInterval, - file: StaticString = #file, - line: UInt = #line) async throws -> Bool { + static func waitForListener( + with token: UnsubscribeToken, + plugin: HubCategoryPlugin? = nil, + timeout: TimeInterval, + file: StaticString = #file, + line: UInt = #line + ) async throws -> Bool { let plugin = try plugin ?? Amplify.Hub.getPlugin(for: AWSHubPlugin.key) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressBaseTest.swift index e6923fd0ed..4650e79c07 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressBaseTest.swift @@ -7,25 +7,25 @@ import XCTest +import AWSAPIPlugin import AWSPluginsCore import Combine -import AWSAPIPlugin @testable import Amplify @testable import AWSDataStorePlugin @testable import DataStoreHostApp class DataStoreStressBaseTest: XCTestCase { - + static let amplifyConfigurationFile = "testconfiguration/AWSAmplifyStressTests-amplifyconfiguration" let concurrencyLimit = 50 let networkTimeout = TimeInterval(180) - + func setUp(withModels models: AmplifyModelRegistration, logLevel: LogLevel = .error) async { - + continueAfterFailure = false Amplify.Logging.logLevel = logLevel - + do { let amplifyConfig = try TestConfigHelper.retrieveAmplifyConfiguration(forResource: Self.amplifyConfigurationFile) try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, configuration: .custom(syncMaxRecords: 100))) @@ -36,15 +36,15 @@ class DataStoreStressBaseTest: XCTestCase { return } } - + override func tearDown() async throws { await Amplify.reset() } - + func stopDataStore() async throws { try await Amplify.DataStore.stop() } - + func clearDataStore() async throws { try await Amplify.DataStore.clear() } @@ -61,8 +61,10 @@ class DataStoreStressBaseTest: XCTestCase { let eventReceived = expectation(description: "DataStore \(eventName) event") var token: UnsubscribeToken! - token = Amplify.Hub.listen(to: .dataStore, - eventName: eventName) { _ in + token = Amplify.Hub.listen( + to: .dataStore, + eventName: eventName + ) { _ in eventReceived.fulfill() Amplify.Hub.removeListener(token) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressTests.swift index 444bb65f76..f7f08184dc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressTests.swift @@ -7,16 +7,16 @@ import XCTest +import AWSAPIPlugin import AWSPluginsCore import Combine -import AWSAPIPlugin @testable import Amplify @testable import AWSDataStorePlugin @testable import DataStoreHostApp final class DataStoreStressTests: DataStoreStressBaseTest { - + struct TestModelRegistration: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { registry.register(modelType: Post.self) @@ -24,9 +24,9 @@ final class DataStoreStressTests: DataStoreStressBaseTest { let version: String = "1" } - + // MARK: - Stress tests - + /// Perform concurrent saves and observe the data successfuly synced from cloud /// /// - Given: DataStore is in ready state @@ -41,13 +41,15 @@ final class DataStoreStressTests: DataStoreStressBaseTest { var posts = [Post]() for index in 0 ..< concurrencyLimit { - let post = Post(title: "title \(index)", - status: .active, - content: "content \(index)", - createdAt: .now()) + let post = Post( + title: "title \(index)", + status: .active, + content: "content \(index)", + createdAt: .now() + ) posts.append(post) } - + let postsSyncedToCloud = expectation(description: "All posts saved and synced to cloud") postsSyncedToCloud.expectedFulfillmentCount = concurrencyLimit @@ -69,7 +71,7 @@ final class DataStoreStressTests: DataStoreStressBaseTest { XCTFail("Failed \(error)") } } - + let capturedPosts = posts DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in @@ -77,10 +79,10 @@ final class DataStoreStressTests: DataStoreStressBaseTest { _ = try await Amplify.DataStore.save(capturedPosts[index]) } } - + await fulfillment(of: [postsSyncedToCloud], timeout: networkTimeout) } - + /// Perform concurrent saves and observe the data successfuly synced from cloud /// /// - Given: DataStore is in ready state @@ -95,7 +97,7 @@ final class DataStoreStressTests: DataStoreStressBaseTest { try await startDataStoreAndWaitForReady() let posts = await saveAndSyncPosts(concurrencyLimit: concurrencyLimit) - + let localQueryForPosts = expectation(description: "Query for the post is successful") localQueryForPosts.expectedFulfillmentCount = concurrencyLimit @@ -109,10 +111,10 @@ final class DataStoreStressTests: DataStoreStressBaseTest { localQueryForPosts.fulfill() } } - + await fulfillment(of: [localQueryForPosts], timeout: networkTimeout) } - + /// Perform concurrent saves and observe the data successfuly synced from cloud /// /// - Given: DataStore is in ready state @@ -127,7 +129,7 @@ final class DataStoreStressTests: DataStoreStressBaseTest { try await startDataStoreAndWaitForReady() let posts = await saveAndSyncPosts(concurrencyLimit: concurrencyLimit) - + let localQueryForPosts = expectation(description: "Query for the post is successful") localQueryForPosts.expectedFulfillmentCount = concurrencyLimit DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in @@ -142,10 +144,10 @@ final class DataStoreStressTests: DataStoreStressBaseTest { localQueryForPosts.fulfill() } } - + await fulfillment(of: [localQueryForPosts], timeout: networkTimeout) } - + /// Perform concurrent saves and observe the data successfuly synced from cloud. Then delete the items afterwards /// and ensure they have successfully synced from cloud /// @@ -160,12 +162,12 @@ final class DataStoreStressTests: DataStoreStressBaseTest { func testMultipleDelete() async throws { await setUp(withModels: TestModelRegistration(), logLevel: .verbose) try await startDataStoreAndWaitForReady() - + let posts = await saveAndSyncPosts(concurrencyLimit: concurrencyLimit) - + let postsDeletedLocally = expectation(description: "All posts deleted locally") postsDeletedLocally.expectedFulfillmentCount = concurrencyLimit - + let postsDeletedFromCloud = expectation(description: "All posts deleted and synced to cloud") postsDeletedFromCloud.expectedFulfillmentCount = concurrencyLimit @@ -176,7 +178,7 @@ final class DataStoreStressTests: DataStoreStressBaseTest { guard posts.contains(where: { $0.id == mutationEvent.modelId }) else { return } - + if mutationEvent.mutationType == MutationEvent.MutationType.delete.rawValue, mutationEvent.version == 1 { postsDeletedLocally.fulfill() @@ -189,29 +191,31 @@ final class DataStoreStressTests: DataStoreStressBaseTest { XCTFail("Failed \(error)") } } - + DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in Task { try await Amplify.DataStore.delete(posts[index]) } } - + await fulfillment(of: [postsDeletedLocally, postsDeletedFromCloud], timeout: networkTimeout) } - - + + // MARK: - Helpers - + func saveAndSyncPosts(concurrencyLimit: Int) async -> [Post] { var posts = [Post]() for index in 0 ..< concurrencyLimit { - let post = Post(title: "title \(index)", - status: .active, - content: "content \(index)", - createdAt: .now()) + let post = Post( + title: "title \(index)", + status: .active, + content: "content \(index)", + createdAt: .now() + ) posts.append(post) } - + let postsSyncedToCloud = expectation(description: "All posts saved and synced to cloud") postsSyncedToCloud.expectedFulfillmentCount = concurrencyLimit @@ -223,7 +227,7 @@ final class DataStoreStressTests: DataStoreStressBaseTest { guard postsCopy.contains(where: { $0.id == mutationEvent.modelId }) else { return } - + if mutationEvent.mutationType == MutationEvent.MutationType.create.rawValue, mutationEvent.version == 1 { postsSyncedToCloud.fulfill() @@ -233,16 +237,16 @@ final class DataStoreStressTests: DataStoreStressBaseTest { XCTFail("Failed \(error)") } } - + let capturedPosts = posts - + DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in Task { _ = try await Amplify.DataStore.save(capturedPosts[index]) } } await fulfillment(of: [postsSyncedToCloud], timeout: networkTimeout) - + return capturedPosts } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/AmplifyModels.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/AmplifyModels.swift index 96eef29957..167804f3b4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/AmplifyModels.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/AmplifyModels.swift @@ -9,11 +9,11 @@ import Amplify import Foundation -// Contains the set of classes that conforms to the `Model` protocol. +// Contains the set of classes that conforms to the `Model` protocol. -final public class AmplifyModels: AmplifyModelRegistration { +public final class AmplifyModels: AmplifyModelRegistration { public let version: String = "9ddf09113aaee75fdec53f41fd7a73d7" - + public func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post+Schema.swift index 96d24f0a99..a1b369d614 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case status @@ -19,23 +19,23 @@ extension Post { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post = Post.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Posts" - + model.attributes( .primaryKey(fields: [post.id]) ) - + model.fields( .field(post.id, is: .required, ofType: .string), .field(post.title, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post.swift index 3658db511f..c5a0adeaac 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post.swift @@ -16,24 +16,30 @@ public struct Post: Model { public var content: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - status: PostStatus, - content: String) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + status: PostStatus, + content: String + ) { + self.init( + id: id, title: title, status: status, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - status: PostStatus, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + status: PostStatus, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.status = status diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+ClientBehavior.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+ClientBehavior.swift index f79c09981f..20a02f8683 100644 --- a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+ClientBehavior.swift +++ b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+ClientBehavior.swift @@ -10,7 +10,7 @@ import Foundation import AWSLocation -extension AWSLocationGeoPlugin { +public extension AWSLocationGeoPlugin { // MARK: - Search @@ -30,8 +30,10 @@ extension AWSLocationGeoPlugin { /// `Geo.Error.networkError` if request failed or network unavailable /// `Geo.Error.pluginError` if encapsulated error received by a dependent plugin /// `Geo.Error.unknown` if error is unknown - public func search(for text: String, - options: Geo.SearchForTextOptions? = nil) async throws -> [Geo.Place] { + func search( + for text: String, + options: Geo.SearchForTextOptions? = nil + ) async throws -> [Geo.Place] { var request = SearchPlaceIndexForTextInput() @@ -41,7 +43,8 @@ extension AWSLocationGeoPlugin { guard request.indexName != nil else { throw Geo.Error.invalidConfiguration( GeoPluginErrorConstants.missingDefaultSearchIndex.errorDescription, - GeoPluginErrorConstants.missingDefaultSearchIndex.recoverySuggestion) + GeoPluginErrorConstants.missingDefaultSearchIndex.recoverySuggestion + ) } request.text = text @@ -49,13 +52,17 @@ extension AWSLocationGeoPlugin { if let area = options?.area { switch area { case .near(let coordinates): - request.biasPosition = [coordinates.longitude, - coordinates.latitude] + request.biasPosition = [ + coordinates.longitude, + coordinates.latitude + ] case .within(let boundingBox): - request.filterBBox = [boundingBox.southwest.longitude, - boundingBox.southwest.latitude, - boundingBox.northeast.longitude, - boundingBox.northeast.latitude] + request.filterBBox = [ + boundingBox.southwest.longitude, + boundingBox.southwest.latitude, + boundingBox.northeast.longitude, + boundingBox.northeast.latitude + ] } } @@ -73,9 +80,7 @@ extension AWSLocationGeoPlugin { let response = try await locationService.searchPlaceIndex(forText: request) var results = [LocationClientTypes.Place]() if let responseResults = response.results { - results = responseResults.compactMap { - $0.place - } + results = responseResults.compactMap(\.place) } let places: [Geo.Place] = results.compactMap { @@ -85,16 +90,18 @@ extension AWSLocationGeoPlugin { return nil } - return Geo.Place(coordinates: Geo.Coordinates(latitude: lat, longitude: long), - label: $0.label, - addressNumber: $0.addressNumber, - street: $0.street, - municipality: $0.municipality, - neighborhood: $0.neighborhood, - region: $0.region, - subRegion: $0.subRegion, - postalCode: $0.postalCode, - country: $0.country) + return Geo.Place( + coordinates: Geo.Coordinates(latitude: lat, longitude: long), + label: $0.label, + addressNumber: $0.addressNumber, + street: $0.street, + municipality: $0.municipality, + neighborhood: $0.neighborhood, + region: $0.region, + subRegion: $0.subRegion, + postalCode: $0.postalCode, + country: $0.country + ) } return places } catch let error as GeoErrorConvertible { @@ -123,8 +130,10 @@ extension AWSLocationGeoPlugin { /// `Geo.Error.networkError` if request failed or network unavailable /// `Geo.Error.pluginError` if encapsulated error received by a dependent plugin /// `Geo.Error.unknown` if error is unknown - public func search(for coordinates: Geo.Coordinates, - options: Geo.SearchForCoordinatesOptions? = nil) async throws -> [Geo.Place] { + func search( + for coordinates: Geo.Coordinates, + options: Geo.SearchForCoordinatesOptions? = nil + ) async throws -> [Geo.Place] { var request = SearchPlaceIndexForPositionInput() @@ -134,11 +143,14 @@ extension AWSLocationGeoPlugin { guard request.indexName != nil else { throw Geo.Error.invalidConfiguration( GeoPluginErrorConstants.missingDefaultSearchIndex.errorDescription, - GeoPluginErrorConstants.missingDefaultSearchIndex.recoverySuggestion) + GeoPluginErrorConstants.missingDefaultSearchIndex.recoverySuggestion + ) } - request.position = [coordinates.longitude, - coordinates.latitude] + request.position = [ + coordinates.longitude, + coordinates.latitude + ] if let maxResults = options?.maxResults { request.maxResults = maxResults as Int @@ -148,9 +160,7 @@ extension AWSLocationGeoPlugin { let response = try await locationService.searchPlaceIndex(forPosition: request) var results = [LocationClientTypes.Place]() if let responseResults = response.results { - results = responseResults.compactMap { - $0.place - } + results = responseResults.compactMap(\.place) } let places: [Geo.Place] = results.compactMap { @@ -160,16 +170,18 @@ extension AWSLocationGeoPlugin { return nil } - return Geo.Place(coordinates: Geo.Coordinates(latitude: lat, longitude: long), - label: $0.label, - addressNumber: $0.addressNumber, - street: $0.street, - municipality: $0.municipality, - neighborhood: $0.neighborhood, - region: $0.region, - subRegion: $0.subRegion, - postalCode: $0.postalCode, - country: $0.country) + return Geo.Place( + coordinates: Geo.Coordinates(latitude: lat, longitude: long), + label: $0.label, + addressNumber: $0.addressNumber, + street: $0.street, + municipality: $0.municipality, + neighborhood: $0.neighborhood, + region: $0.region, + subRegion: $0.subRegion, + postalCode: $0.postalCode, + country: $0.country + ) } return places } catch let error as GeoErrorConvertible { @@ -194,12 +206,13 @@ extension AWSLocationGeoPlugin { /// `Geo.Error.networkError` if request failed or network unavailable /// `Geo.Error.pluginError` if encapsulated error received by a dependent plugin /// `Geo.Error.unknown` if error is unknown - public func availableMaps() async throws -> [Geo.MapStyle] { + func availableMaps() async throws -> [Geo.MapStyle] { let mapStyles = Array(pluginConfig.maps.values) guard !mapStyles.isEmpty else { throw Geo.Error.invalidConfiguration( GeoPluginErrorConstants.missingMaps.errorDescription, - GeoPluginErrorConstants.missingMaps.recoverySuggestion) + GeoPluginErrorConstants.missingMaps.recoverySuggestion + ) } return mapStyles } @@ -213,11 +226,12 @@ extension AWSLocationGeoPlugin { /// `Geo.Error.networkError` if request failed or network unavailable /// `Geo.Error.pluginError` if encapsulated error received by a dependent plugin /// `Geo.Error.unknown` if error is unknown - public func defaultMap() async throws -> Geo.MapStyle { + func defaultMap() async throws -> Geo.MapStyle { guard let mapName = pluginConfig.defaultMap, let mapStyle = pluginConfig.maps[mapName] else { throw Geo.Error.invalidConfiguration( GeoPluginErrorConstants.missingDefaultMap.errorDescription, - GeoPluginErrorConstants.missingDefaultMap.recoverySuggestion) + GeoPluginErrorConstants.missingDefaultMap.recoverySuggestion + ) } return mapStyle } diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Configure.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Configure.swift index 221d9d9551..00fbe68642 100644 --- a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Configure.swift +++ b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Configure.swift @@ -7,12 +7,12 @@ import Foundation @_spi(InternalAmplifyConfiguration) import Amplify +import AWSClientRuntime +import AWSLocation import AWSPluginsCore @_spi(PluginHTTPClientEngine) import InternalAmplifyCredentials -import AWSLocation -import AWSClientRuntime -extension AWSLocationGeoPlugin { +public extension AWSLocationGeoPlugin { /// Configures AWSLocationPlugin with the specified configuration. /// /// This method will be invoked as part of the Amplify configuration flow. @@ -20,7 +20,7 @@ extension AWSLocationGeoPlugin { /// - Parameter configuration: The configuration specified for this plugin. /// - Throws: /// - PluginError.pluginConfigurationError: If one of the configuration values is invalid or empty. - public func configure(using configuration: Any?) throws { + func configure(using configuration: Any?) throws { let pluginConfiguration: AWSLocationGeoPluginConfiguration if let configuration = configuration as? AmplifyOutputsData { pluginConfiguration = try AWSLocationGeoPluginConfiguration(config: configuration) @@ -34,7 +34,7 @@ extension AWSLocationGeoPlugin { } /// Configure AWSLocationPlugin programatically using AWSLocationPluginConfiguration - public func configure(using configuration: AWSLocationGeoPluginConfiguration) throws { + func configure(using configuration: AWSLocationGeoPluginConfiguration) throws { let authService = AWSAuthService() let credentialsProvider = authService.getCredentialIdentityResolver() let region = configuration.regionName @@ -50,9 +50,11 @@ extension AWSLocationGeoPlugin { let location = LocationClient(config: serviceConfiguration) let locationService = AWSLocationAdapter(location: location) - configure(locationService: locationService, - authService: authService, - pluginConfig: configuration) + configure( + locationService: locationService, + authService: authService, + pluginConfig: configuration + ) } // MARK: - Internal @@ -65,9 +67,11 @@ extension AWSLocationGeoPlugin { /// - locationService: The location service object. /// - authService: The authentication service object. /// - pluginConfig: The configuration for the plugin. - func configure(locationService: AWSLocationBehavior, - authService: AWSAuthServiceBehavior, - pluginConfig: AWSLocationGeoPluginConfiguration) { + internal func configure( + locationService: AWSLocationBehavior, + authService: AWSAuthServiceBehavior, + pluginConfig: AWSLocationGeoPluginConfiguration + ) { self.locationService = locationService self.authService = authService self.pluginConfig = pluginConfig diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Reset.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Reset.swift index b1b76ca452..a748002a2c 100644 --- a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Reset.swift +++ b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Reset.swift @@ -8,13 +8,13 @@ import Amplify import Foundation -extension AWSLocationGeoPlugin { +public extension AWSLocationGeoPlugin { /// Resets the state of the plugin. /// /// Sets stored objects to nil to allow deallocation, then calls onComplete closure /// to signal the reset has completed. - public func reset() async { + func reset() async { locationService = nil authService = nil pluginConfig = nil diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Configuration/AWSLocationGeoPluginConfiguration.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Configuration/AWSLocationGeoPluginConfiguration.swift index 4d25b090a5..b4f25e9fe2 100644 --- a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Configuration/AWSLocationGeoPluginConfiguration.swift +++ b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Configuration/AWSLocationGeoPluginConfiguration.swift @@ -6,8 +6,8 @@ // @_spi(InternalAmplifyConfiguration) import Amplify -import Foundation import AWSLocation +import Foundation public struct AWSLocationGeoPluginConfiguration { private static func urlString(regionName: String, mapName: String) -> String { @@ -22,18 +22,24 @@ public struct AWSLocationGeoPluginConfiguration { public let regionName: String init(config: JSONValue) throws { - let configObject = try AWSLocationGeoPluginConfiguration.getConfigObject(section: .plugin, - configJSON: config) + let configObject = try AWSLocationGeoPluginConfiguration.getConfigObject( + section: .plugin, + configJSON: config + ) let regionName = try AWSLocationGeoPluginConfiguration.getRegion(configObject) var maps = [String: Geo.MapStyle]() var defaultMap: String? if let mapsConfigJSON = configObject[Section.maps.key] { - let mapsConfigObject = try AWSLocationGeoPluginConfiguration.getConfigObject(section: .maps, - configJSON: mapsConfigJSON) + let mapsConfigObject = try AWSLocationGeoPluginConfiguration.getConfigObject( + section: .maps, + configJSON: mapsConfigJSON + ) maps = try AWSLocationGeoPluginConfiguration.getMaps(mapConfig: mapsConfigObject, regionName: regionName) - defaultMap = try AWSLocationGeoPluginConfiguration.getDefault(section: .maps, - configObject: mapsConfigObject) + defaultMap = try AWSLocationGeoPluginConfiguration.getDefault( + section: .maps, + configObject: mapsConfigObject + ) guard let map = defaultMap, maps[map] != nil else { throw GeoPluginConfigError.mapDefaultNotFound(mapName: defaultMap) } @@ -42,25 +48,33 @@ public struct AWSLocationGeoPluginConfiguration { var searchIndices = [String]() var defaultSearchIndex: String? if let searchConfigJSON = configObject[Section.searchIndices.key] { - let searchConfigObject = try AWSLocationGeoPluginConfiguration.getConfigObject(section: .searchIndices, - configJSON: searchConfigJSON) - searchIndices = try AWSLocationGeoPluginConfiguration.getItemsStrings(section: .searchIndices, - configObject: searchConfigObject) - defaultSearchIndex = try AWSLocationGeoPluginConfiguration.getDefault(section: .searchIndices, - configObject: searchConfigObject) + let searchConfigObject = try AWSLocationGeoPluginConfiguration.getConfigObject( + section: .searchIndices, + configJSON: searchConfigJSON + ) + searchIndices = try AWSLocationGeoPluginConfiguration.getItemsStrings( + section: .searchIndices, + configObject: searchConfigObject + ) + defaultSearchIndex = try AWSLocationGeoPluginConfiguration.getDefault( + section: .searchIndices, + configObject: searchConfigObject + ) guard let index = defaultSearchIndex, searchIndices.contains(index) else { throw GeoPluginConfigError.searchDefaultNotFound(indexName: defaultSearchIndex) } } - self.init(regionName: regionName, - defaultMap: defaultMap, - maps: maps, - defaultSearchIndex: defaultSearchIndex, - searchIndices: searchIndices) + self.init( + regionName: regionName, + defaultMap: defaultMap, + maps: maps, + defaultSearchIndex: defaultSearchIndex, + searchIndices: searchIndices + ) } - + init(config: AmplifyOutputsData) throws { guard let geo = config.geo else { throw GeoPluginConfigError.configurationInvalid(section: .plugin) @@ -71,7 +85,8 @@ public struct AWSLocationGeoPluginConfiguration { if let geoMaps = geo.maps { maps = try AWSLocationGeoPluginConfiguration.getMaps( mapConfig: geoMaps, - regionName: geo.awsRegion) + regionName: geo.awsRegion + ) defaultMap = geoMaps.default // Validate that the default map exists in `maps` @@ -91,18 +106,22 @@ public struct AWSLocationGeoPluginConfiguration { } } - self.init(regionName: geo.awsRegion, - defaultMap: defaultMap, - maps: maps, - defaultSearchIndex: defaultSearchIndex, - searchIndices: searchIndices) + self.init( + regionName: geo.awsRegion, + defaultMap: defaultMap, + maps: maps, + defaultSearchIndex: defaultSearchIndex, + searchIndices: searchIndices + ) } - init(regionName: String, - defaultMap: String?, - maps: [String: Geo.MapStyle], - defaultSearchIndex: String?, - searchIndices: [String]) { + init( + regionName: String, + defaultMap: String?, + maps: [String: Geo.MapStyle], + defaultSearchIndex: String?, + searchIndices: [String] + ) { self.regionName = regionName self.defaultMap = defaultMap self.maps = maps @@ -162,8 +181,10 @@ public struct AWSLocationGeoPluginConfiguration { return itemsJSON } - private static func getItemsObject(section: Section, - configObject: [String: JSONValue]) throws -> [String: JSONValue] { + private static func getItemsObject( + section: Section, + configObject: [String: JSONValue] + ) throws -> [String: JSONValue] { let itemsJSON = try getItemsJSON(section: section, configObject: configObject) let itemsObject = try getConfigObject(section: section, configJSON: itemsJSON) return itemsObject @@ -200,8 +221,10 @@ public struct AWSLocationGeoPluginConfiguration { throw GeoPluginConfigError.mapStyleIsNotString(mapName: mapName) } - let url = URL(string: AWSLocationGeoPluginConfiguration.urlString(regionName: regionName, - mapName: mapName)) + let url = URL(string: AWSLocationGeoPluginConfiguration.urlString( + regionName: regionName, + mapName: mapName + )) guard let styleURL = url else { throw GeoPluginConfigError.mapStyleURLInvalid(mapName: mapName) } @@ -215,11 +238,15 @@ public struct AWSLocationGeoPluginConfiguration { return mapStyles } - private static func getMaps(mapConfig: AmplifyOutputsData.Geo.Maps, - regionName: String) throws -> [String: Geo.MapStyle] { + private static func getMaps( + mapConfig: AmplifyOutputsData.Geo.Maps, + regionName: String + ) throws -> [String: Geo.MapStyle] { let mapTuples: [(String, Geo.MapStyle)] = try mapConfig.items.map { map in - let url = URL(string: AWSLocationGeoPluginConfiguration.urlString(regionName: regionName, - mapName: map.key)) + let url = URL(string: AWSLocationGeoPluginConfiguration.urlString( + regionName: regionName, + mapName: map.key + )) guard let styleURL = url else { throw GeoPluginConfigError.mapStyleURLInvalid(mapName: map.key) } diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Configuration/GeoPluginConfigError.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Configuration/GeoPluginConfigError.swift index 749533765c..945a30037f 100644 --- a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Configuration/GeoPluginConfigError.swift +++ b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Configuration/GeoPluginConfigError.swift @@ -10,7 +10,7 @@ import Foundation typealias GeoPluginErrorString = (errorDescription: ErrorDescription, recoverySuggestion: RecoverySuggestion) -struct GeoPluginConfigError { +enum GeoPluginConfigError { static func configurationInvalid(section: AWSLocationGeoPluginConfiguration.Section) -> PluginError { PluginError.pluginConfigurationError( "Unable to decode \(section.key) configuration.", diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Dependency/AWSLocationBehavior.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Dependency/AWSLocationBehavior.swift index fdc71dc22f..2433afbc93 100644 --- a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Dependency/AWSLocationBehavior.swift +++ b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Dependency/AWSLocationBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSLocation +import Foundation /// Behavior that `AWSLocationAdapter` will use. /// This protocol allows a way to create a Mock and ensure the plugin implementation is testable. diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Constants/GeoPluginErrorConstants.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Constants/GeoPluginErrorConstants.swift index 11250a7976..f3c9b7fc7e 100644 --- a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Constants/GeoPluginErrorConstants.swift +++ b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Constants/GeoPluginErrorConstants.swift @@ -5,21 +5,24 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation -struct GeoPluginErrorConstants { +enum GeoPluginErrorConstants { static let missingDefaultSearchIndex: GeoPluginErrorString = ( "No default search index was found.", - "Please ensure you have added search to your project before calling search functions.") + "Please ensure you have added search to your project before calling search functions." + ) static let missingDefaultMap: GeoPluginErrorString = ( "No default map was found.", - "Please ensure you have added maps to your project before calling map-related functions.") + "Please ensure you have added maps to your project before calling map-related functions." + ) static let missingMaps: GeoPluginErrorString = ( "No maps are available.", - "Please ensure you have added maps to your project before calling map-related functions.") + "Please ensure you have added maps to your project before calling map-related functions." + ) } // Recovery Messages diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Utils/GeoErrorConvertible.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Utils/GeoErrorConvertible.swift index f1419059c8..cff8f51e84 100644 --- a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Utils/GeoErrorConvertible.swift +++ b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Utils/GeoErrorConvertible.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSLocation +import Foundation @_spi(UnknownAWSHTTPServiceError) import AWSClientRuntime protocol GeoErrorConvertible { diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginAmplifyVersionableTests.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginAmplifyVersionableTests.swift index a39a663998..52f909462f 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginAmplifyVersionableTests.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginAmplifyVersionableTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSLocationGeoPlugin +import XCTest // swiftlint:disable:next type_name class AWSLocationGeoPluginAmplifyVersionableTests: XCTestCase { diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginClientBehaviorTests.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginClientBehaviorTests.swift index f9ae3c2e71..e86b6db90f 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginClientBehaviorTests.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginClientBehaviorTests.swift @@ -7,8 +7,8 @@ import Amplify import AWSLocation -@testable import AWSLocationGeoPlugin import XCTest +@testable import AWSLocationGeoPlugin class AWSLocationGeoPluginClientBehaviorTests: AWSLocationGeoPluginTestBase { let searchText = "coffee shop" @@ -28,8 +28,8 @@ class AWSLocationGeoPluginClientBehaviorTests: AWSLocationGeoPluginTestBase { do { _ = try await geoPlugin.search(for: searchText, options: nil) var request = SearchPlaceIndexForTextInput() - request.text = self.searchText - self.mockLocation.verifySearchPlaceIndexForText(request) + request.text = searchText + mockLocation.verifySearchPlaceIndexForText(request) } catch { XCTFail("Failed with error: \(error)") } @@ -53,13 +53,15 @@ class AWSLocationGeoPluginClientBehaviorTests: AWSLocationGeoPluginTestBase { do { _ = try await geoPlugin.search(for: searchText, options: options) var request = SearchPlaceIndexForTextInput() - request.text = self.searchText - request.biasPosition = [(self.coordinates.longitude), - (self.coordinates.latitude)] + request.text = searchText + request.biasPosition = [ + coordinates.longitude, + coordinates.latitude + ] request.filterCountries = options.countries?.map { $0.code } request.maxResults = options.maxResults ?? 0 request.indexName = (options.pluginOptions as? AWSLocationGeoPluginSearchOptions)?.searchIndex - self.mockLocation.verifySearchPlaceIndexForText(request) + mockLocation.verifySearchPlaceIndexForText(request) } catch { XCTFail("Failed with error: \(error)") } @@ -100,9 +102,11 @@ class AWSLocationGeoPluginClientBehaviorTests: AWSLocationGeoPluginTestBase { do { _ = try await geoPlugin.search(for: coordinates, options: nil) var request = SearchPlaceIndexForPositionInput() - request.position = [(self.coordinates.longitude), - (self.coordinates.latitude)] - self.mockLocation.verifySearchPlaceIndexForPosition(request) + request.position = [ + coordinates.longitude, + coordinates.latitude + ] + mockLocation.verifySearchPlaceIndexForPosition(request) } catch { XCTFail("Failed with error: \(error)") } @@ -124,11 +128,13 @@ class AWSLocationGeoPluginClientBehaviorTests: AWSLocationGeoPluginTestBase { do { _ = try await geoPlugin.search(for: coordinates, options: options) var request = SearchPlaceIndexForPositionInput() - request.position = [(self.coordinates.longitude), - (self.coordinates.latitude) ] + request.position = [ + coordinates.longitude, + coordinates.latitude + ] request.maxResults = options.maxResults ?? 0 request.indexName = (options.pluginOptions as? AWSLocationGeoPluginSearchOptions)?.searchIndex - self.mockLocation.verifySearchPlaceIndexForPosition(request) + mockLocation.verifySearchPlaceIndexForPosition(request) } catch { XCTFail("Failed with error: \(error)") } diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginConfigureTests.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginConfigureTests.swift index f534374b07..1f31bb9b5b 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginConfigureTests.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginConfigureTests.swift @@ -6,8 +6,8 @@ // import Amplify -@testable import AWSLocationGeoPlugin import XCTest +@testable import AWSLocationGeoPlugin class AWSLocationGeoPluginConfigureTests: AWSLocationGeoPluginTestBase { // MARK: - Plugin Key test @@ -56,7 +56,8 @@ class AWSLocationGeoPluginConfigureTests: AWSLocationGeoPluginTestBase { XCTFail("Geo configuration should not succeed.") } catch { guard let pluginError = error as? PluginError, - case .pluginConfigurationError = pluginError else { + case .pluginConfigurationError = pluginError + else { XCTFail("Should throw invalidConfiguration exception. But received \(error) ") return } diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginResetTests.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginResetTests.swift index 8362742b53..32fe84527a 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginResetTests.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginResetTests.swift @@ -6,8 +6,8 @@ // import Amplify -@testable import AWSLocationGeoPlugin import XCTest +@testable import AWSLocationGeoPlugin class AWSLocationGeoPluginResetTests: AWSLocationGeoPluginTestBase { func testReset() async { diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginTestBase.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginTestBase.swift index ee44deb0fb..c1b70fff6d 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginTestBase.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/AWSLocationGeoPluginTestBase.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSLocationGeoPlugin @testable import AWSPluginsTestCommon -import XCTest class AWSLocationGeoPluginTestBase: XCTestCase { var geoPlugin: AWSLocationGeoPlugin! @@ -18,17 +18,21 @@ class AWSLocationGeoPluginTestBase: XCTestCase { var emptyPluginConfig: AWSLocationGeoPluginConfiguration! override func setUp() async throws { - pluginConfig = AWSLocationGeoPluginConfiguration(regionName: GeoPluginTestConfig.regionName, - defaultMap: GeoPluginTestConfig.map, - maps: GeoPluginTestConfig.maps, - defaultSearchIndex: GeoPluginTestConfig.searchIndex, - searchIndices: GeoPluginTestConfig.searchIndices) - - emptyPluginConfig = AWSLocationGeoPluginConfiguration(regionName: GeoPluginTestConfig.regionName, - defaultMap: nil, - maps: [:], - defaultSearchIndex: nil, - searchIndices: []) + pluginConfig = AWSLocationGeoPluginConfiguration( + regionName: GeoPluginTestConfig.regionName, + defaultMap: GeoPluginTestConfig.map, + maps: GeoPluginTestConfig.maps, + defaultSearchIndex: GeoPluginTestConfig.searchIndex, + searchIndices: GeoPluginTestConfig.searchIndices + ) + + emptyPluginConfig = AWSLocationGeoPluginConfiguration( + regionName: GeoPluginTestConfig.regionName, + defaultMap: nil, + maps: [:], + defaultSearchIndex: nil, + searchIndices: [] + ) do { mockLocation = try MockAWSLocation(pluginConfig: pluginConfig) diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Configuration/AWSLocationGeoPluginAmplifyOutputsConfigurationTests.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Configuration/AWSLocationGeoPluginAmplifyOutputsConfigurationTests.swift index 70e30ab8b4..fd98bfa0fd 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Configuration/AWSLocationGeoPluginAmplifyOutputsConfigurationTests.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Configuration/AWSLocationGeoPluginAmplifyOutputsConfigurationTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable @_spi(InternalAmplifyConfiguration) import Amplify import XCTest +@testable @_spi(InternalAmplifyConfiguration) import Amplify @testable import AWSLocationGeoPlugin @@ -49,7 +49,9 @@ class AWSLocationGeoPluginAmplifyOutputsConfigurationTests: XCTestCase { awsRegion: GeoPluginTestConfig.regionName, maps: .init( items: [GeoPluginTestConfig.map: .init(style: GeoPluginTestConfig.style)], - default: GeoPluginTestConfig.map))) + default: GeoPluginTestConfig.map + ) + )) do { let config = try AWSLocationGeoPluginConfiguration(config: config) XCTAssertNotNil(config) @@ -69,7 +71,9 @@ class AWSLocationGeoPluginAmplifyOutputsConfigurationTests: XCTestCase { awsRegion: GeoPluginTestConfig.regionName, searchIndices: .init( items: [GeoPluginTestConfig.searchIndex], - default: GeoPluginTestConfig.searchIndex))) + default: GeoPluginTestConfig.searchIndex + ) + )) do { let config = try AWSLocationGeoPluginConfiguration(config: config) @@ -92,8 +96,10 @@ class AWSLocationGeoPluginAmplifyOutputsConfigurationTests: XCTestCase { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.configurationInvalid(section: .plugin).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.configurationInvalid(section: .plugin).errorDescription + ) } } @@ -108,15 +114,19 @@ class AWSLocationGeoPluginAmplifyOutputsConfigurationTests: XCTestCase { awsRegion: GeoPluginTestConfig.regionName, maps: .init( items: [GeoPluginTestConfig.map: .init(style: GeoPluginTestConfig.style)], - default: map))) + default: map + ) + )) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.mapDefaultNotFound(mapName: map).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.mapDefaultNotFound(mapName: map).errorDescription + ) } } @@ -129,15 +139,18 @@ class AWSLocationGeoPluginAmplifyOutputsConfigurationTests: XCTestCase { geo: .init( awsRegion: GeoPluginTestConfig.regionName, maps: nil, - searchIndices: .init(items: [GeoPluginTestConfig.searchIndex], default: searchIndex))) + searchIndices: .init(items: [GeoPluginTestConfig.searchIndex], default: searchIndex) + )) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.searchDefaultNotFound(indexName: searchIndex).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.searchDefaultNotFound(indexName: searchIndex).errorDescription + ) } } } diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Configuration/AWSLocationGeoPluginConfigurationTests.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Configuration/AWSLocationGeoPluginConfigurationTests.swift index 8118fc2fa0..cf5106e31f 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Configuration/AWSLocationGeoPluginConfigurationTests.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Configuration/AWSLocationGeoPluginConfigurationTests.swift @@ -44,9 +44,11 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { } func testConfigureSuccessOnlyMaps() throws { - let geoPluginConfigJSON = JSONValue(dictionaryLiteral: + let geoPluginConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, GeoPluginTestConfig.mapsConfigJSON)) + (AWSLocationGeoPluginConfiguration.Section.maps.key, GeoPluginTestConfig.mapsConfigJSON) + ) do { let config = try AWSLocationGeoPluginConfiguration(config: geoPluginConfigJSON) @@ -62,9 +64,11 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { } func testConfigureSuccessOnlySearch() throws { - let geoPluginConfigJSON = JSONValue(dictionaryLiteral: + let geoPluginConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON) + ) do { let config = try AWSLocationGeoPluginConfiguration(config: geoPluginConfigJSON) @@ -87,40 +91,50 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.configurationInvalid(section: .plugin).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.configurationInvalid(section: .plugin).errorDescription + ) } } func testConfigureThrowsErrorForInvalidMapsConfiguration() { let mapsConfigJSON = JSONValue(stringLiteral: "notADictionaryLiteral") - let geoPluginConfig = JSONValue(dictionaryLiteral: + let geoPluginConfig = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON)) + (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: geoPluginConfig)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.configurationInvalid(section: .maps).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.configurationInvalid(section: .maps).errorDescription + ) } } func testConfigureThrowsErrorForInvalidSearchConfiguration() { let searchConfigJSON = JSONValue(stringLiteral: "notADictionaryLiteral") - let geoPluginConfig = JSONValue(dictionaryLiteral: + let geoPluginConfig = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, searchConfigJSON)) + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: geoPluginConfig)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.configurationInvalid(section: .searchIndices).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.configurationInvalid(section: .searchIndices).errorDescription + ) } } @@ -131,21 +145,27 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { let map = "missingMapName" let mapJSON = JSONValue(stringLiteral: map) - let mapsConfigJSON = JSONValue(dictionaryLiteral: + let mapsConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, GeoPluginTestConfig.mapItemConfigJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, mapJSON)) + (AWSLocationGeoPluginConfiguration.Node.default.key, mapJSON) + ) - let geoPluginConfig = JSONValue(dictionaryLiteral: + let geoPluginConfig = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON)) + (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: geoPluginConfig)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.mapDefaultNotFound(mapName: map).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.mapDefaultNotFound(mapName: map).errorDescription + ) } } @@ -156,37 +176,47 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { let searchIndex = "missingSearchIndex" let searchIndexJSON = JSONValue(stringLiteral: searchIndex) - let searchConfigJSON = JSONValue(dictionaryLiteral: + let searchConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, GeoPluginTestConfig.searchItemsArrayJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, searchIndexJSON)) + (AWSLocationGeoPluginConfiguration.Node.default.key, searchIndexJSON) + ) - let geoPluginConfig = JSONValue(dictionaryLiteral: + let geoPluginConfig = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, searchConfigJSON)) + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: geoPluginConfig)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.searchDefaultNotFound(indexName: searchIndex).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.searchDefaultNotFound(indexName: searchIndex).errorDescription + ) } } - + /// - Given: geo plugin configuration /// - When: the object initializes missing region /// - Then: the configuration fails to initialize with regionMissing error func testConfigureFailureForMissingRegion() async { - let config = JSONValue(dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Section.maps.key, GeoPluginTestConfig.mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Section.maps.key, GeoPluginTestConfig.mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.regionMissing.errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.regionMissing.errorDescription + ) } } @@ -194,37 +224,45 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { /// - When: the object initializes with an invalid region /// - Then: the configuration fails to initialize with regionInvalid error func testConfigureFailureForInvalidRegion() async { - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, JSONValue(integerLiteral: 1)), - (AWSLocationGeoPluginConfiguration.Section.maps.key, GeoPluginTestConfig.mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, JSONValue(integerLiteral: 1)), + (AWSLocationGeoPluginConfiguration.Section.maps.key, GeoPluginTestConfig.mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.regionInvalid.errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.regionInvalid.errorDescription + ) } } - + /// - Given: geo plugin configuration /// - When: the object initializes with a missing default maps section /// - Then: the configuration fails to initialize with defaultMissing error func testConfigureFailureForMissingDefaultMapsSection() async { let mapsConfigJSON = JSONValue(dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, GeoPluginTestConfig.mapItemConfigJSON)) - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), + (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.defaultMissing(section: .maps).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.defaultMissing(section: .maps).errorDescription + ) } } - + /// - Given: geo plugin configuration /// - When: the object initializes without default map /// - Then: the configuration fails to initialize with mapDefaultNotFound error @@ -234,19 +272,25 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { let mapStyleConfigJSON = JSONValue(dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.style.key, mapStyleJSON)) let mapItemConfigJSON = JSONValue(dictionaryLiteral: (mapName, mapStyleConfigJSON)) - let mapsConfigJSON = JSONValue(dictionaryLiteral: + let mapsConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, mapItemConfigJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, GeoPluginTestConfig.testMapJSON)) - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) + (AWSLocationGeoPluginConfiguration.Node.default.key, GeoPluginTestConfig.testMapJSON) + ) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), + (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.mapDefaultNotFound(mapName: "testMap").errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.mapDefaultNotFound(mapName: "testMap").errorDescription + ) } } @@ -254,18 +298,24 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { /// - When: the object initializes with a invalid default maps section /// - Then: the configuration fails to initialize with defaultNotString error func testConfigureFailureForInvalidDefaultMapsSection() async { - let mapsConfigJSON = JSONValue(dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, GeoPluginTestConfig.mapItemConfigJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, JSONValue(integerLiteral: 1))) - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) + let mapsConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, GeoPluginTestConfig.mapItemConfigJSON), + (AWSLocationGeoPluginConfiguration.Node.default.key, JSONValue(integerLiteral: 1)) + ) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), + (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.defaultNotString(section: .maps).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.defaultNotString(section: .maps).errorDescription + ) } } @@ -275,60 +325,76 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { /// - When: the object initializes with a empty default maps section /// - Then: the configuration fails to initialize with defaultIsEmpty error func testConfigureFailureForEmptyDefaultMapsSection() async { - let mapsConfigJSON = JSONValue(dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, GeoPluginTestConfig.mapItemConfigJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, JSONValue(stringLiteral: ""))) - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) + let mapsConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, GeoPluginTestConfig.mapItemConfigJSON), + (AWSLocationGeoPluginConfiguration.Node.default.key, JSONValue(stringLiteral: "")) + ) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), + (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.defaultIsEmpty(section: .maps).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.defaultIsEmpty(section: .maps).errorDescription + ) } } - + /// - Given: geo plugin configuration /// - When: the object initializes with a items default maps section /// - Then: the configuration fails to initialize with itemsMissing error func testConfigureFailureForMissingItemsMapsSection() async { - let mapsConfigJSON = JSONValue(dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.default.key,GeoPluginTestConfig.testMapJSON)) - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) + let mapsConfigJSON = JSONValue(dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.default.key, GeoPluginTestConfig.testMapJSON)) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), + (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.itemsMissing(section: .maps).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.itemsMissing(section: .maps).errorDescription + ) } } - + /// - Given: geo plugin configuration /// - When: the object initializes with a invalid maps section /// - Then: the configuration fails to initialize with mapInvalid error func testConfigureFailureForInvalidMapsSection() async { let mapItemConfigJSON = JSONValue(dictionaryLiteral: ("testMap", JSONValue(stringLiteral: ""))) - let mapsConfigJSON = JSONValue(dictionaryLiteral: + let mapsConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, mapItemConfigJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, GeoPluginTestConfig.testMapJSON)) - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) + (AWSLocationGeoPluginConfiguration.Node.default.key, GeoPluginTestConfig.testMapJSON) + ) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), + (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.mapInvalid(mapName: "testMap").errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.mapInvalid(mapName: "testMap").errorDescription + ) } } - + /// - Given: geo plugin configuration /// - When: the object initializes with a invalid maps section /// - Then: the configuration fails to initialize with mapStyleMissing error @@ -336,23 +402,29 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { let mapStyleConfigJSON = JSONValue(dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, JSONValue(stringLiteral: ""))) let mapItemConfigJSON = JSONValue(dictionaryLiteral: ("testMap", mapStyleConfigJSON)) - let mapsConfigJSON = JSONValue(dictionaryLiteral: + let mapsConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, mapItemConfigJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, GeoPluginTestConfig.testMapJSON)) - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) + (AWSLocationGeoPluginConfiguration.Node.default.key, GeoPluginTestConfig.testMapJSON) + ) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), + (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.mapStyleMissing(mapName: "testMap").errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.mapStyleMissing(mapName: "testMap").errorDescription + ) } } - - + + /// - Given: geo plugin configuration /// - When: the object initializes with a invalid maps section /// - Then: the configuration fails to initialize with mapStyleMissing error @@ -362,12 +434,16 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { let mapStyleConfigJSON = JSONValue(dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.style.key, mapStyleJSON)) let mapItemConfigJSON = JSONValue(dictionaryLiteral: (mapName, mapStyleConfigJSON)) - let mapsConfigJSON = JSONValue(dictionaryLiteral: + let mapsConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, mapItemConfigJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, GeoPluginTestConfig.testMapJSON)) - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) + (AWSLocationGeoPluginConfiguration.Node.default.key, GeoPluginTestConfig.testMapJSON) + ) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), + (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case PluginError.pluginConfigurationError(_, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") @@ -375,7 +451,7 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { } } } - + /// - Given: geo plugin configuration /// - When: the object initializes with a invalid map style url /// - Then: the configuration fails to initialize with mapStyleIsNotString error @@ -385,19 +461,25 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { let mapStyleConfigJSON = JSONValue(dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.style.key, mapStyleJSON)) let mapItemConfigJSON = JSONValue(dictionaryLiteral: (mapName, mapStyleConfigJSON)) - let mapsConfigJSON = JSONValue(dictionaryLiteral: + let mapsConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, mapItemConfigJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, GeoPluginTestConfig.testMapJSON)) - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) + (AWSLocationGeoPluginConfiguration.Node.default.key, GeoPluginTestConfig.testMapJSON) + ) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), + (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.mapStyleIsNotString(mapName: mapName).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.mapStyleIsNotString(mapName: mapName).errorDescription + ) } } @@ -408,19 +490,25 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { let searchIndex = "testSearchIndex" let searchIndexJSON = JSONValue(stringLiteral: searchIndex) let searchItemsArrayJSON = JSONValue(stringLiteral: "") - let searchConfigJSON = JSONValue(dictionaryLiteral: + let searchConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, searchItemsArrayJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, searchIndexJSON)) - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, GeoPluginTestConfig.mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, searchConfigJSON)) + (AWSLocationGeoPluginConfiguration.Node.default.key, searchIndexJSON) + ) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), + (AWSLocationGeoPluginConfiguration.Section.maps.key, GeoPluginTestConfig.mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.itemsInvalid(section: .searchIndices).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.itemsInvalid(section: .searchIndices).errorDescription + ) } } @@ -431,22 +519,28 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { let searchIndex = "testSearchIndex" let searchIndexJSON = JSONValue(stringLiteral: searchIndex) let searchItemsArrayJSON = JSONValue(arrayLiteral: 1) - let searchConfigJSON = JSONValue(dictionaryLiteral: + let searchConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, searchItemsArrayJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, searchIndexJSON)) - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, GeoPluginTestConfig.mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, searchConfigJSON)) + (AWSLocationGeoPluginConfiguration.Node.default.key, searchIndexJSON) + ) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), + (AWSLocationGeoPluginConfiguration.Section.maps.key, GeoPluginTestConfig.mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.itemsIsNotStringArray(section: .searchIndices).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.itemsIsNotStringArray(section: .searchIndices).errorDescription + ) } } - + /// - Given: geo plugin configuration /// - When: configuration initializes with a mismatch search items and default item /// - Then: the configuration fails to initializes with searchDefaultNotFound error @@ -454,19 +548,25 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { let searchIndex = "testSearchIndex" let searchIndexJSON = JSONValue(stringLiteral: searchIndex) let searchItemsArrayJSON = JSONValue(arrayLiteral: JSONValue(stringLiteral: "test")) - let searchConfigJSON = JSONValue(dictionaryLiteral: + let searchConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, searchItemsArrayJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, searchIndexJSON)) - let config = JSONValue(dictionaryLiteral:(AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), - (AWSLocationGeoPluginConfiguration.Section.maps.key, GeoPluginTestConfig.mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, searchConfigJSON)) + (AWSLocationGeoPluginConfiguration.Node.default.key, searchIndexJSON) + ) + let config = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, GeoPluginTestConfig.regionJSON), + (AWSLocationGeoPluginConfiguration.Section.maps.key, GeoPluginTestConfig.mapsConfigJSON), + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, searchConfigJSON) + ) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.searchDefaultNotFound(indexName: searchIndex).errorDescription) + XCTAssertEqual( + errorDescription, + GeoPluginConfigError.searchDefaultNotFound(indexName: searchIndex).errorDescription + ) } } } diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSClientConfiguration.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSClientConfiguration.swift index 90031b94ae..a7c5689199 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSClientConfiguration.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSClientConfiguration.swift @@ -6,12 +6,12 @@ // import AWSClientRuntime -import ClientRuntime import AWSLocation +import ClientRuntime import Foundation -import XCTest -import SmithyHTTPAPI import Smithy +import SmithyHTTPAPI +import XCTest @testable import AWSLocationGeoPlugin @testable import AWSPluginsTestCommon @@ -20,9 +20,9 @@ extension LocationClient.LocationClientConfiguration { static func mock(region: String) throws -> LocationClient.LocationClientConfiguration { try .init( awsCredentialIdentityResolver: MockAWSAuthService().getCredentialIdentityResolver(), - awsRetryMode: .standard, + awsRetryMode: .standard, region: region, - signingRegion: "", + signingRegion: "", endpointResolver: MockEndPointResolver() ) } diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSLocation+ClientBehavior.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSLocation+ClientBehavior.swift index 3f7fbb6c27..87ec14aee0 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSLocation+ClientBehavior.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSLocation+ClientBehavior.swift @@ -6,38 +6,46 @@ // import AWSLocation -@testable import AWSLocationGeoPlugin import Foundation +@testable import AWSLocationGeoPlugin -extension MockAWSLocation { +public extension MockAWSLocation { - public func searchPlaceIndex(forText: SearchPlaceIndexForTextInput, - completionHandler: ((SearchPlaceIndexForTextOutput?, - Error?) -> Void)?) { + func searchPlaceIndex( + forText: SearchPlaceIndexForTextInput, + completionHandler: (( + SearchPlaceIndexForTextOutput?, + Error? + ) -> Void)? + ) { searchPlaceIndexForTextCalled += 1 searchPlaceIndexForTextRequest = forText - if let completionHandler = completionHandler { + if let completionHandler { completionHandler(SearchPlaceIndexForTextOutput(), nil) } } - public func searchPlaceIndex(forPosition: SearchPlaceIndexForPositionInput, - completionHandler: ((SearchPlaceIndexForPositionOutput?, - Error?) -> Void)?) { + func searchPlaceIndex( + forPosition: SearchPlaceIndexForPositionInput, + completionHandler: (( + SearchPlaceIndexForPositionOutput?, + Error? + ) -> Void)? + ) { searchPlaceIndexForPositionCalled += 1 searchPlaceIndexForPositionRequest = forPosition - if let completionHandler = completionHandler { + if let completionHandler { completionHandler(SearchPlaceIndexForPositionOutput(), nil) } } - public func searchPlaceIndex(forText: SearchPlaceIndexForTextInput) async throws -> SearchPlaceIndexForTextOutput { + func searchPlaceIndex(forText: SearchPlaceIndexForTextInput) async throws -> SearchPlaceIndexForTextOutput { searchPlaceIndexForTextCalled += 1 searchPlaceIndexForTextRequest = forText return SearchPlaceIndexForTextOutput() } - public func searchPlaceIndex(forPosition: SearchPlaceIndexForPositionInput) async throws -> SearchPlaceIndexForPositionOutput { + func searchPlaceIndex(forPosition: SearchPlaceIndexForPositionInput) async throws -> SearchPlaceIndexForPositionOutput { searchPlaceIndexForPositionCalled += 1 searchPlaceIndexForPositionRequest = forPosition return SearchPlaceIndexForPositionOutput() diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSLocation.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSLocation.swift index 0dc4080432..ce1ffe3c84 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSLocation.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSLocation.swift @@ -33,16 +33,16 @@ public class MockAWSLocation: AWSLocationBehavior { public func getEscapeHatch() -> LocationClient { getEscapeHatchCalled += 1 - return self.locationClient + return locationClient } } -extension MockAWSLocation { - public func verifyGetEscapeHatch() { +public extension MockAWSLocation { + func verifyGetEscapeHatch() { XCTAssertEqual(getEscapeHatchCalled, 1) } - public func verifySearchPlaceIndexForText(_ request: SearchPlaceIndexForTextInput) { + func verifySearchPlaceIndexForText(_ request: SearchPlaceIndexForTextInput) { XCTAssertEqual(searchPlaceIndexForTextCalled, 1) guard let receivedRequest = searchPlaceIndexForTextRequest else { XCTFail("Did not receive request.") @@ -59,7 +59,7 @@ extension MockAWSLocation { XCTAssertEqual(receivedRequest.maxResults, request.maxResults) } - public func verifySearchPlaceIndexForPosition(_ request: SearchPlaceIndexForPositionInput) { + func verifySearchPlaceIndexForPosition(_ request: SearchPlaceIndexForPositionInput) { XCTAssertEqual(searchPlaceIndexForPositionCalled, 1) guard let receivedRequest = searchPlaceIndexForPositionRequest else { XCTFail("Did not receive request.") diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Support/Constants/GeoPluginTestConfig.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Support/Constants/GeoPluginTestConfig.swift index cf11c975e3..4efca9c8cf 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Support/Constants/GeoPluginTestConfig.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Support/Constants/GeoPluginTestConfig.swift @@ -9,7 +9,7 @@ import Foundation @testable @_spi(InternalAmplifyConfiguration) import Amplify @testable import AWSLocationGeoPlugin -struct GeoPluginTestConfig { +enum GeoPluginTestConfig { static let timeout = 1.0 // Plugin Test Configuration @@ -35,31 +35,38 @@ struct GeoPluginTestConfig { static let mapItemConfigJSON = JSONValue(dictionaryLiteral: (map, mapStyleConfigJSON)) - static let mapsConfigJSON = JSONValue(dictionaryLiteral: + static let mapsConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, mapItemConfigJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, testMapJSON)) + (AWSLocationGeoPluginConfiguration.Node.default.key, testMapJSON) + ) // MARK: - Search Config JSON static let searchIndexJSON = JSONValue(stringLiteral: searchIndex) static let searchItemsArrayJSON = JSONValue(arrayLiteral: searchIndexJSON) - static let searchConfigJSON = JSONValue(dictionaryLiteral: + static let searchConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.items.key, searchItemsArrayJSON), - (AWSLocationGeoPluginConfiguration.Node.default.key, searchIndexJSON)) + (AWSLocationGeoPluginConfiguration.Node.default.key, searchIndexJSON) + ) // MARK: - Plugin Config JSON static let regionJSON = JSONValue(stringLiteral: regionName) - static let geoPluginConfigJSON = JSONValue(dictionaryLiteral: + static let geoPluginConfigJSON = JSONValue( + dictionaryLiteral: (AWSLocationGeoPluginConfiguration.Node.region.key, regionJSON), (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), - (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, searchConfigJSON)) + (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, searchConfigJSON) + ) static let geoPluginConfigAmplifyOutputs = AmplifyOutputsData( geo: .init( awsRegion: regionName, maps: .init(items: [map: .init(style: style)], default: map), searchIndices: .init(items: [searchIndex], default: searchIndex), - geofenceCollections: nil)) + geofenceCollections: nil + )) } diff --git a/AmplifyPlugins/Geo/Tests/GeoHostApp/AWSLocationGeoPluginIntegrationTests/AWSLocationGeoPluginIntegrationTests.swift b/AmplifyPlugins/Geo/Tests/GeoHostApp/AWSLocationGeoPluginIntegrationTests/AWSLocationGeoPluginIntegrationTests.swift index 682ef7f4be..6ff5a7bdf1 100644 --- a/AmplifyPlugins/Geo/Tests/GeoHostApp/AWSLocationGeoPluginIntegrationTests/AWSLocationGeoPluginIntegrationTests.swift +++ b/AmplifyPlugins/Geo/Tests/GeoHostApp/AWSLocationGeoPluginIntegrationTests/AWSLocationGeoPluginIntegrationTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSLocation +import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin diff --git a/AmplifyPlugins/Geo/Tests/GeoHostApp/GeoStressTests/GeoStressTests.swift b/AmplifyPlugins/Geo/Tests/GeoHostApp/GeoStressTests/GeoStressTests.swift index a512832e52..5b9c77b5f6 100644 --- a/AmplifyPlugins/Geo/Tests/GeoHostApp/GeoStressTests/GeoStressTests.swift +++ b/AmplifyPlugins/Geo/Tests/GeoHostApp/GeoStressTests/GeoStressTests.swift @@ -33,9 +33,9 @@ final class GeoStressTests: XCTestCase { override func tearDown() async throws { await Amplify.reset() } - + // MARK: - Stress Tests - + /// Test if concurrent execution of search(for: text) is successful /// - Given: Geo plugin with a valid configuration. /// - When: @@ -44,9 +44,9 @@ final class GeoStressTests: XCTestCase { /// - Place results are returned. /// func testMultipleSearchForText() async { - let successExpectation = expectation(description: "searchForText was successful") + let successExpectation = expectation(description: "searchForText was successful") successExpectation.expectedFulfillmentCount = concurrencyLimit - for _ in 1...concurrencyLimit { + for _ in 1 ... concurrencyLimit { Task { do { let options = Geo.SearchForTextOptions(area: .near(coordinates)) @@ -58,10 +58,10 @@ final class GeoStressTests: XCTestCase { } } } - + await fulfillment(of: [successExpectation], timeout: timeout) } - + /// Test if concurrent execution of search(for: coordinates) is successful /// - Given: Geo plugin with a valid configuration. /// - When: @@ -72,7 +72,7 @@ final class GeoStressTests: XCTestCase { func testMultipleSearchForCoordinates() async { let successExpectation = expectation(description: "searchForCoordinates was successful") successExpectation.expectedFulfillmentCount = concurrencyLimit - for _ in 1...concurrencyLimit { + for _ in 1 ... concurrencyLimit { Task { do { let places = try await Amplify.Geo.search(for: coordinates, options: nil) @@ -84,7 +84,7 @@ final class GeoStressTests: XCTestCase { } } } - + await fulfillment(of: [successExpectation], timeout: timeout) } diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/AWSPinpointBehavior.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/AWSPinpointBehavior.swift index 9f4c7d5d7a..e46287ddff 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/AWSPinpointBehavior.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/AWSPinpointBehavior.swift @@ -46,8 +46,10 @@ public protocol AWSPinpointBehavior { /// the automatic submission is disabled /// - Parameter interval: How much to wait between submissions /// - Parameter onSubmit: An optional callback to be run after each submission happens - func setAutomaticSubmitEventsInterval(_ interval: TimeInterval, - onSubmit: AnalyticsClientBehaviour.SubmitResult?) + func setAutomaticSubmitEventsInterval( + _ interval: TimeInterval, + onSubmit: AnalyticsClientBehaviour.SubmitResult? + ) // MARK: Session /// Beings automatically tracking session activity in the device. @@ -67,8 +69,10 @@ public protocol AWSPinpointBehavior { /// Updates the current endpoint with the provided profile /// - Parameter endpointProfile: The new endpoint profile /// - Parameter source: The source that originates this endpoint update, i.e. analytics or pushNotifications - func updateEndpoint(with endpointProfile: PinpointEndpointProfile, - source: AWSPinpointSource) async throws + func updateEndpoint( + with endpointProfile: PinpointEndpointProfile, + source: AWSPinpointSource + ) async throws } @_spi(InternalAWSPinpoint) diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/AnalyticsClient.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/AnalyticsClient.swift index c7db089487..9374091b5c 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/AnalyticsClient.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/AnalyticsClient.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import StoreKit import Amplify import AWSPinpoint +import Foundation +import StoreKit @_spi(InternalAWSPinpoint) public protocol AnalyticsClientBehaviour: Actor { - typealias SubmitResult = ((Result<[PinpointEvent], Error>) -> Void) + typealias SubmitResult = (Result<[PinpointEvent], Error>) -> Void nonisolated var pinpointClient: PinpointClientProtocol { get } func addGlobalAttribute(_ attribute: String, forKey key: String) @@ -27,18 +27,24 @@ public protocol AnalyticsClientBehaviour: Actor { func setRemoteGlobalAttributes(_ attributes: [String: String]) func removeAllRemoteGlobalAttributes() - func setAutomaticSubmitEventsInterval(_ interval: TimeInterval, - onSubmit: SubmitResult?) + func setAutomaticSubmitEventsInterval( + _ interval: TimeInterval, + onSubmit: SubmitResult? + ) @discardableResult func submitEvents() async throws -> [PinpointEvent] func update(_ session: PinpointSession) async throws - nonisolated func createAppleMonetizationEvent(with transaction: SKPaymentTransaction, - with product: SKProduct) -> PinpointEvent - nonisolated func createVirtualMonetizationEvent(withProductId productId: String, - withItemPrice itemPrice: Double, - withQuantity quantity: Int, - withCurrency currency: String) -> PinpointEvent + nonisolated func createAppleMonetizationEvent( + with transaction: SKPaymentTransaction, + with product: SKProduct + ) -> PinpointEvent + nonisolated func createVirtualMonetizationEvent( + withProductId productId: String, + withItemPrice itemPrice: Double, + withQuantity quantity: Int, + withCurrency currency: String + ) -> PinpointEvent nonisolated func createEvent(withEventType eventType: String) -> PinpointEvent } @@ -67,8 +73,10 @@ actor AnalyticsClient: AnalyticsClientBehaviour { private lazy var eventTypeAttributes: [String: PinpointEventAttributes] = [:] private lazy var eventTypeMetrics: [String: PinpointEventMetrics] = [:] - init(eventRecorder: AnalyticsEventRecording, - sessionProvider: @escaping SessionProvider) { + init( + eventRecorder: AnalyticsEventRecording, + sessionProvider: @escaping SessionProvider + ) { self.eventRecorder = eventRecorder self.sessionProvider = sessionProvider } @@ -76,28 +84,42 @@ actor AnalyticsClient: AnalyticsClientBehaviour { // Actors no longer use 'convenience' for inits. This is a warning in swift 5.7 and an error in swift 6+. // However, 'convenience' is required to build with swift <5.7 #if swift(>=5.7) - init(applicationId: String, - pinpointClient: PinpointClientProtocol, - endpointClient: EndpointClientBehaviour, - sessionProvider: @escaping SessionProvider) throws { - let dbAdapter = try SQLiteLocalStorageAdapter(prefixPath: Constants.eventRecorderStoragePathPrefix, - databaseName: applicationId) - let eventRecorder = try EventRecorder(appId: applicationId, - storage: AnalyticsEventSQLStorage(dbAdapter: dbAdapter), - pinpointClient: pinpointClient, endpointClient: endpointClient) + init( + applicationId: String, + pinpointClient: PinpointClientProtocol, + endpointClient: EndpointClientBehaviour, + sessionProvider: @escaping SessionProvider + ) throws { + let dbAdapter = try SQLiteLocalStorageAdapter( + prefixPath: Constants.eventRecorderStoragePathPrefix, + databaseName: applicationId + ) + let eventRecorder = try EventRecorder( + appId: applicationId, + storage: AnalyticsEventSQLStorage(dbAdapter: dbAdapter), + pinpointClient: pinpointClient, + endpointClient: endpointClient + ) self.init(eventRecorder: eventRecorder, sessionProvider: sessionProvider) } #else - convenience init(applicationId: String, - pinpointClient: PinpointClientProtocol, - endpointClient: EndpointClientBehaviour, - sessionProvider: @escaping SessionProvider) throws { - let dbAdapter = try SQLiteLocalStorageAdapter(prefixPath: Constants.eventRecorderStoragePathPrefix, - databaseName: applicationId) - let eventRecorder = try EventRecorder(appId: applicationId, - storage: AnalyticsEventSQLStorage(dbAdapter: dbAdapter), - pinpointClient: pinpointClient, endpointClient: endpointClient) + convenience init( + applicationId: String, + pinpointClient: PinpointClientProtocol, + endpointClient: EndpointClientBehaviour, + sessionProvider: @escaping SessionProvider + ) throws { + let dbAdapter = try SQLiteLocalStorageAdapter( + prefixPath: Constants.eventRecorderStoragePathPrefix, + databaseName: applicationId + ) + let eventRecorder = try EventRecorder( + appId: applicationId, + storage: AnalyticsEventSQLStorage(dbAdapter: dbAdapter), + pinpointClient: pinpointClient, + endpointClient: endpointClient + ) self.init(eventRecorder: eventRecorder, sessionProvider: sessionProvider) } @@ -160,65 +182,91 @@ actor AnalyticsClient: AnalyticsClientBehaviour { } // MARK: - Monetization events - nonisolated func createAppleMonetizationEvent(with transaction: SKPaymentTransaction, - with product: SKProduct) -> PinpointEvent { + nonisolated func createAppleMonetizationEvent( + with transaction: SKPaymentTransaction, + with product: SKProduct + ) -> PinpointEvent { let numberFormatter = NumberFormatter() numberFormatter.locale = product.priceLocale numberFormatter.numberStyle = .currency numberFormatter.isLenient = true - return createMonetizationEvent(withStore: Constants.PurchaseEvent.appleStore, - productId: product.productIdentifier, - quantity: transaction.payment.quantity, - itemPrice: product.price.doubleValue, - currencyCode: product.priceLocale.currencyCode, - formattedItemPrice: numberFormatter.string(from: product.price), - transactionId: transaction.transactionIdentifier) + return createMonetizationEvent( + withStore: Constants.PurchaseEvent.appleStore, + productId: product.productIdentifier, + quantity: transaction.payment.quantity, + itemPrice: product.price.doubleValue, + currencyCode: product.priceLocale.currencyCode, + formattedItemPrice: numberFormatter.string(from: product.price), + transactionId: transaction.transactionIdentifier + ) } - nonisolated func createVirtualMonetizationEvent(withProductId productId: String, - withItemPrice itemPrice: Double, - withQuantity quantity: Int, - withCurrency currency: String) -> PinpointEvent { - return createMonetizationEvent(withStore: Constants.PurchaseEvent.virtual, - productId: productId, - quantity: quantity, - itemPrice: itemPrice, - currencyCode: currency) + nonisolated func createVirtualMonetizationEvent( + withProductId productId: String, + withItemPrice itemPrice: Double, + withQuantity quantity: Int, + withCurrency currency: String + ) -> PinpointEvent { + return createMonetizationEvent( + withStore: Constants.PurchaseEvent.virtual, + productId: productId, + quantity: quantity, + itemPrice: itemPrice, + currencyCode: currency + ) } - private nonisolated func createMonetizationEvent(withStore store: String, - productId: String, - quantity: Int, - itemPrice: Double, - currencyCode: String?, - formattedItemPrice: String? = nil, - priceLocale: Locale? = nil, - transactionId: String? = nil) -> PinpointEvent { - let monetizationEvent = PinpointEvent(eventType: Constants.PurchaseEvent.name, - session: sessionProvider()) - monetizationEvent.addAttribute(store, - forKey: Constants.PurchaseEvent.Keys.store) - monetizationEvent.addAttribute(productId, - forKey: Constants.PurchaseEvent.Keys.productId) - monetizationEvent.addMetric(quantity, - forKey: Constants.PurchaseEvent.Keys.quantity) - monetizationEvent.addMetric(itemPrice, - forKey: Constants.PurchaseEvent.Keys.itemPrice) - - if let currencyCode = currencyCode { - monetizationEvent.addAttribute(currencyCode, - forKey: Constants.PurchaseEvent.Keys.currency) + private nonisolated func createMonetizationEvent( + withStore store: String, + productId: String, + quantity: Int, + itemPrice: Double, + currencyCode: String?, + formattedItemPrice: String? = nil, + priceLocale: Locale? = nil, + transactionId: String? = nil + ) -> PinpointEvent { + let monetizationEvent = PinpointEvent( + eventType: Constants.PurchaseEvent.name, + session: sessionProvider() + ) + monetizationEvent.addAttribute( + store, + forKey: Constants.PurchaseEvent.Keys.store + ) + monetizationEvent.addAttribute( + productId, + forKey: Constants.PurchaseEvent.Keys.productId + ) + monetizationEvent.addMetric( + quantity, + forKey: Constants.PurchaseEvent.Keys.quantity + ) + monetizationEvent.addMetric( + itemPrice, + forKey: Constants.PurchaseEvent.Keys.itemPrice + ) + + if let currencyCode { + monetizationEvent.addAttribute( + currencyCode, + forKey: Constants.PurchaseEvent.Keys.currency + ) } - if let formattedItemPrice = formattedItemPrice { - monetizationEvent.addAttribute(formattedItemPrice, - forKey: Constants.PurchaseEvent.Keys.priceFormatted) + if let formattedItemPrice { + monetizationEvent.addAttribute( + formattedItemPrice, + forKey: Constants.PurchaseEvent.Keys.priceFormatted + ) } - if let transactionId = transactionId { - monetizationEvent.addAttribute(transactionId, - forKey: Constants.PurchaseEvent.Keys.transactionId) + if let transactionId { + monetizationEvent.addAttribute( + transactionId, + forKey: Constants.PurchaseEvent.Keys.transactionId + ) } return monetizationEvent @@ -227,8 +275,10 @@ actor AnalyticsClient: AnalyticsClientBehaviour { // MARK: - Event recording nonisolated func createEvent(withEventType eventType: String) -> PinpointEvent { precondition(!eventType.isEmpty, "Event types must be at least 1 character in length.") - return PinpointEvent(eventType: eventType, - session: sessionProvider()) + return PinpointEvent( + eventType: eventType, + session: sessionProvider() + ) } func record(_ event: PinpointEvent) async throws { @@ -263,13 +313,15 @@ actor AnalyticsClient: AnalyticsClientBehaviour { func submitEvents() async throws -> [PinpointEvent] { return try await eventRecorder.submitAllEvents() } - + func update(_ session: PinpointSession) async throws { try await eventRecorder.update(session) } - func setAutomaticSubmitEventsInterval(_ interval: TimeInterval, - onSubmit: SubmitResult?) { + func setAutomaticSubmitEventsInterval( + _ interval: TimeInterval, + onSubmit: SubmitResult? + ) { guard automaticSubmitEventsInterval != interval else { let message = interval == .zero ? "disabled" : "set to \(interval) seconds" log.verbose("Automatic Submission of Events' interval is already \(message).") @@ -287,7 +339,7 @@ actor AnalyticsClient: AnalyticsClientBehaviour { automaticSubmitEventsTimer = RepeatingTimer.createRepeatingTimer( timeInterval: automaticSubmitEventsInterval, eventHandler: { [weak self] in - guard let self = self else { return } + guard let self else { return } Task { self.log.debug("AutoFlushTimer triggered, flushing events") do { @@ -297,7 +349,8 @@ actor AnalyticsClient: AnalyticsClientBehaviour { onSubmit?(.failure(error)) } } - }) + } + ) automaticSubmitEventsTimer?.resume() } } @@ -313,13 +366,13 @@ extension AnalyticsClient: DefaultLogger { } extension AnalyticsClient { - private struct Constants { - struct PurchaseEvent { + private enum Constants { + enum PurchaseEvent { static let name = "_monetization.purchase" static let appleStore = "Apple" static let virtual = "Virtual" - struct Keys { + enum Keys { static let productId = "_product_id" static let quantity = "_quantity" static let itemPrice = "_item_price" diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/EventRecorder.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/EventRecorder.swift index 7782ddb733..b5d2ab2dbb 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/EventRecorder.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/EventRecorder.swift @@ -7,9 +7,9 @@ import Amplify import AWSCognitoAuthPlugin +import enum AwsCommonRuntimeKit.CommonRunTimeError import AWSPinpoint import ClientRuntime -import enum AwsCommonRuntimeKit.CommonRunTimeError import Foundation import SmithyHTTPAPI @@ -26,10 +26,12 @@ protocol AnalyticsEventRecording: Actor { /// - ofType: event type /// - withSessionId: session identifier /// - setAttributes: event attributes - func updateAttributesOfEvents(ofType: String, - withSessionId: PinpointSession.SessionId, - setAttributes: [String: String]) throws - + func updateAttributesOfEvents( + ofType: String, + withSessionId: PinpointSession.SessionId, + setAttributes: [String: String] + ) throws + /// Updates the session information of the events that match the same sessionId. /// - Parameter session: The session to update func update(_ session: PinpointSession) throws @@ -54,10 +56,12 @@ actor EventRecorder: AnalyticsEventRecording { /// - storage: A storage object that conforms to AnalyticsEventStorage /// - pinpointClient: A Pinpoint client /// - endpointClient: An EndpointClientBehaviour client - init(appId: String, - storage: AnalyticsEventStorage, - pinpointClient: PinpointClientProtocol, - endpointClient: EndpointClientBehaviour) throws { + init( + appId: String, + storage: AnalyticsEventStorage, + pinpointClient: PinpointClientProtocol, + endpointClient: EndpointClientBehaviour + ) throws { self.appId = appId self.storage = storage self.pinpointClient = pinpointClient @@ -75,12 +79,16 @@ actor EventRecorder: AnalyticsEventRecording { try storage.checkDiskSize(limit: Constants.pinpointClientByteLimitDefault) } - func updateAttributesOfEvents(ofType eventType: String, - withSessionId sessionId: PinpointSession.SessionId, - setAttributes attributes: [String: String]) throws { - try storage.updateEvents(ofType: eventType, - withSessionId: sessionId, - setAttributes: attributes) + func updateAttributesOfEvents( + ofType eventType: String, + withSessionId sessionId: PinpointSession.SessionId, + setAttributes attributes: [String: String] + ) throws { + try storage.updateEvents( + ofType: eventType, + withSessionId: sessionId, + setAttributes: attributes + ) } func update(_ session: PinpointSession) throws { @@ -129,8 +137,10 @@ actor EventRecorder: AnalyticsEventRecording { } } - private func submit(pinpointEvents: [PinpointEvent], - endpointProfile: PinpointEndpointProfile) async throws { + private func submit( + pinpointEvents: [PinpointEvent], + endpointProfile: PinpointEndpointProfile + ) async throws { var clientEvents = [String: PinpointClientTypes.Event]() var pinpointEventsById = [String: PinpointEvent]() for event in pinpointEvents { @@ -139,11 +149,15 @@ actor EventRecorder: AnalyticsEventRecording { } let publicEndpoint = endpointClient.convertToPublicEndpoint(endpointProfile) - let eventsBatch = PinpointClientTypes.EventsBatch(endpoint: publicEndpoint, - events: clientEvents) + let eventsBatch = PinpointClientTypes.EventsBatch( + endpoint: publicEndpoint, + events: clientEvents + ) let batchItem = [endpointProfile.endpointId: eventsBatch] - let putEventsInput = PutEventsInput(applicationId: appId, - eventsRequest: .init(batchItem: batchItem)) + let putEventsInput = PutEventsInput( + applicationId: appId, + eventsRequest: .init(batchItem: batchItem) + ) await identifySource(for: pinpointEvents) do { @@ -156,7 +170,7 @@ actor EventRecorder: AnalyticsEventRecording { throw AnalyticsError.unknown(errorMessage) } - let endpointResponseMap = results.compactMap { $0.value.endpointItemResponse } + let endpointResponseMap = results.compactMap(\.value.endpointItemResponse) for endpointResponse in endpointResponseMap { if HTTPStatusCode.accepted.rawValue == endpointResponse.statusCode { log.verbose("EndpointProfile updated successfully.") @@ -165,7 +179,7 @@ actor EventRecorder: AnalyticsEventRecording { } } - let eventsResponseMap = results.compactMap { $0.value.eventsItemResponse } + let eventsResponseMap = results.compactMap(\.value.eventsItemResponse) for (eventId, eventResponse) in eventsResponseMap.flatMap({ $0 }) { guard let event = pinpointEventsById[eventId] else { continue } let responseMessage = eventResponse.message ?? "Unknown" @@ -182,11 +196,10 @@ actor EventRecorder: AnalyticsEventRecording { } else { // On other failures, increment the event retry counter incrementEventRetry(eventId: eventId) - let retryMessage: String - if event.retryCount < Constants.maxNumberOfRetries { - retryMessage = "Event will be retried" + let retryMessage = if event.retryCount < Constants.maxNumberOfRetries { + "Event will be retried" } else { - retryMessage = "Event will be discarded because it exceeded its max retry attempts" + "Event will be discarded because it exceeded its max retry attempts" } log.verbose("Submit attempt #\(event.retryCount + 1) for event with id \(eventId) failed.") log.error("Unable to successfully deliver event with id \(eventId) to the server. \(retryMessage). Error: \(responseMessage)") @@ -327,9 +340,11 @@ actor EventRecorder: AnalyticsEventRecording { events.forEach { incrementEventRetry(eventId: $0.id) } } - private func retry(times: Int = Constants.defaultNumberOfRetriesForStorageOperations, - onErrorMessage: String, - _ closure: () throws -> Void) { + private func retry( + times: Int = Constants.defaultNumberOfRetriesForStorageOperations, + onErrorMessage: String, + _ closure: () throws -> Void + ) { do { try closure() } catch { @@ -358,30 +373,30 @@ extension EventRecorder: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.analytics.displayName, forNamespace: String(describing: self)) } - nonisolated public var log: Logger { + public nonisolated var log: Logger { Self.log } } extension EventRecorder { - private struct Constants { + private enum Constants { static let maxEventsSubmittedPerBatch = 100 - static let pinpointClientByteLimitDefault = 5 * 1024 * 1024 // 5MB - static let pinpointClientBatchRecordByteLimitDefault = 512 * 1024 // 0.5MB - static let pinpointClientBatchRecordByteLimitMax = 4 * 1024 * 1024 // 4MB + static let pinpointClientByteLimitDefault = 5 * 1_024 * 1_024 // 5MB + static let pinpointClientBatchRecordByteLimitDefault = 512 * 1_024 // 0.5MB + static let pinpointClientBatchRecordByteLimitMax = 4 * 1_024 * 1_024 // 4MB static let acceptedResponseMessage = "Accepted" static let defaultNumberOfRetriesForStorageOperations = 1 static let maxNumberOfRetries = 3 } } -private extension Array where Element == PinpointEvent { +private extension [PinpointEvent] { func numberOfPushNotificationsEvents() -> Int { - let pushNotificationsEvents = filter({ event in + let pushNotificationsEvents = filter { event in event.eventType.contains(".opened_notification") || event.eventType.contains(".received_foreground") || event.eventType.contains(".received_background") - }) + } return pushNotificationsEvents.count } } diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/AnalyticsEventSQLStorage.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/AnalyticsEventSQLStorage.swift index 260c982b1d..4257c1cedf 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/AnalyticsEventSQLStorage.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/AnalyticsEventSQLStorage.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation import SQLite /// This is a temporary placeholder class to interface with the SQLiteLocalStorageAdapter @@ -101,9 +101,11 @@ class AnalyticsEventSQLStorage: AnalyticsEventStorage { _ = try dbAdapter.executeQuery(deleteStatement, []) } - func updateEvents(ofType eventType: String, - withSessionId sessionId: PinpointSession.SessionId, - setAttributes attributes: [String: String]) throws { + func updateEvents( + ofType eventType: String, + withSessionId sessionId: PinpointSession.SessionId, + setAttributes attributes: [String: String] + ) throws { let updateStatement = """ UPDATE Event SET attributes = ? @@ -113,9 +115,10 @@ class AnalyticsEventSQLStorage: AnalyticsEventStorage { _ = try dbAdapter.executeQuery(updateStatement, [ PinpointEvent.archiveEventAttributes(attributes), sessionId, - eventType]) + eventType + ]) } - + func updateSession(_ session: PinpointSession) throws { let updateStatement = """ UPDATE Event @@ -226,15 +229,15 @@ class AnalyticsEventSQLStorage: AnalyticsEventStorage { } /// Check the disk usage limit of the local database. - /// If database is over the limit then delete all dirty events and oldest event + /// If database is over the limit then delete all dirty events and oldest event /// - Parameter limit: the size limit of the database in Byte unit func checkDiskSize(limit: Byte) throws { if dbAdapter.diskBytesUsed > limit { - try self.deleteDirtyEvents() + try deleteDirtyEvents() } if dbAdapter.diskBytesUsed > limit { - try self.deleteOldestEvent() + try deleteOldestEvent() } } } diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/AnalyticsEventStorage.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/AnalyticsEventStorage.swift index d5aea17167..8fcf6db67c 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/AnalyticsEventStorage.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/AnalyticsEventStorage.swift @@ -26,10 +26,12 @@ protocol AnalyticsEventStorage { /// - ofType: event type /// - sessionId: session identifier /// - setAttributes: event attributes - func updateEvents(ofType: String, - withSessionId: PinpointSession.SessionId, - setAttributes: [String: String]) throws - + func updateEvents( + ofType: String, + withSessionId: PinpointSession.SessionId, + setAttributes: [String: String] + ) throws + /// Updates the session information of the events that match the same sessionId. /// - Parameter session: The session to update func updateSession(_ session: PinpointSession) throws diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/PinpointEvent+Bindings.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/PinpointEvent+Bindings.swift index 571d60b41d..7ebc4965af 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/PinpointEvent+Bindings.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/PinpointEvent+Bindings.swift @@ -55,7 +55,8 @@ extension PinpointEvent { let dateFormatter = DateFormatter.iso8601Formatter guard let sessionId = element[EventPropertyIndex.sessionId] as? String, let startTimeString = element[EventPropertyIndex.sessionStartTime] as? String, - let startTime = dateFormatter.date(from: startTimeString) else { + let startTime = dateFormatter.date(from: startTimeString) + else { return nil } @@ -68,7 +69,8 @@ extension PinpointEvent { guard let eventType = element[EventPropertyIndex.eventType] as? String, let eventTimestampValue = element[EventPropertyIndex.eventTimestamp] as? String, - let timestamp = dateFormatter.date(from: eventTimestampValue) else { + let timestamp = dateFormatter.date(from: eventTimestampValue) + else { return nil } @@ -100,7 +102,7 @@ extension PinpointEvent { return pinpointEvent } - struct EventPropertyIndex { + enum EventPropertyIndex { static let id = 0 static let attributes = 1 static let eventType = 2 diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/SQLiteLocalStorageAdapter.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/SQLiteLocalStorageAdapter.swift index ae32ef37fd..0c4f147cd6 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/SQLiteLocalStorageAdapter.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/LocalStorage/SQLiteLocalStorageAdapter.swift @@ -23,15 +23,19 @@ final class SQLiteLocalStorageAdapter: SQLStorageProtocol { /// - prefixPath: A prefix to be used for the database path. Defaults to none. /// - databaseName: The database name /// - fileManager: A FileManagerBehaviour instance to interact with the disk. Defaults to FileManager.default - init(prefixPath: String = "", - databaseName: String, - fileManager: FileManagerBehaviour = FileManager.default) throws { + init( + prefixPath: String = "", + databaseName: String, + fileManager: FileManagerBehaviour = FileManager.default + ) throws { let dbDirectoryPath = try Self.getTmpPath() .appendingPathComponent(prefixPath) var dbFilePath = dbDirectoryPath.appendingPathComponent(databaseName) if !fileManager.fileExists(atPath: dbDirectoryPath.path) { - try fileManager.createDirectory(atPath: dbDirectoryPath.path, - withIntermediateDirectories: true) + try fileManager.createDirectory( + atPath: dbDirectoryPath.path, + withIntermediateDirectories: true + ) } let connection: Connection @@ -77,7 +81,7 @@ final class SQLiteLocalStorageAdapter: SQLStorageProtocol { /// Create a SQL table /// - Parameter statement: SQL statement to create a table func createTable(_ statement: String) throws { - guard let connection = connection else { + guard let connection else { throw LocalStorageError.missingConnection } @@ -94,7 +98,7 @@ final class SQLiteLocalStorageAdapter: SQLStorageProtocol { /// - bindings: A collection of SQL bindings to prepare with the query statement /// - Returns: A SQL statement result from the query func executeQuery(_ statement: String, _ bindings: [Binding?]) throws -> Statement { - guard let connection = connection else { + guard let connection else { throw LocalStorageError.missingConnection } diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/PinpointEvent+PinpointClientTypes.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/PinpointEvent+PinpointClientTypes.swift index e2c78b496e..ef39960ac0 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/PinpointEvent+PinpointClientTypes.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/PinpointEvent+PinpointClientTypes.swift @@ -7,12 +7,12 @@ import AWSPinpoint import AWSPluginsCore -import InternalAmplifyCredentials import Foundation +import InternalAmplifyCredentials extension PinpointEvent { private var clientTypeSession: PinpointClientTypes.Session? { - var sessionDuration: Int? = nil + var sessionDuration: Int? if let duration = session.duration { // If the session duration cannot be represented by Int, return a nil session instead. // This is extremely unlikely to happen since a session's stopTime is set when the app is closed diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/PinpointEvent.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/PinpointEvent.swift index a8296abaed..9d92cd94f8 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/PinpointEvent.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/PinpointEvent.swift @@ -17,14 +17,16 @@ public class PinpointEvent: AnalyticsPropertiesModel { let eventDate: Date let session: PinpointSession let retryCount: Int - private(set) public lazy var attributes: [String: String] = [:] - private(set) public lazy var metrics: [String: Double] = [:] - - init(id: String = UUID().uuidString, - eventType: String, - eventDate: Date = Date(), - session: PinpointSession, - retryCount: Int = 0) { + public private(set) lazy var attributes: [String: String] = [:] + public private(set) lazy var metrics: [String: Double] = [:] + + init( + id: String = UUID().uuidString, + eventType: String, + eventDate: Date = Date(), + session: PinpointSession, + retryCount: Int = 0 + ) { self.id = id self.eventType = eventType self.eventDate = eventDate diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Configuration/AWSPinpointPluginConfiguration.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Configuration/AWSPinpointPluginConfiguration.swift index 6c2969fa3d..ec22d2fbb0 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Configuration/AWSPinpointPluginConfiguration.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Configuration/AWSPinpointPluginConfiguration.swift @@ -6,8 +6,8 @@ // @_spi(InternalAmplifyConfiguration) import Amplify -import AWSPinpoint import AWSClientRuntime +import AWSPinpoint import Foundation @_spi(InternalAWSPinpoint) @@ -26,14 +26,16 @@ public struct AWSPinpointPluginConfiguration { ) } - self.init( - appId: try AWSPinpointPluginConfiguration.getAppId(configObject), - region: try AWSPinpointPluginConfiguration.getRegion(configObject) + try self.init( + appId: AWSPinpointPluginConfiguration.getAppId(configObject), + region: AWSPinpointPluginConfiguration.getRegion(configObject) ) } - public init(appId: String, - region: String) { + public init( + appId: String, + region: String + ) { self.appId = appId self.region = region } diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/AWSPinpointFactory.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/AWSPinpointFactory.swift index d0b93f647d..886b021470 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/AWSPinpointFactory.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/AWSPinpointFactory.swift @@ -24,8 +24,10 @@ public class AWSPinpointFactory { static var provisioningProfileReader: ProvisioningProfileReader = .default - public static func sharedPinpoint(appId: String, - region: String) throws -> AWSPinpointBehavior { + public static func sharedPinpoint( + appId: String, + region: String + ) throws -> AWSPinpointBehavior { let key = PinpointContextKey(appId: appId, region: region) if let existingContext = instances[key] { return existingContext diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/PinpointContext+AWSPinpointBehavior.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/PinpointContext+AWSPinpointBehavior.swift index 30fe00f951..0b15e93011 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/PinpointContext+AWSPinpointBehavior.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/PinpointContext+AWSPinpointBehavior.swift @@ -31,8 +31,10 @@ extension PinpointContext: AWSPinpointBehavior { await endpointClient.currentEndpointProfile() } - func updateEndpoint(with endpointProfile: PinpointEndpointProfile, - source: AWSPinpointSource) async throws { + func updateEndpoint( + with endpointProfile: PinpointEndpointProfile, + source: AWSPinpointSource + ) async throws { await PinpointRequestsRegistry.shared.registerSource(source, for: .updateEndpoint) try await endpointClient.updateEndpointProfile(with: endpointProfile) } @@ -61,8 +63,10 @@ extension PinpointContext: AWSPinpointBehavior { await analyticsClient.setRemoteGlobalAttributes(attributes) } - func setAutomaticSubmitEventsInterval(_ interval: TimeInterval, - onSubmit: AnalyticsClientBehaviour.SubmitResult?) { + func setAutomaticSubmitEventsInterval( + _ interval: TimeInterval, + onSubmit: AnalyticsClientBehaviour.SubmitResult? + ) { Task { await analyticsClient.setAutomaticSubmitEventsInterval(interval, onSubmit: onSubmit) } diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/PinpointContext.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/PinpointContext.swift index dc5a653a7d..af84ceaa07 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/PinpointContext.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/PinpointContext.swift @@ -50,14 +50,16 @@ extension FileManager: FileManagerBehaviour, DefaultLogger { } func createDirectory(atPath path: String, withIntermediateDirectories createIntermediates: Bool) throws { - try createDirectory(atPath: path, - withIntermediateDirectories: createIntermediates, - attributes: nil) + try createDirectory( + atPath: path, + withIntermediateDirectories: createIntermediates, + attributes: nil + ) } func fileSize(for url: URL) -> Byte { do { - let attributes = try self.attributesOfItem(atPath: url.path) + let attributes = try attributesOfItem(atPath: url.path) return attributes[.size] as? Byte ?? 0 } catch { log.error("Error getting file size with error \(error)") @@ -82,10 +84,12 @@ struct PinpointContextConfiguration { /// Setting this flag to true will set the Endpoint Profile to have a channel type of "APNS_SANDBOX". let isDebug: Bool - init(appId: String, - region: String, - credentialIdentityResolver: some AWSCredentialIdentityResolver, - isDebug: Bool = false) { + init( + appId: String, + region: String, + credentialIdentityResolver: some AWSCredentialIdentityResolver, + isDebug: Bool = false + ) { self.appId = appId self.region = region self.credentialIdentityResolver = credentialIdentityResolver @@ -110,37 +114,51 @@ class PinpointContext { private let configuration: PinpointContextConfiguration private let storage: PinpointContextStorage - init(with configuration: PinpointContextConfiguration, - endpointInformationProvider: EndpointInformationProvider = DefaultEndpointInformationProvider(), - userDefaults: UserDefaultsBehaviour = UserDefaults.standard, - keychainStore: KeychainStoreBehavior = KeychainStore(service: PinpointContext.Constants.Keychain.service), - fileManager: FileManagerBehaviour = FileManager.default, - archiver: AmplifyArchiverBehaviour = AmplifyArchiver(), - remoteNotificationsHelper: RemoteNotificationsBehaviour = .default) throws { + init( + with configuration: PinpointContextConfiguration, + endpointInformationProvider: EndpointInformationProvider = DefaultEndpointInformationProvider(), + userDefaults: UserDefaultsBehaviour = UserDefaults.standard, + keychainStore: KeychainStoreBehavior = KeychainStore(service: PinpointContext.Constants.Keychain.service), + fileManager: FileManagerBehaviour = FileManager.default, + archiver: AmplifyArchiverBehaviour = AmplifyArchiver(), + remoteNotificationsHelper: RemoteNotificationsBehaviour = .default + ) throws { self.configuration = configuration - storage = PinpointContextStorage(userDefaults: userDefaults, - keychainStore: keychainStore, - fileManager: fileManager, - archiver: archiver) - uniqueId = Self.retrieveUniqueId(applicationId: configuration.appId, storage: storage) - - let pinpointClient = try PinpointClient(region: configuration.region, - credentialIdentityResolver: configuration.credentialIdentityResolver) - - endpointClient = EndpointClient(configuration: .init(appId: configuration.appId, - uniqueDeviceId: uniqueId, - isDebug: configuration.isDebug), - pinpointClient: pinpointClient, - endpointInformationProvider: endpointInformationProvider, - userDefaults: userDefaults, - keychain: keychainStore, - remoteNotificationsHelper: remoteNotificationsHelper) - - sessionClient = SessionClient(archiver: archiver, - configuration: .init(appId: configuration.appId, - uniqueDeviceId: uniqueId), - endpointClient: endpointClient, - userDefaults: userDefaults) + self.storage = PinpointContextStorage( + userDefaults: userDefaults, + keychainStore: keychainStore, + fileManager: fileManager, + archiver: archiver + ) + self.uniqueId = Self.retrieveUniqueId(applicationId: configuration.appId, storage: storage) + + let pinpointClient = try PinpointClient( + region: configuration.region, + credentialIdentityResolver: configuration.credentialIdentityResolver + ) + + self.endpointClient = EndpointClient( + configuration: .init( + appId: configuration.appId, + uniqueDeviceId: uniqueId, + isDebug: configuration.isDebug + ), + pinpointClient: pinpointClient, + endpointInformationProvider: endpointInformationProvider, + userDefaults: userDefaults, + keychain: keychainStore, + remoteNotificationsHelper: remoteNotificationsHelper + ) + + self.sessionClient = SessionClient( + archiver: archiver, + configuration: .init( + appId: configuration.appId, + uniqueDeviceId: uniqueId + ), + endpointClient: endpointClient, + userDefaults: userDefaults + ) let sessionProvider: () -> PinpointSession = { [weak sessionClient] in guard let sessionClient = sessionClient else { @@ -149,19 +167,25 @@ class PinpointContext { return sessionClient.currentSession } - analyticsClient = try AnalyticsClient(applicationId: configuration.appId, - pinpointClient: pinpointClient, - endpointClient: endpointClient, - sessionProvider: sessionProvider) + self.analyticsClient = try AnalyticsClient( + applicationId: configuration.appId, + pinpointClient: pinpointClient, + endpointClient: endpointClient, + sessionProvider: sessionProvider + ) sessionClient.analyticsClient = analyticsClient sessionClient.startPinpointSession() setAutomaticSubmitEventsInterval(Constants.defaultAutomaticSubmissionInterval) } - private static func legacyPreferencesFilePath(applicationId: String, - storage: PinpointContextStorage) -> String? { - let applicationSupportDirectoryUrls = storage.fileManager.urls(for: .applicationSupportDirectory, - in: .userDomainMask) + private static func legacyPreferencesFilePath( + applicationId: String, + storage: PinpointContextStorage + ) -> String? { + let applicationSupportDirectoryUrls = storage.fileManager.urls( + for: .applicationSupportDirectory, + in: .userDomainMask + ) let preferencesFileUrl = applicationSupportDirectoryUrls.first? .appendingPathComponent(Constants.Preferences.mobileAnalyticsRoot) .appendingPathComponent(applicationId) @@ -170,10 +194,14 @@ class PinpointContext { return preferencesFileUrl?.path } - private static func removeLegacyPreferencesFile(applicationId: String, - storage: PinpointContextStorage) { - guard let preferencesPath = legacyPreferencesFilePath(applicationId: applicationId, - storage: storage) else { + private static func removeLegacyPreferencesFile( + applicationId: String, + storage: PinpointContextStorage + ) { + guard let preferencesPath = legacyPreferencesFilePath( + applicationId: applicationId, + storage: storage + ) else { return } @@ -184,13 +212,19 @@ class PinpointContext { } } - private static func legacyUniqueId(applicationId: String, - storage: PinpointContextStorage) -> String? { - guard let preferencesPath = legacyPreferencesFilePath(applicationId: applicationId, - storage: storage), + private static func legacyUniqueId( + applicationId: String, + storage: PinpointContextStorage + ) -> String? { + guard let preferencesPath = legacyPreferencesFilePath( + applicationId: applicationId, + storage: storage + ), storage.fileManager.fileExists(atPath: preferencesPath), - let preferencesJson = try? JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: preferencesPath)), - options: .mutableContainers) as? [String: String] else { + let preferencesJson = try? JSONSerialization.jsonObject( + with: Data(contentsOf: URL(fileURLWithPath: preferencesPath)), + options: .mutableContainers + ) as? [String: String] else { return nil } @@ -199,20 +233,22 @@ class PinpointContext { /** Attempts to retrieve a previously generated Device Unique ID. - + This value can be present in 3 places: 1. In a preferences file stored in disk 2. In UserDefauls 3. In the Keychain - + 1 and 2 are legacy storage options that are supportted for backwards compability, but once retrieved those values will be migrated to the Keychain. - + If no existing Device Unique ID is found, a new one will be generated and stored in the Keychain. - + - Returns: A string representing the Device Unique ID */ - private static func retrieveUniqueId(applicationId: String, - storage: PinpointContextStorage) -> String { + private static func retrieveUniqueId( + applicationId: String, + storage: PinpointContextStorage + ) -> String { // 1. Look for the UniqueId in the Keychain if let deviceUniqueId = try? storage.keychainStore._getString(Constants.Keychain.uniqueIdKey) { return deviceUniqueId @@ -283,15 +319,15 @@ extension PinpointContext: DefaultLogger { } extension PinpointContext { - struct Constants { + enum Constants { static let defaultAutomaticSubmissionInterval: TimeInterval = 60 - struct Preferences { + enum Preferences { static let mobileAnalyticsRoot = "com.amazonaws.MobileAnalytics" static let fileName = "preferences" static let uniqueIdKey = "UniqueId" } - struct Keychain { + enum Keychain { static let service = "com.amazonaws.AWSPinpointContext" static let uniqueIdKey = "com.amazonaws.AWSPinpointContextKeychainUniqueIdKey" } diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Endpoint/EndpointClient.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Endpoint/EndpointClient.swift index e89118f4bb..f71e0f824a 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Endpoint/EndpointClient.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Endpoint/EndpointClient.swift @@ -40,13 +40,14 @@ actor EndpointClient: EndpointClientBehaviour { private var endpointProfile: PinpointEndpointProfile? private static let defaultDateFormatter = ISO8601DateFormatter() - init(configuration: EndpointClient.Configuration, - pinpointClient: PinpointClientProtocol, - archiver: AmplifyArchiverBehaviour = AmplifyArchiver(), - endpointInformationProvider: EndpointInformationProvider, - userDefaults: UserDefaultsBehaviour = UserDefaults.standard, - keychain: KeychainStoreBehavior = KeychainStore(service: PinpointContext.Constants.Keychain.service), - remoteNotificationsHelper: RemoteNotificationsBehaviour = .default + init( + configuration: EndpointClient.Configuration, + pinpointClient: PinpointClientProtocol, + archiver: AmplifyArchiverBehaviour = AmplifyArchiver(), + endpointInformationProvider: EndpointInformationProvider, + userDefaults: UserDefaultsBehaviour = UserDefaults.standard, + keychain: KeychainStoreBehavior = KeychainStore(service: PinpointContext.Constants.Keychain.service), + remoteNotificationsHelper: RemoteNotificationsBehaviour = .default ) { self.configuration = configuration self.pinpointClient = pinpointClient @@ -76,7 +77,7 @@ actor EndpointClient: EndpointClientBehaviour { private func retrieveOrCreateEndpointProfile() async -> PinpointEndpointProfile { // 1. Look for the local endpointProfile variable - if let endpointProfile = endpointProfile { + if let endpointProfile { return endpointProfile } @@ -89,8 +90,10 @@ actor EndpointClient: EndpointClientBehaviour { try? keychain._remove(Constants.endpointProfileKey) // Create a new PinpointEndpointProfile - return await configure(endpointProfile: PinpointEndpointProfile(applicationId: configuration.appId, - endpointId: configuration.uniqueDeviceId)) + return await configure(endpointProfile: PinpointEndpointProfile( + applicationId: configuration.appId, + endpointId: configuration.uniqueDeviceId + )) } private func configure(endpointProfile: PinpointEndpointProfile) async -> PinpointEndpointProfile { @@ -132,7 +135,8 @@ actor EndpointClient: EndpointClientBehaviour { private func updateStoredAPNsToken(from endpointProfile: PinpointEndpointProfile) { do { guard let deviceToken = endpointProfile.deviceToken, - let apnsToken = Data(hexString: deviceToken) else { + let apnsToken = Data(hexString: deviceToken) + else { try keychain._remove(Constants.deviceTokenKey) return } @@ -152,18 +156,22 @@ actor EndpointClient: EndpointClientBehaviour { let channelType = getChannelType(from: endpointProfile) let effectiveDate = getEffectiveDateIso8601FractionalSeconds(from: endpointProfile) let optOut = getOptOut(from: endpointProfile) - let endpointRequest = PinpointClientTypes.EndpointRequest(address: endpointProfile.deviceToken, - attributes: endpointProfile.attributes, - channelType: channelType, - demographic: endpointProfile.demographic, - effectiveDate: effectiveDate, - location: endpointProfile.location, - metrics: endpointProfile.metrics, - optOut: optOut, - user: endpointProfile.user) - return UpdateEndpointInput(applicationId: endpointProfile.applicationId, - endpointId: endpointProfile.endpointId, - endpointRequest: endpointRequest) + let endpointRequest = PinpointClientTypes.EndpointRequest( + address: endpointProfile.deviceToken, + attributes: endpointProfile.attributes, + channelType: channelType, + demographic: endpointProfile.demographic, + effectiveDate: effectiveDate, + location: endpointProfile.location, + metrics: endpointProfile.metrics, + optOut: optOut, + user: endpointProfile.user + ) + return UpdateEndpointInput( + applicationId: endpointProfile.applicationId, + endpointId: endpointProfile.endpointId, + endpointRequest: endpointRequest + ) } nonisolated func convertToPublicEndpoint(_ endpointProfile: PinpointEndpointProfile) -> PinpointClientTypes.PublicEndpoint { @@ -179,22 +187,23 @@ actor EndpointClient: EndpointClientBehaviour { location: endpointProfile.location, metrics: endpointProfile.metrics, optOut: optOut, - user: endpointProfile.user) + user: endpointProfile.user + ) return publicEndpoint } - nonisolated private func getChannelType(from endpointProfile: PinpointEndpointProfile) -> PinpointClientTypes.ChannelType? { + private nonisolated func getChannelType(from endpointProfile: PinpointEndpointProfile) -> PinpointClientTypes.ChannelType? { if endpointProfile.deviceToken == nil { return nil } return endpointProfile.isDebug ? .apnsSandbox : .apns } - nonisolated private func getEffectiveDateIso8601FractionalSeconds(from endpointProfile: PinpointEndpointProfile) -> String { + private nonisolated func getEffectiveDateIso8601FractionalSeconds(from endpointProfile: PinpointEndpointProfile) -> String { endpointProfile.effectiveDate.asISO8601String } - nonisolated private func getOptOut(from endpointProfile: PinpointEndpointProfile) -> String? { + private nonisolated func getOptOut(from endpointProfile: PinpointEndpointProfile) -> String? { if endpointProfile.deviceToken == nil { return nil } @@ -245,8 +254,8 @@ extension EndpointClient: DefaultLogger { } extension EndpointClient { - struct Constants { - struct OptOut { + enum Constants { + enum OptOut { static let all = "ALL" static let none = "NONE" } @@ -257,20 +266,24 @@ extension EndpointClient { } extension PinpointClientTypes.EndpointDemographic { - struct Constants { + enum Constants { static let appleMake = "apple" static let unknown = "Unknown" } - init(device: EndpointInformation, - locale: String = Locale.autoupdatingCurrent.identifier, - timezone: String = TimeZone.current.identifier) { - self.init(appVersion: device.appVersion, - locale: locale, - make: Constants.appleMake, - model: device.model, - platform: device.platform.name, - platformVersion: device.platform.version, - timezone: timezone) + init( + device: EndpointInformation, + locale: String = Locale.autoupdatingCurrent.identifier, + timezone: String = TimeZone.current.identifier + ) { + self.init( + appVersion: device.appVersion, + locale: locale, + make: Constants.appleMake, + model: device.model, + platform: device.platform.name, + platformVersion: device.platform.version, + timezone: timezone + ) } } diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Endpoint/PinpointClientTypes+Codable.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Endpoint/PinpointClientTypes+Codable.swift index c1964cb00b..28619dcab3 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Endpoint/PinpointClientTypes+Codable.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Endpoint/PinpointClientTypes+Codable.swift @@ -113,7 +113,7 @@ extension PinpointClientTypes.EndpointUser: Codable, Equatable { } public static func == ( - lhs: PinpointClientTypes.EndpointUser, + lhs: PinpointClientTypes.EndpointUser, rhs: PinpointClientTypes.EndpointUser ) -> Bool { return lhs.userAttributes == rhs.userAttributes diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Endpoint/PinpointEndpointProfile.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Endpoint/PinpointEndpointProfile.swift index c2d6cca523..9530f66267 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Endpoint/PinpointEndpointProfile.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Endpoint/PinpointEndpointProfile.swift @@ -25,15 +25,17 @@ public struct PinpointEndpointProfile: Codable, Equatable { private(set) var attributes: [String: [String]] = [:] private(set) var metrics: [String: Double] = [:] - init(applicationId: String, - endpointId: String, - deviceToken: DeviceToken? = nil, - effectiveDate: Date = Date(), - isDebug: Bool = false, - isOptOut: Bool = false, - location: PinpointClientTypes.EndpointLocation = .init(), - demographic: PinpointClientTypes.EndpointDemographic = .init(), - user: PinpointClientTypes.EndpointUser = .init()) { + init( + applicationId: String, + endpointId: String, + deviceToken: DeviceToken? = nil, + effectiveDate: Date = Date(), + isDebug: Bool = false, + isOptOut: Bool = false, + location: PinpointClientTypes.EndpointLocation = .init(), + demographic: PinpointClientTypes.EndpointDemographic = .init(), + user: PinpointClientTypes.EndpointUser = .init() + ) { self.applicationId = applicationId self.endpointId = endpointId self.deviceToken = deviceToken @@ -80,14 +82,14 @@ public struct PinpointEndpointProfile: Codable, Equatable { } private mutating func addCustomProperties(_ properties: [String: UserProfilePropertyValue]?) { - guard let properties = properties else { return } + guard let properties else { return } for (key, value) in properties { setCustomProperty(value, forKey: key) } } private mutating func addUserAttributes(_ attributes: [String: [String]]?) { - guard let attributes = attributes else { return } + guard let attributes else { return } let userAttributes = user.userAttributes ?? [:] user.userAttributes = userAttributes.merging( attributes, @@ -95,8 +97,10 @@ public struct PinpointEndpointProfile: Codable, Equatable { ) } - private mutating func setCustomProperty(_ value: UserProfilePropertyValue, - forKey key: String) { + private mutating func setCustomProperty( + _ value: UserProfilePropertyValue, + forKey key: String + ) { if let value = value as? String { attributes[key] = [value] } else if let values = value as? [String] { @@ -111,16 +115,16 @@ public struct PinpointEndpointProfile: Codable, Equatable { } } -extension Optional where Wrapped == PinpointEndpointProfile.DeviceToken { +extension PinpointEndpointProfile.DeviceToken? { var isNotEmpty: Bool { - guard let self = self else { return false } + guard let self else { return false } return !self.isEmpty } } extension PinpointEndpointProfile { - struct Constants { - struct AttributeKeys { + enum Constants { + enum AttributeKeys { static let email = "email" static let name = "name" static let plan = "plan" diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/CommonRunTimeError+isConnectivityError.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/CommonRunTimeError+isConnectivityError.swift index c3a3c3dd20..7e651b1f2d 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/CommonRunTimeError+isConnectivityError.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/CommonRunTimeError+isConnectivityError.swift @@ -6,8 +6,8 @@ // import Amplify -import AwsCIo import AwsCHttp +import AwsCIo import AwsCommonRuntimeKit import AWSPinpoint import ClientRuntime diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/Date+Formatting.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/Date+Formatting.swift index d1dfabbe31..3c31e11d38 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/Date+Formatting.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/Date+Formatting.swift @@ -29,7 +29,7 @@ extension Date { typealias Millisecond = Int64 var millisecondsSince1970: Millisecond { - return Int64(self.timeIntervalSince1970 * 1000) + return Int64(timeIntervalSince1970 * 1_000) } var asISO8601String: String { @@ -39,7 +39,7 @@ extension Date { extension Date.Millisecond { var asDate: Date { - return Date(timeIntervalSince1970: TimeInterval(self / 1000)) - .addingTimeInterval(TimeInterval(Double(self % 1000) / 1000 )) + return Date(timeIntervalSince1970: TimeInterval(self / 1_000)) + .addingTimeInterval(TimeInterval(Double(self % 1_000) / 1_000 )) } } diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/PinpointClient+CredentialsProvider.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/PinpointClient+CredentialsProvider.swift index 15c437b3ea..b75a090c16 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/PinpointClient+CredentialsProvider.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/PinpointClient+CredentialsProvider.swift @@ -6,8 +6,8 @@ // import AWSClientRuntime -import AWSPluginsCore import AWSPinpoint +import AWSPluginsCore @_spi(PluginHTTPClientEngine) import InternalAmplifyCredentials import SmithyIdentity diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Session/ActivityTracking/ActivityTracker.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Session/ActivityTracking/ActivityTracker.swift index d85da389d3..782c19ddbc 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Session/ActivityTracking/ActivityTracker.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Session/ActivityTracking/ActivityTracker.swift @@ -28,7 +28,7 @@ enum ApplicationState { case runningInBackground(isStale: Bool) case terminated - struct Resolver { + enum Resolver { static func resolve(currentState: ApplicationState, event: ActivityEvent) -> ApplicationState { if case .terminated = currentState { log.warn("Unexpected state transition. Received event \(event) in \(currentState) state.") @@ -122,25 +122,33 @@ class ActivityTracker: ActivityTrackerBehaviour { applicationWillTerminateNotification ] - init(backgroundTrackingTimeout: TimeInterval = .infinity, - stateMachine: StateMachine? = nil) { + init( + backgroundTrackingTimeout: TimeInterval = .infinity, + stateMachine: StateMachine? = nil + ) { self.backgroundTrackingTimeout = backgroundTrackingTimeout - self.stateMachine = stateMachine ?? StateMachine(initialState: .initializing, - resolver: ApplicationState.Resolver.resolve(currentState:event:)) + self.stateMachine = stateMachine ?? StateMachine( + initialState: .initializing, + resolver: ApplicationState.Resolver.resolve(currentState:event:) + ) for notification in ActivityTracker.notifications { - NotificationCenter.default.addObserver(self, - selector: #selector(handleApplicationStateChange), - name: notification, - object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(handleApplicationStateChange), + name: notification, + object: nil + ) } } deinit { for notification in ActivityTracker.notifications { - NotificationCenter.default.removeObserver(self, - name: notification, - object: nil) + NotificationCenter.default.removeObserver( + self, + name: notification, + object: nil + ) } stateMachineSubscriberToken = nil } @@ -197,7 +205,7 @@ class ActivityTracker: ActivityTrackerBehaviour { #if canImport(UIKit) extension ActivityTracker { - struct Constants { + enum Constants { static let backgroundTask = "com.amazonaws.AWSPinpointSessionBackgroundTask" } } diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Session/ActivityTracking/StateMachine.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Session/ActivityTracking/StateMachine.swift index 58bbe66676..32afd7d2c9 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Session/ActivityTracking/StateMachine.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Session/ActivityTracking/StateMachine.swift @@ -15,8 +15,10 @@ extension AnyCancellable: StateMachineSubscriberToken {} class StateMachine { typealias Reducer = (State, Event) -> State - private let queue = DispatchQueue(label: "com.amazonaws.Amplify.StateMachine<\(State.self), \(Event.self)>", - target: DispatchQueue.global()) + private let queue = DispatchQueue( + label: "com.amazonaws.Amplify.StateMachine<\(State.self), \(Event.self)>", + target: DispatchQueue.global() + ) private var reducer: Reducer #if canImport(Combine) diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Session/PinpointSession.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Session/PinpointSession.swift index 3a43fc8bce..5d5e435299 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Session/PinpointSession.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Session/PinpointSession.swift @@ -27,19 +27,25 @@ public struct PinpointSession: Codable { return stopTime } } - + private var state: State = .active - init(appId: String, - uniqueId: String) { - sessionId = Self.generateSessionId(appId: appId, - uniqueId: uniqueId) - startTime = Date() + init( + appId: String, + uniqueId: String + ) { + self.sessionId = Self.generateSessionId( + appId: appId, + uniqueId: uniqueId + ) + self.startTime = Date() } - init(sessionId: SessionId, - startTime: Date, - stopTime: Date?) { + init( + sessionId: SessionId, + startTime: Date, + stopTime: Date? + ) { self.sessionId = sessionId self.startTime = startTime if let stopTime { @@ -54,7 +60,7 @@ public struct PinpointSession: Codable { return false } - + var isStopped: Bool { if case .stopped = state { return true @@ -83,8 +89,10 @@ public struct PinpointSession: Codable { state = .active } - private static func generateSessionId(appId: String, - uniqueId: String) -> SessionId { + private static func generateSessionId( + appId: String, + uniqueId: String + ) -> SessionId { let now = Date() let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(abbreviation: Constants.Date.defaultTimezone) @@ -98,12 +106,16 @@ public struct PinpointSession: Codable { dateFormatter.dateFormat = Constants.Date.timeFormat let timestampTime = dateFormatter.string(from: now) - let appIdKey = appId.padding(toLength: Constants.maxAppKeyLength, - withPad: Constants.paddingChar, - startingAt: 0) - let uniqueIdKey = uniqueId.padding(toLength: Constants.maxUniqueIdLength, - withPad: Constants.paddingChar, - startingAt: 0) + let appIdKey = appId.padding( + toLength: Constants.maxAppKeyLength, + withPad: Constants.paddingChar, + startingAt: 0 + ) + let uniqueIdKey = uniqueId.padding( + toLength: Constants.maxUniqueIdLength, + withPad: Constants.paddingChar, + startingAt: 0 + ) // Create Session ID formatted as - - -