From c993076333428c43ec4b55e398c8afd3b4ac4b8a Mon Sep 17 00:00:00 2001 From: Tuan Pham Date: Tue, 3 Sep 2024 12:45:09 -0500 Subject: [PATCH 1/5] chore(core): resolve swiftformat errors and warnings --- .../AWSAPIPluginDataStoreOptions.swift | 5 +- .../AWSPluginsCore/AWSPluginOptions.swift | 5 +- .../Auth/AWSAuthModeStrategy.swift | 35 +++++---- .../AWSPluginsCore/Auth/AWSAuthService.swift | 2 +- .../Auth/AWSAuthServiceBehavior.swift | 2 +- .../Auth/AWSAuthSessionBehavior.swift | 10 +-- .../Auth/AWSAuthorizationType.swift | 6 +- .../Auth/AmplifyAuthorizationType.swift | 1 - .../Auth/AuthAWSCredentialsProvider.swift | 9 ++- .../AWSAuthorizationConfiguration.swift | 15 ++-- .../Keychain/KeychainStatus.swift | 6 +- .../Keychain/KeychainStore.swift | 4 +- .../Keychain/KeychainStoreAttributes.swift | 2 +- .../Model/AnyModel/AnyModel+Codable.swift | 2 +- .../Model/AnyModel/AnyModel+Subscript.swift | 6 +- .../Model/AnyModel/AnyModel.swift | 10 +-- .../Model/Decorator/AuthRuleDecorator.swift | 44 +++++++----- .../ConflictResolutionDecorator.swift | 25 ++++--- .../Decorator/DirectiveNameDecorator.swift | 14 ++-- .../Model/Decorator/FilterDecorator.swift | 6 +- .../IncludeAssociationDecorator.swift | 10 +-- .../ModelBasedGraphQLDocumentDecorator.swift | 2 +- .../Model/Decorator/ModelDecorator.swift | 12 ++-- .../Model/Decorator/ModelIdDecorator.swift | 23 +++--- .../Model/Decorator/PaginationDecorator.swift | 12 ++-- .../GraphQLDocument/GraphQLMutation.swift | 5 +- .../Model/GraphQLDocument/GraphQLQuery.swift | 5 +- .../GraphQLDocument/GraphQLSubscription.swift | 3 +- .../ModelBasedGraphQLDocumentBuilder.swift | 4 +- .../SingleDirectiveGraphQLDocument.swift | 15 ++-- .../GraphQLRequest+AnyModelWithSync.swift | 48 ++++++++----- .../GraphQLRequest/GraphQLRequest+Model.swift | 64 ++++++++++------- .../Model/Support/AuthRule+Extension.swift | 25 ++++--- .../Model/Support/Model+GraphQL.swift | 23 +++--- .../Model/Support/ModelSchema+GraphQL.swift | 25 ++++--- .../Support/QueryPredicate+GraphQL.swift | 22 +++--- .../Model/Support/SelectionSet.swift | 27 +++---- .../ModelSync/ModelSyncMetadata+Schema.swift | 8 +-- .../Sync/ModelSync/ModelSyncMetadata.swift | 3 +- .../MutationSyncMetadata+Schema.swift | 8 +-- .../AWSPluginsCore/Sync/PaginatedList.swift | 10 +-- .../WebSocket/AmplifyNetworkMonitor.swift | 4 +- .../WebSocket/RetryWithJitter.swift | 15 ++-- .../WebSocket/WebSocketClient.swift | 71 +++++++++---------- .../WebSocket/WebSocketEvent.swift | 1 - .../WebSocket/WebSocketInterceptor.swift | 1 - .../WebSocketNetworkMonitorProtocol.swift | 3 +- .../Auth/AuthModeStrategyTests.swift | 2 +- .../ModelMultipleOwnerAuthRuleTests.swift | 8 ++- .../ModelReadUpdateAuthRuleTests.swift | 3 +- ...lWithOwnerAuthAndGroupWithGroupClaim.swift | 6 +- .../ModelWithOwnerAuthAndMultiGroup.swift | 3 +- .../ModelWithOwnerFieldAuthRuleTests.swift | 9 ++- .../GraphQLCreateMutationTests.swift | 4 +- .../GraphQLGetQueryTests.swift | 4 +- ...raphQLRequestEmbeddableTypeJSONTests.swift | 3 +- .../GraphQLRequestEmbeddableTypeTests.swift | 3 +- ...aphQLRequestOptionalAssociationTests.swift | 2 +- .../GraphQLRequest/MockAWSAuthUser.swift | 1 + .../Support/AuthRuleExtensionTests.swift | 2 +- ...yPredicateEvaluateGeneratedBoolTests.swift | 1 + ...yPredicateEvaluateGeneratedDateTests.swift | 1 + ...dicateEvaluateGeneratedDateTimeTests.swift | 1 + ...icateEvaluateGeneratedDoubleIntTests.swift | 1 + ...redicateEvaluateGeneratedDoubleTests.swift | 1 + ...ryPredicateEvaluateGeneratedIntTests.swift | 1 + ...redicateEvaluateGeneratedStringTests.swift | 1 + ...yPredicateEvaluateGeneratedTimeTests.swift | 1 + .../QueryPredicateEvaluateGenerator.swift | 45 ++++++++---- .../Query/QueryPredicateEvaluateTests.swift | 1 + .../WebSocket/LocalWebSocketServer.swift | 10 ++- .../WebSocket/RetryWithJitterTests.swift | 9 ++- .../WebSocket/WebSocketClientTests.swift | 9 ++- .../MockAWSAuthService.swift | 4 +- .../MockAWSSignatureV4Signer.swift | 7 +- .../AWSAuthCredentialsProviderBehavior.swift | 2 +- .../AWSAuthService+CredentialsProvider.swift | 2 +- .../AmplifyAWSServiceConfiguration.swift | 2 +- .../AmplifyAWSSignatureV4Signer.swift | 9 +-- .../AuthTokenProvider.swift | 2 +- .../ClientRuntimeFoundationBridge.swift | 2 +- .../FoundationClientEngine.swift | 4 +- .../FoundationClientEngineError.swift | 2 +- .../PluginClientEngine.swift | 4 +- .../SdkHttpRequest+updatingUserAgent.swift | 6 +- .../UserAgentSettingClientEngine.swift | 10 +-- .../UserAgentSuffixAppender.swift | 2 +- .../IAMCredentialProvider.swift | 2 +- ...lifyAWSServiceConfiguration+Platform.swift | 8 +-- .../Auth/AWSAuthServiceTests.swift | 2 +- .../UserAgentSettingClientEngineTests.swift | 4 +- .../Utils/UserAgentSuffixAppenderTests.swift | 2 +- 92 files changed, 484 insertions(+), 382 deletions(-) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift b/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift index f3035b76f0..9cac54243a 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 /// @@ -21,7 +21,8 @@ public struct AWSAPIPluginDataStoreOptions { public let modelName: String public init(authType: AWSAuthorizationType?, - modelName: String) { + modelName: String) + { self.authType = authType self.modelName = modelName } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift b/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift index b6f83ec2b3..0b8e60b572 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 /// @@ -38,7 +38,8 @@ public struct AWSPluginOptions { public let modelName: String? public init(authType: AWSAuthorizationType?, - modelName: String) { + 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..ca4ab63a71 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,17 @@ 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 { + operation: ModelOperation) -> AWSAuthorizationTypeIterator + { return AWSAuthorizationTypeIterator(withValues: [.inferred]) } public func authTypesFor(schema: ModelSchema, - operations: [ModelOperation]) -> AWSAuthorizationTypeIterator { + operations: [ModelOperation]) -> AWSAuthorizationTypeIterator + { return AWSAuthorizationTypeIterator(withValues: [.inferred]) } } @@ -129,7 +131,7 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { private typealias AuthPriority = Int - required public init() {} + public required init() {} private static func defaultAuthTypeFor(authStrategy: AuthStrategy) -> AWSAuthorizationType { switch authStrategy { @@ -199,7 +201,8 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { /// Use provider priority to sort if rules have the same strategy private static let comparator = { (rule1: AuthRule, rule2: AuthRule) -> Bool in if let providerRule1 = rule1.provider, - let providerRule2 = rule2.provider, rule1.allow == rule2.allow { + let providerRule2 = rule2.provider, rule1.allow == rule2.allow + { return priorityOf(authRuleProvider: providerRule1) < priorityOf(authRuleProvider: providerRule2) } return priorityOf(authStrategy: rule1.allow) < priorityOf(authStrategy: rule2.allow) @@ -211,7 +214,8 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { /// - operation: model operation /// - Returns: an iterator for the applicable auth rules public func authTypesFor(schema: ModelSchema, - operation: ModelOperation) async -> AWSAuthorizationTypeIterator { + operation: ModelOperation) async -> AWSAuthorizationTypeIterator + { return await authTypesFor(schema: schema, operations: [operation]) } @@ -221,18 +225,19 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { /// - operations: model operations /// - Returns: an iterator for the applicable auth rules public func authTypesFor(schema: ModelSchema, - operations: [ModelOperation]) async -> AWSAuthorizationTypeIterator { + 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..735e2178d4 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 { 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 c08e8821c8..57ae11a6b4 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..55c09c07cd 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 @@ -20,8 +20,9 @@ public enum AWSAuthorizationConfiguration { // MARK: - AWSAuthorizationConfiguration factory extension AWSAuthorizationConfiguration { private static func awsIAMAuthorizationConfiguration(region: String?) - throws -> AWSAuthorizationConfiguration { - guard let region = region else { + throws -> AWSAuthorizationConfiguration + { + guard let region else { throw PluginError.pluginConfigurationError("Region is not set for IAM", "Set the region") } @@ -29,9 +30,10 @@ extension AWSAuthorizationConfiguration { } private static func apiKeyAuthorizationConfiguration(apiKey: String?) - throws -> AWSAuthorizationConfiguration { + throws -> AWSAuthorizationConfiguration + { - guard let apiKey = apiKey else { + guard let apiKey else { throw PluginError.pluginConfigurationError( "Could not get `ApiKey` from plugin configuration", """ @@ -55,7 +57,8 @@ extension AWSAuthorizationConfiguration { /// - Returns: an `AWSAuthorizationConfiguration` according to the provided `authType` public static func makeConfiguration(authType: AWSAuthorizationType, region: String?, - apiKey: String?) throws -> AWSAuthorizationConfiguration { + 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 6327676c83..58d400da16 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..bcfcefa40b 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,20 +33,20 @@ 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, diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift index 0cf0f79d04..fd63b5752e 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] @@ -38,18 +38,21 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { /// - 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) { + authType: AWSAuthorizationType? = nil) + { self.input = authRuleDecoratorInput self.authType = authType } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + modelType: Model.Type) -> SingleDirectiveGraphQLDocument + { decorate(document, modelSchema: modelType.schema) } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument + { let authRules = modelSchema.authRules .filterBy(authType: authType) .filterBy(ownerFieldType: .string, modelSchema: modelSchema) @@ -59,7 +62,7 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { var decorateDocument = document let readRestrictingStaticGroups = authRules.groupClaimsToReadRestrictingStaticGroups() - authRules.forEach { authRule in + for authRule in authRules { decorateDocument = decorateAuthStrategy(document: decorateDocument, authRule: authRule, readRestrictingStaticGroups: readRestrictingStaticGroups) @@ -69,9 +72,11 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { private func decorateAuthStrategy(document: SingleDirectiveGraphQLDocument, authRule: AuthRule, - readRestrictingStaticGroups: [String: Set]) -> SingleDirectiveGraphQLDocument { + readRestrictingStaticGroups: [String: Set]) -> SingleDirectiveGraphQLDocument + { guard authRule.allow == .owner, - var selectionSet = document.selectionSet else { + var selectionSet = document.selectionSet + else { return document } @@ -82,11 +87,12 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { let tokenClaims = claims, authRule.isReadRestrictingOwner() && isNotInReadRestrictingStaticGroup(jwtTokenClaims: tokenClaims, - readRestrictingStaticGroups: readRestrictingStaticGroups) { + readRestrictingStaticGroups: readRestrictingStaticGroups) + { var inputs = document.inputs let identityClaimValue = resolveIdentityClaimValue(identityClaim: authRule.identityClaimOrDefault(), claims: tokenClaims) - if let identityClaimValue = identityClaimValue { + if let identityClaimValue { inputs[ownerField] = GraphQLDocumentInput(type: "String!", value: .scalar(identityClaimValue)) } return document.copy(inputs: inputs, selectionSet: selectionSet) @@ -107,7 +113,8 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { } private func isNotInReadRestrictingStaticGroup(jwtTokenClaims: IdentityClaimsDictionary, - readRestrictingStaticGroups: [String: Set]) -> Bool { + readRestrictingStaticGroups: [String: Set]) -> Bool + { for (groupClaim, readRestrictingStaticGroupsPerClaim) in readRestrictingStaticGroups { let groupsFromClaim = groupsFrom(jwtTokenClaims: jwtTokenClaims, groupClaim: groupClaim) let doesNotBelongToGroupsFromClaim = readRestrictingStaticGroupsPerClaim.isEmpty || @@ -122,7 +129,8 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { } private func groupsFrom(jwtTokenClaims: IdentityClaimsDictionary, - groupClaim: String) -> Set { + groupClaim: String) -> Set + { var groupSet = Set() if let groups = (jwtTokenClaims[groupClaim] as? NSArray) as Array? { for group in groups { @@ -147,10 +155,11 @@ 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 { + 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 +167,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 +184,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 +193,7 @@ private extension AuthRule { private extension AuthRules { func filterBy(authType: AWSAuthorizationType?) -> AuthRules { - guard let authType = authType else { + guard let authType else { return self } @@ -200,7 +209,8 @@ private extension AuthRules { } func filterBy(ownerFieldType: ModelFieldType, - modelSchema: ModelSchema) -> AuthRules { + 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..a9633c83eb 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift @@ -22,7 +22,8 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { public init(version: Int? = nil, lastSync: Int64? = nil, graphQLType: GraphQLOperationType, - primaryKeysOnly: Bool = true) { + primaryKeysOnly: Bool = true) + { self.version = version self.lastSync = lastSync self.graphQLType = graphQLType @@ -30,29 +31,32 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + modelType: Model.Type) -> SingleDirectiveGraphQLDocument + { decorate(document, modelSchema: modelType.schema) } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> 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 { + case var .object(value) = input.value + { value["_version"] = version input.value = .object(value) 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)) } @@ -71,7 +75,8 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { /// Append the correct conflict resolution fields for `model` and `pagination` selection sets. private func addConflictResolution(selectionSet: SelectionSet, primaryKeysOnly: Bool, - includeSyncMetadataFields: SyncMetadataFields = .full) { + includeSyncMetadataFields: SyncMetadataFields = .full) + { var includeSyncMetadataFields = includeSyncMetadataFields switch selectionSet.value.fieldType { case .value, .embedded: @@ -93,12 +98,12 @@ 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 + for child in selectionSet.children { addConflictResolution(selectionSet: child, primaryKeysOnly: primaryKeysOnly, includeSyncMetadataFields: .full) @@ -106,7 +111,7 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { } 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 + 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..61c547c28a 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 @@ -36,22 +36,24 @@ public struct DirectiveNameDecorator: ModelBasedGraphQLDocumentDecorator { } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + modelType: Model.Type) -> SingleDirectiveGraphQLDocument + { decorate(document, modelSchema: modelType.schema) } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> 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..4c607038ed 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift @@ -19,12 +19,14 @@ public struct FilterDecorator: ModelBasedGraphQLDocumentDecorator { } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + modelType: Model.Type) -> SingleDirectiveGraphQLDocument + { decorate(document, modelSchema: modelType.schema) } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> 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..cac3c5531d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/IncludeAssociationDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/IncludeAssociationDecorator.swift @@ -19,12 +19,14 @@ public struct IncludeAssociationDecorator: ModelBasedGraphQLDocumentDecorator { } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + modelType: Model.Type) -> SingleDirectiveGraphQLDocument + { return decorate(document, modelSchema: modelType.schema) } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument + { if includedAssociations.isEmpty { return document } @@ -32,7 +34,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 +84,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..147fafabcf 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public protocol ModelBasedGraphQLDocumentDecorator { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift index 7a7ef66cfb..ab2fcf67e3 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 @@ -22,20 +22,22 @@ public struct ModelDecorator: ModelBasedGraphQLDocumentDecorator { } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + modelType: Model.Type) -> SingleDirectiveGraphQLDocument + { decorate(document, modelSchema: modelType.schema) } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> 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..c54e48ce60 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 { @@ -18,7 +18,8 @@ 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 { + modelSchema: schema) + else { return nil } if firstField { @@ -32,7 +33,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 +41,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 +57,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!") }) @@ -65,12 +66,14 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + modelType: Model.Type) -> SingleDirectiveGraphQLDocument + { decorate(document, modelSchema: modelType.schema) } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument + { var inputs = document.inputs if case .mutation = document.operationType { @@ -94,7 +97,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..8b7d8354bb 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 { @@ -20,21 +20,23 @@ public struct PaginationDecorator: ModelBasedGraphQLDocumentDecorator { } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + modelType: Model.Type) -> SingleDirectiveGraphQLDocument + { decorate(document, modelSchema: modelType.schema) } public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> 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)) } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift index ca03962ded..e64ba2752b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift @@ -5,8 +5,8 @@ // 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 { @@ -14,7 +14,8 @@ public struct GraphQLMutation: SingleDirectiveGraphQLDocument { public init(operationType: GraphQLOperationType, name: String, inputs: [GraphQLParameterName: GraphQLDocumentInput], - selectionSet: SelectionSet?) { + 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..4818cc2efa 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift @@ -5,8 +5,8 @@ // 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 { @@ -14,7 +14,8 @@ public struct GraphQLQuery: SingleDirectiveGraphQLDocument { public init(operationType: GraphQLOperationType, name: String, inputs: [GraphQLParameterName: GraphQLDocumentInput], - selectionSet: SelectionSet?) { + 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..5e8a451098 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLSubscription.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLSubscription.swift @@ -14,7 +14,8 @@ public struct GraphQLSubscription: SingleDirectiveGraphQLDocument { public init(operationType: GraphQLOperationType, name: String, inputs: [GraphQLParameterName: GraphQLDocumentInput], - selectionSet: SelectionSet?) { + 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..10f1926c00 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift @@ -39,14 +39,15 @@ public protocol SingleDirectiveGraphQLDocument { } // 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, + func copy(operationType: GraphQLOperationType? = nil, name: String? = nil, inputs: [GraphQLParameterName: GraphQLDocumentInput]? = nil, - selectionSet: SelectionSet? = nil) -> Self { + selectionSet: SelectionSet? = nil) -> Self + { return Self.init(operationType: operationType ?? self.operationType, name: name ?? self.name, @@ -56,13 +57,13 @@ extension SingleDirectiveGraphQLDocument { /// 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 +79,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 +107,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..e69fc0f0a6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift @@ -60,7 +60,8 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { public static func query(modelName: String, byId id: String, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + authType: AWSAuthorizationType? = nil) -> GraphQLRequest + { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: modelName, operationType: .query, primaryKeysOnly: false) @@ -82,27 +83,31 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { public static func createMutation(of model: Model, version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + 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 { + 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 { + 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 { + authType: AWSAuthorizationType? = nil) -> GraphQLRequest + { subscription(to: modelType.schema, subscriptionType: subscriptionType, claims: claims, authType: authType) } @@ -111,7 +116,8 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { limit: Int? = nil, nextToken: String? = nil, lastSync: Int64? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + authType: AWSAuthorizationType? = nil) -> GraphQLRequest + { syncQuery(modelSchema: modelType.schema, where: predicate, limit: limit, @@ -123,7 +129,8 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { public static func createMutation(of model: Model, modelSchema: ModelSchema, version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + authType: AWSAuthorizationType? = nil) -> GraphQLRequest + { createOrUpdateMutation(of: model, modelSchema: modelSchema, type: .create, version: version, authType: authType) } @@ -131,7 +138,8 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { modelSchema: ModelSchema, where filter: GraphQLFilter? = nil, version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + authType: AWSAuthorizationType? = nil) -> GraphQLRequest + { createOrUpdateMutation(of: model, modelSchema: modelSchema, where: filter, @@ -144,14 +152,15 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { modelSchema: ModelSchema, where filter: GraphQLFilter? = nil, version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + 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 { + if let filter { documentBuilder.add(decorator: FilterDecorator(filter: filter)) } documentBuilder.add(decorator: ConflictResolutionDecorator(version: version, graphQLType: .mutation, primaryKeysOnly: false)) @@ -170,7 +179,8 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { public static func subscription(to modelSchema: ModelSchema, subscriptionType: GraphQLSubscriptionType, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + authType: AWSAuthorizationType? = nil) -> GraphQLRequest + { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, operationType: .subscription, @@ -192,7 +202,8 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { public static func subscription(to modelSchema: ModelSchema, subscriptionType: GraphQLSubscriptionType, claims: IdentityClaimsDictionary, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + authType: AWSAuthorizationType? = nil) -> GraphQLRequest + { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, operationType: .subscription, @@ -219,7 +230,8 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { limit: Int? = nil, nextToken: String? = nil, lastSync: Int64? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + authType: AWSAuthorizationType? = nil) -> GraphQLRequest + { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, operationType: .query, primaryKeysOnly: true) @@ -249,13 +261,14 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { where filter: GraphQLFilter? = nil, type: GraphQLMutationType, version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + 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)) @@ -278,13 +291,14 @@ 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 { return predicate } else if let predicate = predicate as? QueryPredicateConstant, - predicate == .all { + predicate == .all + { return predicate } return QueryPredicateGroup(type: .and, predicates: [predicate]) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift index 7338fab830..3fb796e545 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift @@ -90,7 +90,7 @@ 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, + static func create(_ model: M, includes: IncludedAssociations, authMode: AWSAuthorizationType?) -> GraphQLRequest @@ -146,7 +146,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,7 +154,8 @@ 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), @@ -165,7 +166,8 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { public static func update(_ model: M, where predicate: QueryPredicate? = nil, includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { + authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + { return update( model, modelSchema: modelSchema(for: model), @@ -177,20 +179,22 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { public static func delete(_ model: M, where predicate: QueryPredicate? = nil, includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { + authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + { return delete( model, modelSchema: modelSchema(for: model), - where: predicate, + where: predicate, includes: includes, authMode: authMode) } - public static func create(_ model: M, + public static func create(_ model: M, modelSchema: ModelSchema, includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - return mutation(of: model, + authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + { + return mutation(of: model, modelSchema: modelSchema, includes: includes, type: .create, @@ -201,8 +205,9 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - return mutation(of: model, + authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + { + return mutation(of: model, modelSchema: modelSchema, where: predicate, includes: includes, @@ -214,8 +219,9 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - return mutation(of: model, + authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + { + return mutation(of: model, modelSchema: modelSchema, where: predicate, includes: includes, @@ -227,11 +233,12 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { where predicate: QueryPredicate? = nil, includes: IncludedAssociations = { _ in [] }, type: GraphQLMutationType, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - mutation(of: model, + authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + { + mutation(of: model, modelSchema: model.schema, where: predicate, - includes: includes, + includes: includes, type: type, authMode: authMode) } @@ -241,7 +248,8 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { where predicate: QueryPredicate? = nil, includes: IncludedAssociations = { _ in [] }, type: GraphQLMutationType, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { + authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: type)) @@ -257,12 +265,12 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { case .delete: documentBuilder.add(decorator: ModelIdDecorator(model: model, schema: modelSchema)) - if let predicate = predicate { + 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))) } } @@ -278,7 +286,8 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { public static func get(_ modelType: M.Type, byId id: String, includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { + authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) @@ -294,7 +303,7 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { return GraphQLRequest(document: document.stringValue, variables: document.variables, responseType: M?.self, - decodePath: document.name, + decodePath: document.name, authMode: authMode) } @@ -310,7 +319,8 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { byIdentifier id: ModelIdentifier, includes: IncludedAssociations = { _ in [] }, authMode: AWSAuthorizationType? = nil) -> GraphQLRequest - where M: ModelIdentifiable { + where M: ModelIdentifiable + { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) @@ -325,7 +335,7 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { return GraphQLRequest(document: document.stringValue, variables: document.variables, responseType: M?.self, - decodePath: document.name, + decodePath: document.name, authMode: authMode) } @@ -333,7 +343,8 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { where predicate: QueryPredicate? = nil, includes: IncludedAssociations = { _ in [] }, limit: Int? = nil, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest> { + authMode: AWSAuthorizationType? = nil) -> GraphQLRequest> + { let primaryKeysOnly = (M.rootPath != nil) ? true : false var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, operationType: .query) @@ -344,7 +355,7 @@ 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))) } @@ -361,7 +372,8 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { public static func subscription(of modelType: M.Type, type: GraphQLSubscriptionType, includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { + authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, operationType: .subscription) documentBuilder.add(decorator: DirectiveNameDecorator(type: type)) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift index 72d6c1bcde..5629ac0589 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift @@ -7,23 +7,22 @@ import Amplify -extension AuthRuleProvider { +public extension AuthRuleProvider { /// Returns corresponding `AWSAuthorizationType` for each `AuthRuleProvider` /// - Returns: AWS authorization type - public func toAWSAuthorizationType() -> AWSAuthorizationType { - var authType: AWSAuthorizationType - switch self { + func toAWSAuthorizationType() -> AWSAuthorizationType { + var authType: AWSAuthorizationType = switch self { case .apiKey: - authType = .apiKey + .apiKey case .oidc: - authType = .openIDConnect + .openIDConnect case .iam: - authType = .awsIAM + .awsIAM case .userPools: - authType = .amazonCognitoUserPools + .amazonCognitoUserPools case .function: - authType = .function + .function } return authType } @@ -31,7 +30,7 @@ extension AuthRuleProvider { extension AuthRule { func getOwnerFieldOrDefault() -> String { - guard let ownerField = ownerField else { + guard let ownerField else { return "owner" } return ownerField @@ -53,7 +52,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 +62,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 +94,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..4a48b38225 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?] @@ -21,7 +21,8 @@ extension Model { modelSchema.sortedFields.compactMap { field in guard !field.isReadOnly, let fieldValue = getFieldValue(for: field.name, - modelSchema: modelSchema) else { + modelSchema: modelSchema) + else { return nil } return (field, fieldValue) @@ -114,7 +115,8 @@ extension Model { /// 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? { + modelSchema: ModelSchema) -> String? + { guard let modelField = modelSchema.field(withName: modelFieldName) else { return nil @@ -127,7 +129,7 @@ extension Model { } // swiftlint:disable:next syntactic_sugar - guard case .some(Optional.some(let value)) = fieldValue else { + guard case .some(Any?.some(let value)) = fieldValue else { return nil } @@ -160,7 +162,8 @@ extension Model { private func associatedModelIdentifierFields(fromModelValue value: Any, field: ModelField, associatedModelName: String, - mutationType: GraphQLMutationType) -> [(String, Persistable?)] { + mutationType: GraphQLMutationType) -> [(String, Persistable?)] + { guard let associateModelSchema = ModelRegistry.modelSchema(from: associatedModelName) else { preconditionFailure("Associated model \(associatedModelName) not found.") } @@ -194,18 +197,19 @@ extension Model { if let modelValue = value as? Model { return modelValue.identifier(schema: modelSchema).values } else if let optionalModel = value as? Model?, - let modelValue = optionalModel { + let modelValue = optionalModel + { return modelValue.identifier(schema: modelSchema).values } 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 } } @@ -230,7 +234,8 @@ extension Model { if case let .belongsTo(_, targetNames) = modelField.association, !targetNames.isEmpty { return targetNames } else if case let .hasOne(_, _, targetNames) = modelField.association, - !targetNames.isEmpty { + !targetNames.isEmpty + { return targetNames } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift index 86f1d9445a..2cf10d8881 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift @@ -13,26 +13,25 @@ extension ModelSchema { /// The GraphQL directive name translated from a GraphQL query operation and model schema data func graphQLName(queryType: GraphQLQueryType) -> String { - let graphQLName: String - switch queryType { + let graphQLName: String = switch queryType { case .list: - if let listPluralName = listPluralName { - graphQLName = queryType.rawValue + listPluralName - } else if let pluralName = pluralName { - graphQLName = queryType.rawValue + pluralName + if let listPluralName { + queryType.rawValue + listPluralName + } else if let pluralName { + queryType.rawValue + pluralName } else { - graphQLName = (queryType.rawValue + name).pluralize() + (queryType.rawValue + name).pluralize() } case .sync: - if let syncPluralName = syncPluralName { - graphQLName = queryType.rawValue + syncPluralName - } else if let pluralName = pluralName { - graphQLName = queryType.rawValue + pluralName + if let syncPluralName { + queryType.rawValue + syncPluralName + } else if let pluralName { + queryType.rawValue + pluralName } else { - graphQLName = (queryType.rawValue + name).pluralize() + (queryType.rawValue + name).pluralize() } case .get: - graphQLName = queryType.rawValue + name + queryType.rawValue + name } return graphQLName diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift index f2e3a6f816..3c1a513c37 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] @@ -22,7 +22,8 @@ public struct GraphQLFilterConverter { /// by host applications. The behavior of this may change without warning. public static func toJSON(_ queryPredicate: QueryPredicate, modelSchema: ModelSchema, - options: JSONSerialization.WritingOptions = []) throws -> String { + options: JSONSerialization.WritingOptions = []) throws -> String + { let graphQLFilterData = try JSONSerialization.data(withJSONObject: queryPredicate.graphQLFilter(for: modelSchema), options: options) @@ -42,7 +43,8 @@ public struct GraphQLFilterConverter { """) /// Serialize the translated GraphQL query variable object to JSON string. public static func toJSON(_ queryPredicate: QueryPredicate, - options: JSONSerialization.WritingOptions = []) throws -> String { + options: JSONSerialization.WritingOptions = []) throws -> String + { let graphQLFilterData = try JSONSerialization.data(withJSONObject: queryPredicate.graphQLFilter, options: options) @@ -68,11 +70,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 +90,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 +115,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 +152,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 @@ -194,7 +196,7 @@ extension QueryOperator { switch self { case .notEqual(let value), .equals(let value): - if let value = value { + if let value { return value.graphQLValue() } @@ -217,7 +219,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..3e16ac24c9 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,14 +43,15 @@ 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) { + let schema = ModelRegistry.modelSchema(from: associatedModelName) + { if recursive { var recursive = recursive if field._isBelongsToOrHasOne { @@ -64,10 +65,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 +76,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 +113,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 +126,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 +182,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..cfcdff997d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift @@ -19,7 +19,8 @@ public struct ModelSyncMetadata: Model { public init(id: String, lastSync: Int64? = nil, - syncPredicate: String? = nil) { + syncPredicate: String? = nil) + { self.id = id self.lastSync = lastSync self.syncPredicate = syncPredicate 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 cc1149ac27..fdde0154a1 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,13 +151,13 @@ 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) } let urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: nil) return urlSession.webSocketTask(with: urlRequest) @@ -166,19 +165,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 } @@ -207,32 +206,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? @@ -248,15 +247,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)) } } } @@ -276,18 +275,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 } @@ -309,7 +308,7 @@ extension WebSocketClient { } .store(in: &cancelables) - self.resetRetryCountOnConnected() + resetRetryCountOnConnected() } private func resetRetryCountOnConnected() { @@ -328,7 +327,7 @@ extension WebSocketClient { } private func retryOnCloseCode(_ closeCode: URLSessionWebSocketTask.CloseCode) async { - guard self.autoRetryOnConnectionFailure == true else { + guard autoRetryOnConnectionFailure == true else { return } @@ -365,9 +364,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 a53ec3b950..0db1967f1d 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/Auth/AuthModeStrategyTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift index 8674e962cb..cd50320b9c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift @@ -89,7 +89,7 @@ class AuthModeStrategyTests: XCTestCase { let authMode = AWSMultiAuthModeStrategy() let delegate = UnauthenticatedUserDelegate() authMode.authDelegate = delegate - + var authTypesIterator = await authMode.authTypesFor(schema: ModelWithOwnerAndPublicAuth.schema, operation: .create) XCTAssertEqual(authTypesIterator.count, 1) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelMultipleOwnerAuthRuleTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelMultipleOwnerAuthRuleTests.swift index b6ae079862..5021398303 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: [ @@ -28,7 +29,8 @@ public struct ModelMultipleOwner: Model { public var editors: [String]? public init(id: String = UUID().uuidString, content: String, - editors: [String]? = []) { + editors: [String]? = []) + { self.id = id self.content = content self.editors = editors @@ -71,7 +73,7 @@ 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, @@ -219,7 +221,7 @@ 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", diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift index 778945a24f..03a23511dd 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift @@ -24,7 +24,8 @@ public struct ModelReadUpdateField: Model { public let id: String public var content: String public init(id: String = UUID().uuidString, - content: String) { + content: String) + { self.id = id self.content = content } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift index a1d37b50fd..2d0850864c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift @@ -34,14 +34,16 @@ public struct OIDCGroupPost: Model { public init(id: String = UUID().uuidString, title: String, - owner: String? = nil) { + owner: String? = nil) + { self.id = id self.title = title self.owner = owner } // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + public enum CodingKeys: String, ModelKey + { case id case title case owner diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift index 03ac101b21..e907209b0f 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift @@ -36,7 +36,8 @@ public struct OIDCMultiGroupPost: Model { 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/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerFieldAuthRuleTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerFieldAuthRuleTests.swift index 7e0856eced..8a4396e249 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerFieldAuthRuleTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerFieldAuthRuleTests.swift @@ -328,7 +328,8 @@ public struct ModelWithOwnerField: Model { public var author: String? public init(id: String = UUID().uuidString, content: String, - author: String?) { + author: String?) + { self.id = id self.content = content self.author = author @@ -368,7 +369,8 @@ public struct ModelWithOIDCOwnerField: Model { public var author: String? public init(id: String = UUID().uuidString, content: String, - author: String?) { + author: String?) + { self.id = id self.content = content self.author = author @@ -414,7 +416,8 @@ public struct ModelWithMultipleAuthRules: Model { public var author: String? public init(id: String = UUID().uuidString, content: String, - author: String?) { + author: String?) + { self.id = id self.content = content self.author = author diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLCreateMutationTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLCreateMutationTests.swift index f528dfb1c0..b9564c2410 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLCreateMutationTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLCreateMutationTests.swift @@ -118,7 +118,7 @@ class GraphQLCreateMutationTests: XCTestCase { } XCTAssertEqual(input["commentPostId"] as? String, post.id) } - + /// - Given: a `Model` instance /// - When: /// - the model is of type `Comment` @@ -276,7 +276,7 @@ class GraphQLCreateMutationTests: XCTestCase { } XCTAssertEqual(input["commentPostId"] as? String, post.id) } - + /// - Given: a `Model` instance /// - When: /// - the model is of type `Comment` 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/GraphQLRequest/GraphQLRequestEmbeddableTypeJSONTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeJSONTests.swift index 5b2e3f60eb..31c7ea3c37 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeJSONTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeJSONTests.swift @@ -57,7 +57,8 @@ class GraphQLRequestEmbeddableTypeJSONTests: XCTestCase { todoStickies.name: todoStickies]) ModelRegistry.register(modelType: DynamicModel.self, - modelSchema: todoSchema) { (_, _) -> Model in + modelSchema: todoSchema) + { _, _ -> Model in return DynamicModel(id: "1", map: [:]) } } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeTests.swift index b974ea1c79..f622c0505c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeTests.swift @@ -137,7 +137,8 @@ class GraphQLRequestJSONNonModelTests: XCTestCase { todoStickies.name: todoStickies]) ModelRegistry.register(modelType: DynamicModel.self, - modelSchema: todoSchema) { (_, _) -> Model in + modelSchema: todoSchema) + { _, _ -> Model in return DynamicModel(id: "1", map: [:]) } } 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/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/Query/QueryPredicateEvaluateGeneratedBoolTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedBoolTests.swift index e3e013d248..c274c56910 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 ae7c9c8f34..cdab3eb658 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 226b3d7908..27bbf85439 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 31fe364268..c3b05e5cc4 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 fbc4c6566d..84d82af3a9 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/QueryPredicateEvaluateGeneratedIntTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedIntTests.swift index 1e5c4ec370..8b3b207409 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 1ce8eb039c..bca4f41179 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 0caa2f6566..13e03b330c 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..90a8c4be1e 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 } @@ -338,7 +340,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 } @@ -395,7 +398,8 @@ class QueryPredicateGenerator: XCTestCase { if attemptToResolve(type1, val1.replacingOccurrences(of: "\"", with: ""), type2, - val2.replacingOccurrences(of: "\"", with: ""), oper) { + val2.replacingOccurrences(of: "\"", with: ""), oper) + { print(" XCTAssert(evaluation)") } else { print(" XCTAssertFalse(evaluation)") @@ -407,7 +411,8 @@ class QueryPredicateGenerator: XCTestCase { func attemptToResolve(_ type1: String, _ val1: String, _ type2: String, _ val2: String, - _ operation: String) -> Bool { + _ operation: String) -> Bool + { if val2 == "" { return false } @@ -415,12 +420,14 @@ class QueryPredicateGenerator: XCTestCase { if type1 == "Double" && type2 == "Int" || type1 == "Int" && type2 == "Double" || type1 == "Double" && type2 == "Double" || - type1 == "Int" && type2 == "Int" { + type1 == "Int" && type2 == "Int" + { return attemptToResolveNumeric(type1, val1, type2, val2, operation) } else if type1.contains("Temporal") { return attemptToResolveTemporal(type1, val1, type2, val2, operation) } else if (type1 == "String" && type2 == "String") || - (type1 == "Bool" && type2 == "Bool") { + (type1 == "Bool" && type2 == "Bool") + { return attemptToResolveStringBool(val1, val2, operation) } print("attemptToResolve: FAILED TO DETECT TYPES!") @@ -429,7 +436,8 @@ class QueryPredicateGenerator: XCTestCase { func attemptToResolveStringBool(_ val1: String, _ val2: String, - _ operation: String) -> Bool { + _ operation: String) -> Bool + { let rhs = val1 let lhs = val2 switch operation { @@ -457,9 +465,11 @@ class QueryPredicateGenerator: XCTestCase { func attemptToResolveNumeric(_ type1: String, _ sv1: String, _ type2: String, _ sv2: String, - _ operation: String) -> Bool { + _ operation: String) -> Bool + { guard let val1 = Double(sv1), - let val2 = Double(sv2) else { + let val2 = Double(sv2) + else { print("FAILED attemptToResolveNumeric") return false } @@ -489,7 +499,8 @@ class QueryPredicateGenerator: XCTestCase { func attemptToResolveTemporal(_ type1: String, _ sv1: String, _ type2: String, _ sv2: String, - _ operation: String) -> Bool { + _ operation: String) -> Bool + { // Use built-in Date to determine the assert logic let val1 = temporalToTimeMap[sv1]! let val2 = temporalToTimeMap[sv2]! @@ -517,7 +528,8 @@ class QueryPredicateGenerator: XCTestCase { func attemptToResolveBetweenTemporal(_ st1: String, _ sv1: String, _ st2: String, _ sv2: String, - _ sv3: String) -> Bool { + _ sv3: String) -> Bool + { if sv3 == "" { return false } @@ -530,14 +542,16 @@ class QueryPredicateGenerator: XCTestCase { func attemptToResolveBetweenDouble(_ sv1: String, _ sv2: String, - _ sv3: String) -> Bool { + _ 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 } @@ -547,7 +561,8 @@ class QueryPredicateGenerator: XCTestCase { func attemptToResolveBetweenString(_ sv1: String, _ sv2: String, - _ sv3: String) -> Bool { + _ 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 f3e53669c1..9f02fe9498 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,6 +207,6 @@ fileprivate class MockNetworkMonitor: WebSocketNetworkMonitorProtocol { func updateState(_ nextState: AmplifyNetworkMonitor.State) async { subject.send(nextState) } - + } diff --git a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift index 7f11328ad1..33d11a0db5 100644 --- a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift +++ b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import ClientRuntime -import AWSClientRuntime import Amplify +import AWSClientRuntime +import ClientRuntime import InternalAmplifyCredentials public class MockAWSAuthService: AWSAuthCredentialsProviderBehavior { diff --git a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift index abeb670efb..b974cd6ed6 100644 --- a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift +++ b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift @@ -5,18 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSClientRuntime import AWSPluginsCore import ClientRuntime -import AWSClientRuntime -import InternalAmplifyCredentials import Foundation +import InternalAmplifyCredentials class MockAWSSignatureV4Signer: AWSSignatureV4Signer { func sigV4SignedRequest(requestBuilder: SdkHttpRequestBuilder, credentialsProvider: CredentialsProviding, signingName: String, signingRegion: String, - date: Date) throws -> SdkHttpRequest? { + date: Date) throws -> SdkHttpRequest? + { let originalRequest = requestBuilder.build() return originalRequest } diff --git a/AmplifyPlugins/Core/AmplifyCredentials/AWSAuthCredentialsProviderBehavior.swift b/AmplifyPlugins/Core/AmplifyCredentials/AWSAuthCredentialsProviderBehavior.swift index 6d6cfe9277..c0fbedb152 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 AWSClientRuntime import AWSPluginsCore +import Foundation public protocol AWSAuthCredentialsProviderBehavior: AWSAuthServiceBehavior { func getCredentialsProvider() -> CredentialsProviding diff --git a/AmplifyPlugins/Core/AmplifyCredentials/AWSAuthService+CredentialsProvider.swift b/AmplifyPlugins/Core/AmplifyCredentials/AWSAuthService+CredentialsProvider.swift index ec8babe3d5..15180bb115 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 AWSClientRuntime import AWSPluginsCore +import Foundation extension AWSAuthService: AWSAuthCredentialsProviderBehavior { public func getCredentialsProvider() -> AWSClientRuntime.CredentialsProviding { diff --git a/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSServiceConfiguration.swift b/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSServiceConfiguration.swift index 2d3a77f173..2c61c531ae 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 015f2e8395..2f3153b9cd 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSSignatureV4Signer.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSSignatureV4Signer.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import ClientRuntime import AWSClientRuntime import AwsCommonRuntimeKit +import ClientRuntime +import Foundation public protocol AWSSignatureV4Signer { func sigV4SignedRequest(requestBuilder: SdkHttpRequestBuilder, @@ -27,7 +27,8 @@ public class AmplifyAWSSignatureV4Signer: AWSSignatureV4Signer { credentialsProvider: AWSClientRuntime.CredentialsProviding, signingName: Swift.String, signingRegion: Swift.String, - date: ClientRuntime.Date) async throws -> SdkHttpRequest? { + date: ClientRuntime.Date) async throws -> SdkHttpRequest? + { do { let credentials = try await credentialsProvider.getCredentials() @@ -51,7 +52,7 @@ public class AmplifyAWSSignatureV4Signer: AWSSignatureV4Signer { 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/ClientRuntimeFoundationBridge.swift b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/ClientRuntimeFoundationBridge.swift index 18fa1470b2..79b6852823 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/ClientRuntimeFoundationBridge.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/ClientRuntimeFoundationBridge.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import ClientRuntime +import Foundation extension Foundation.URLRequest { init(sdkRequest: ClientRuntime.SdkHttpRequest) async throws { diff --git a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngine.swift b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngine.swift index d8f18fe889..9e4dc70e78 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngine.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngine.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import ClientRuntime import Amplify +import ClientRuntime +import Foundation @_spi(FoundationClientEngine) public struct FoundationClientEngine: HTTPClient { diff --git a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngineError.swift b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngineError.swift index 09e6df49ef..396ec729be 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngineError.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/FoundationClientEngineError.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import ClientRuntime +import Foundation struct FoundationClientEngineError: AmplifyError { let errorDescription: ErrorDescription diff --git a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/PluginClientEngine.swift b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/PluginClientEngine.swift index 6a2e8d7544..18e3b46ed6 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/PluginClientEngine.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/PluginClientEngine.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import ClientRuntime import AWSClientRuntime +import ClientRuntime +import Foundation @_spi(PluginHTTPClientEngine) public func baseClientEngine( diff --git a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/SdkHttpRequest+updatingUserAgent.swift b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/SdkHttpRequest+updatingUserAgent.swift index 690b8f932f..ef751be625 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/SdkHttpRequest+updatingUserAgent.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/SdkHttpRequest+updatingUserAgent.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import ClientRuntime +import Foundation @_spi(PluginHTTPClientEngine) -extension SdkHttpRequest { - public func updatingUserAgent(with value: String) -> SdkHttpRequest { +public extension SdkHttpRequest { + func updatingUserAgent(with value: String) -> SdkHttpRequest { 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 807403f21a..2fcfed593c 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSettingClientEngine.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSettingClientEngine.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import ClientRuntime import AWSClientRuntime +import ClientRuntime +import Foundation @_spi(PluginHTTPClientEngine) public struct UserAgentSettingClientEngine: AWSPluginExtension { @@ -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: AWSClientConfiguration ) -> Self { let baseClientEngine = baseClientEngine(for: configuration) diff --git a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSuffixAppender.swift b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSuffixAppender.swift index bb82ae44f3..135812484e 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSuffixAppender.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/CustomHttpClientEngine/UserAgentSuffixAppender.swift @@ -22,7 +22,7 @@ public class UserAgentSuffixAppender: AWSPluginExtension { @_spi(InternalHttpEngineProxy) extension UserAgentSuffixAppender: HTTPClient { public func send(request: SdkHttpRequest) async throws -> HttpResponse { - guard let target = target else { + guard let target else { throw ClientError.unknownError("HttpClientEngine is not set") } diff --git a/AmplifyPlugins/Core/AmplifyCredentials/IAMCredentialProvider.swift b/AmplifyPlugins/Core/AmplifyCredentials/IAMCredentialProvider.swift index 1265a9130f..1765363263 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/IAMCredentialProvider.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/IAMCredentialProvider.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSClientRuntime import AWSPluginsCore +import Foundation public protocol IAMCredentialsProvider { func getCredentialsProvider() -> CredentialsProviding 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 abca5ad99c..9e4f98bf5f 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 { diff --git a/AmplifyPlugins/Core/AmplifyCredentialsTests/Utils/UserAgentSettingClientEngineTests.swift b/AmplifyPlugins/Core/AmplifyCredentialsTests/Utils/UserAgentSettingClientEngineTests.swift index a6b2d3a800..6e6e0e4128 100644 --- a/AmplifyPlugins/Core/AmplifyCredentialsTests/Utils/UserAgentSettingClientEngineTests.swift +++ b/AmplifyPlugins/Core/AmplifyCredentialsTests/Utils/UserAgentSettingClientEngineTests.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -@_spi(InternalAmplifyPluginExtension) +import ClientRuntime +@_spi(InternalAmplifyPluginExtension) @_spi(PluginHTTPClientEngine) @_spi(InternalHttpEngineProxy) import InternalAmplifyCredentials -import ClientRuntime import XCTest class UserAgentSettingClientEngineTestCase: XCTestCase { diff --git a/AmplifyPlugins/Core/AmplifyCredentialsTests/Utils/UserAgentSuffixAppenderTests.swift b/AmplifyPlugins/Core/AmplifyCredentialsTests/Utils/UserAgentSuffixAppenderTests.swift index dece4394d4..766518762f 100644 --- a/AmplifyPlugins/Core/AmplifyCredentialsTests/Utils/UserAgentSuffixAppenderTests.swift +++ b/AmplifyPlugins/Core/AmplifyCredentialsTests/Utils/UserAgentSuffixAppenderTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -@_spi(InternalAmplifyPluginExtension) @_spi(InternalHttpEngineProxy) import InternalAmplifyCredentials import ClientRuntime +@_spi(InternalAmplifyPluginExtension) @_spi(InternalHttpEngineProxy) import InternalAmplifyCredentials import XCTest class UserAgentSuffixAppenderTests: XCTestCase { From a2e0e66a154863bb3a655c30b621bf0f66a1ac00 Mon Sep 17 00:00:00 2001 From: Tuan Pham Date: Mon, 9 Sep 2024 16:35:02 -0500 Subject: [PATCH 2/5] updated swiftformat rules --- .../AWSAPIPluginDataStoreOptions.swift | 7 +- .../AWSPluginsCore/AWSPluginOptions.swift | 7 +- .../Auth/AWSAuthModeStrategy.swift | 31 +- .../AWSPluginsCore/Auth/AWSAuthService.swift | 24 +- .../AWSAuthorizationConfiguration.swift | 21 +- .../Model/AnyModel/AnyModel.swift | 6 +- .../Model/Decorator/AuthRuleDecorator.swift | 79 ++-- .../ConflictResolutionDecorator.swift | 53 ++- .../Decorator/DirectiveNameDecorator.swift | 14 +- .../Model/Decorator/FilterDecorator.swift | 14 +- .../IncludeAssociationDecorator.swift | 14 +- .../ModelBasedGraphQLDocumentDecorator.swift | 12 +- .../Model/Decorator/ModelDecorator.swift | 14 +- .../Model/Decorator/ModelIdDecorator.swift | 20 +- .../Model/Decorator/PaginationDecorator.swift | 20 +- .../GraphQLDocument/GraphQLMutation.swift | 11 +- .../Model/GraphQLDocument/GraphQLQuery.swift | 11 +- .../GraphQLDocument/GraphQLSubscription.swift | 11 +- .../SingleDirectiveGraphQLDocument.swift | 33 +- .../GraphQLRequest+AnyModelWithSync.swift | 396 +++++++++-------- .../GraphQLRequest/GraphQLRequest+Model.swift | 404 ++++++++++-------- .../Model/Support/Model+GraphQL.swift | 40 +- .../Support/QueryPredicate+GraphQL.swift | 28 +- .../Model/Support/SelectionSet.swift | 3 +- .../Sync/ModelSync/ModelSyncMetadata.swift | 9 +- .../Sync/MutationSync/MutationSync.swift | 25 +- .../Auth/AuthModeStrategyTests.swift | 18 +- .../ModelMultipleOwnerAuthRuleTests.swift | 81 ++-- .../ModelReadUpdateAuthRuleTests.swift | 82 ++-- ...lWithOwnerAuthAndGroupWithGroupClaim.swift | 92 ++-- .../ModelWithOwnerAuthAndMultiGroup.swift | 163 ++++--- .../ModelWithOwnerFieldAuthRuleTests.swift | 132 ++++-- .../IncludeAssociationDecoratorTests.swift | 8 +- .../GraphQLCreateMutationTests.swift | 16 +- .../GraphQLDeleteMutationTests.swift | 6 +- .../GraphQLListQueryTests.swift | 18 +- .../GraphQLSubscriptionTests.swift | 16 +- .../GraphQLSyncQueryTests.swift | 8 +- .../GraphQLUpdateMutationTests.swift | 6 +- .../GraphQLRequestAnyModelWithSyncTests.swift | 46 +- ...GraphQLRequestAuthIdentityClaimTests.swift | 48 ++- .../GraphQLRequestAuthRuleTests.swift | 64 ++- ...raphQLRequestEmbeddableTypeJSONTests.swift | 117 +++-- .../GraphQLRequestEmbeddableTypeTests.swift | 209 +++++---- .../GraphQLRequestOwnerAndGroupTests.swift | 218 ++++++---- ...phQLRequestSyncCustomPrimaryKeyTests.swift | 50 ++- ...tomPrimaryKeyWithMultipleFieldsTests.swift | 60 ++- .../Model/Support/ModelGraphQLTests.swift | 64 +-- .../Support/ModelSchemaGraphQLTests.swift | 14 +- .../Support/QueryPredicateGraphQLTests.swift | 16 +- ...yPredicateEvaluateGeneratedEnumTests.swift | 96 +++-- .../QueryPredicateEvaluateGenerator.swift | 148 ++++--- .../MockAWSAuthService.swift | 3 +- .../MockAWSSignatureV4Signer.swift | 13 +- .../AmplifyAWSCredentialsProvider.swift | 6 +- .../AmplifyAWSSignatureV4Signer.swift | 53 ++- .../Auth/AWSAuthServiceTests.swift | 6 +- 57 files changed, 1938 insertions(+), 1246 deletions(-) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift b/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift index 9cac54243a..d496276231 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift @@ -20,9 +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 0b8e60b572..a6a11decb4 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift @@ -37,9 +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 ca4ab63a71..15d338b1dc 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift @@ -110,15 +110,17 @@ public class AWSDefaultAuthModeStrategy: AuthModeStrategy { public weak var authDelegate: AuthModeStrategyDelegate? 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]) } } @@ -201,8 +203,7 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { /// Use provider priority to sort if rules have the same strategy private static let comparator = { (rule1: AuthRule, rule2: AuthRule) -> Bool in if let providerRule1 = rule1.provider, - let providerRule2 = rule2.provider, rule1.allow == rule2.allow - { + let providerRule2 = rule2.provider, rule1.allow == rule2.allow { return priorityOf(authRuleProvider: providerRule1) < priorityOf(authRuleProvider: providerRule2) } return priorityOf(authStrategy: rule1.allow) < priorityOf(authStrategy: rule2.allow) @@ -213,9 +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]) } @@ -224,9 +226,10 @@ 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 diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift index 735e2178d4..338fdfaf7a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift @@ -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/Configuration/AWSAuthorizationConfiguration.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Configuration/AWSAuthorizationConfiguration.swift index 55c09c07cd..57168ab230 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Configuration/AWSAuthorizationConfiguration.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Configuration/AWSAuthorizationConfiguration.swift @@ -20,18 +20,18 @@ public enum AWSAuthorizationConfiguration { // MARK: - AWSAuthorizationConfiguration factory extension AWSAuthorizationConfiguration { private static func awsIAMAuthorizationConfiguration(region: String?) - throws -> AWSAuthorizationConfiguration - { + throws -> AWSAuthorizationConfiguration { guard let region else { - throw PluginError.pluginConfigurationError("Region is not set for IAM", - "Set the region") + throw PluginError.pluginConfigurationError( + "Region is not set for IAM", + "Set the region" + ) } return .awsIAM(AWSIAMConfiguration(region: region)) } private static func apiKeyAuthorizationConfiguration(apiKey: String?) - throws -> AWSAuthorizationConfiguration - { + throws -> AWSAuthorizationConfiguration { guard let apiKey else { throw PluginError.pluginConfigurationError( @@ -55,10 +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/Model/AnyModel/AnyModel.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel.swift index bcfcefa40b..d739bde176 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel.swift @@ -49,8 +49,10 @@ public extension AnyModel { 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 fd63b5752e..384e2564c6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift @@ -37,22 +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) @@ -63,17 +66,20 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { let readRestrictingStaticGroups = authRules.groupClaimsToReadRestrictingStaticGroups() for authRule in authRules { - decorateDocument = decorateAuthStrategy(document: decorateDocument, - authRule: authRule, - readRestrictingStaticGroups: readRestrictingStaticGroups) + 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 { @@ -86,12 +92,15 @@ 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) + let identityClaimValue = resolveIdentityClaimValue( + identityClaim: authRule.identityClaimOrDefault(), + claims: tokenClaims + ) if let identityClaimValue { inputs[ownerField] = GraphQLDocumentInput(type: "String!", value: .scalar(identityClaimValue)) } @@ -112,9 +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 || @@ -128,9 +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 { @@ -154,9 +165,10 @@ 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 { for selectionSet in selectionSetModel.children { @@ -208,9 +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 a9633c83eb..455d8f35c1 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift @@ -19,26 +19,29 @@ 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 @@ -48,8 +51,7 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { if let version, case .mutation = document.operationType, var input = inputs["input"], - case var .object(value) = input.value - { + case var .object(value) = input.value { value["_version"] = version input.value = .object(value) @@ -73,10 +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: @@ -104,17 +107,21 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { // subscriptions and sync query is to receive data, so it can be reduced to allow decoding to the // LazyReference type. for child in selectionSet.children { - addConflictResolution(selectionSet: child, - primaryKeysOnly: primaryKeysOnly, - includeSyncMetadataFields: .full) + 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. for child in selectionSet.children { - addConflictResolution(selectionSet: child, - primaryKeysOnly: primaryKeysOnly, - includeSyncMetadataFields: includeSyncMetadataFields) + 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 61c547c28a..9e2ec3671a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/DirectiveNameDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/DirectiveNameDecorator.swift @@ -35,15 +35,17 @@ 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 { return document.copy(name: modelSchema.graphQLName(queryType: queryType)) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift index 4c607038ed..6d7dea2894 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift @@ -18,15 +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 cac3c5531d..8ee92d10ab 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/IncludeAssociationDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/IncludeAssociationDecorator.swift @@ -18,15 +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 } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift index 147fafabcf..328da76ab0 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift @@ -13,9 +13,13 @@ 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 ab2fcf67e3..ef6b871951 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift @@ -21,15 +21,17 @@ 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) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift index c54e48ce60..88d76167e6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift @@ -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) + guard let value = model.graphQLInputForPrimaryKey( + modelFieldName: fieldName, + modelSchema: schema + ) else { return nil } @@ -65,15 +67,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 { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/PaginationDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/PaginationDecorator.swift index 8b7d8354bb..3de8605169 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/PaginationDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/PaginationDecorator.swift @@ -19,15 +19,17 @@ 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 { @@ -42,8 +44,10 @@ public struct PaginationDecorator: ModelBasedGraphQLDocumentDecorator { 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 e64ba2752b..e681be161c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift @@ -11,11 +11,12 @@ 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 4818cc2efa..1c7b60732f 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift @@ -11,11 +11,12 @@ 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 5e8a451098..a558138dc3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLSubscription.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLSubscription.swift @@ -11,11 +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/SingleDirectiveGraphQLDocument.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift index 10f1926c00..2fad197f59 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift @@ -32,10 +32,12 @@ 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 @@ -43,16 +45,19 @@ 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. - 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` diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift index e69fc0f0a6..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,13 +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)) @@ -74,92 +91,110 @@ 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)) + documentBuilder.add(decorator: ModelIdDecorator( + model: model, + schema: modelSchema + )) if let filter { documentBuilder.add(decorator: FilterDecorator(filter: filter)) } @@ -170,21 +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)) @@ -192,22 +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)) @@ -218,23 +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))) @@ -247,25 +297,30 @@ 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 { @@ -278,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. @@ -297,8 +354,7 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { if predicate as? QueryPredicateGroup != nil { return predicate } else if let predicate = predicate as? QueryPredicateConstant, - predicate == .all - { + predicate == .all { return predicate } return QueryPredicateGroup(type: .and, predicates: [predicate]) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift index 3fb796e545..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 @@ -154,104 +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, 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 { @@ -263,8 +301,10 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { case .create: documentBuilder.add(decorator: ModelDecorator(model: model, mutationType: type)) case .delete: - documentBuilder.add(decorator: ModelIdDecorator(model: model, - schema: modelSchema)) + documentBuilder.add(decorator: ModelIdDecorator( + model: model, + schema: modelSchema + )) if let predicate { documentBuilder.add(decorator: FilterDecorator(filter: predicate.graphQLFilter(for: modelSchema))) } @@ -276,20 +316,25 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { } 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 { @@ -300,29 +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 - where M: ModelIdentifiable - { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .query) + 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 + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) if let modelPath = modelType.rootPath as? ModelPath { @@ -332,22 +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 { @@ -362,20 +419,25 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { 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 { @@ -385,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/Model+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift index 4a48b38225..db484eccfe 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift @@ -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) + let fieldValue = getFieldValue( + for: field.name, + modelSchema: modelSchema + ) else { return nil } @@ -87,10 +89,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) } @@ -114,9 +118,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 @@ -159,11 +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.") } @@ -197,8 +203,7 @@ extension Model { if let modelValue = value as? Model { return modelValue.identifier(schema: modelSchema).values } else if let optionalModel = value as? Model?, - let modelValue = optionalModel - { + let modelValue = optionalModel { return modelValue.identifier(schema: modelSchema).values } else if let lazyModel = value as? (any _LazyReferenceValue) { switch lazyModel._state { @@ -234,8 +239,7 @@ extension Model { if case let .belongsTo(_, targetNames) = modelField.association, !targetNames.isEmpty { return targetNames } else if case let .hasOne(_, _, targetNames) = modelField.association, - !targetNames.isEmpty - { + !targetNames.isEmpty { return targetNames } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift index 3c1a513c37..dcb600567d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift @@ -20,13 +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(""" @@ -42,11 +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(""" diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift index 3e16ac24c9..8a0d8d2bf3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift @@ -50,8 +50,7 @@ extension SelectionSet { addChild(settingParentOf: child) } else if field._isBelongsToOrHasOne, let associatedModelName = field.associatedModelName, - let schema = ModelRegistry.modelSchema(from: associatedModelName) - { + let schema = ModelRegistry.modelSchema(from: associatedModelName) { if recursive { var recursive = recursive if field._isBelongsToOrHasOne { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift index cfcdff997d..fe17daa10c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift @@ -17,10 +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/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift index cd50320b9c..32a41d8d7b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift @@ -90,8 +90,10 @@ class AuthModeStrategyTests: XCTestCase { 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 5021398303..a9a50bce1a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelMultipleOwnerAuthRuleTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelMultipleOwnerAuthRuleTests.swift @@ -27,10 +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 @@ -76,8 +77,10 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // 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() @@ -99,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() @@ -122,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() @@ -145,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() @@ -168,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)) @@ -193,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)) @@ -224,10 +237,14 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // 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() @@ -253,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() @@ -282,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 03a23511dd..d31f860e4c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift @@ -23,9 +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 } @@ -42,7 +43,8 @@ public struct ModelReadUpdateField: Model { ] model.fields( .id(), - .field(modelReadUpdateField.content, is: .required, ofType: .string)) + .field(modelReadUpdateField.content, is: .required, ofType: .string) + ) } } @@ -58,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() @@ -80,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() @@ -102,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() @@ -124,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() @@ -146,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)) @@ -170,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)) @@ -200,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() @@ -224,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() @@ -247,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 2d0850864c..a321edca6e 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift @@ -32,18 +32,18 @@ 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 } // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey - { + public enum CodingKeys: String, ModelKey { case id case title case owner @@ -54,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) ) } } @@ -85,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() @@ -112,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() @@ -136,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() @@ -160,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 e907209b0f..e302631d99 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift @@ -34,10 +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 @@ -55,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" @@ -88,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() @@ -111,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() @@ -137,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() @@ -162,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() @@ -187,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() @@ -216,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() @@ -246,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 8a4396e249..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,10 +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 @@ -349,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) + ) } } @@ -367,10 +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 @@ -390,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) + ) } } @@ -414,10 +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 @@ -438,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 b9564c2410..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)) @@ -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/GraphQLListQueryTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLListQueryTests.swift index 7d26e52108..2064a7c7e8 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 = """ 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 31c7ea3c37..f23e5bd2fc 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeJSONTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeJSONTests.swift @@ -16,49 +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: [:]) } } @@ -68,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 f622c0505c..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,69 +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: [:]) } } @@ -148,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/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/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/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/QueryPredicateEvaluateGenerator.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGenerator.swift index 90a8c4be1e..c8a74d2a40 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGenerator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGenerator.swift @@ -289,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 != "" { @@ -374,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))") @@ -396,10 +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)") @@ -409,10 +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 } @@ -420,24 +446,23 @@ class QueryPredicateGenerator: XCTestCase { if type1 == "Double" && type2 == "Int" || type1 == "Int" && type2 == "Double" || type1 == "Double" && type2 == "Double" || - type1 == "Int" && type2 == "Int" - { + type1 == "Int" && type2 == "Int" { return attemptToResolveNumeric(type1, val1, type2, val2, operation) } else if type1.contains("Temporal") { return attemptToResolveTemporal(type1, val1, type2, val2, operation) } else if (type1 == "String" && type2 == "String") || - (type1 == "Bool" && type2 == "Bool") - { + (type1 == "Bool" && type2 == "Bool") { return attemptToResolveStringBool(val1, val2, operation) } print("attemptToResolve: FAILED TO DETECT TYPES!") 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 { @@ -463,10 +488,13 @@ 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 { @@ -497,10 +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]! @@ -526,10 +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 } @@ -540,10 +574,11 @@ 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 } @@ -559,10 +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/AWSPluginsTestCommon/MockAWSAuthService.swift b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift index 33d11a0db5..a72f1de3fb 100644 --- a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift +++ b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift @@ -66,6 +66,7 @@ struct MyCustomCredentialsProvider: CredentialsProviding { AWSCredentials( accessKey: "AKIDEXAMPLE", secret: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", - expirationTimeout: Date().addingTimeInterval(30)) + expirationTimeout: Date().addingTimeInterval(30) + ) } } diff --git a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift index b974cd6ed6..07ba6bcb50 100644 --- a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift +++ b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift @@ -12,12 +12,13 @@ import Foundation import InternalAmplifyCredentials class MockAWSSignatureV4Signer: AWSSignatureV4Signer { - func sigV4SignedRequest(requestBuilder: SdkHttpRequestBuilder, - credentialsProvider: CredentialsProviding, - signingName: String, - signingRegion: String, - date: Date) throws -> SdkHttpRequest? - { + func sigV4SignedRequest( + requestBuilder: SdkHttpRequestBuilder, + credentialsProvider: CredentialsProviding, + signingName: String, + signingRegion: String, + date: Date + ) throws -> SdkHttpRequest? { let originalRequest = requestBuilder.build() return originalRequest } diff --git a/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSCredentialsProvider.swift b/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSCredentialsProvider.swift index 63d1197a6d..05bb682680 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSCredentialsProvider.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSCredentialsProvider.swift @@ -33,12 +33,14 @@ extension AWSPluginsCore.AWSCredentials { accessKey: tempCredentials.accessKeyId, secret: tempCredentials.secretAccessKey, expirationTimeout: tempCredentials.expiration, - sessionToken: tempCredentials.sessionToken) + sessionToken: tempCredentials.sessionToken + ) } else { return AWSClientRuntime.AWSCredentials( accessKey: accessKeyId, secret: secretAccessKey, - expirationTimeout: Date()) + expirationTimeout: Date() + ) } } diff --git a/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSSignatureV4Signer.swift b/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSSignatureV4Signer.swift index 2f3153b9cd..3c842ac3fd 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSSignatureV4Signer.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSSignatureV4Signer.swift @@ -12,40 +12,47 @@ import ClientRuntime import Foundation public protocol AWSSignatureV4Signer { - func sigV4SignedRequest(requestBuilder: SdkHttpRequestBuilder, - credentialsProvider: AWSClientRuntime.CredentialsProviding, - signingName: Swift.String, - signingRegion: Swift.String, - date: ClientRuntime.Date) async throws -> SdkHttpRequest? + func sigV4SignedRequest( + requestBuilder: SdkHttpRequestBuilder, + credentialsProvider: AWSClientRuntime.CredentialsProviding, + signingName: Swift.String, + signingRegion: Swift.String, + date: ClientRuntime.Date + ) async throws -> SdkHttpRequest? } public class AmplifyAWSSignatureV4Signer: AWSSignatureV4Signer { public init() { } - public func sigV4SignedRequest(requestBuilder: SdkHttpRequestBuilder, - credentialsProvider: AWSClientRuntime.CredentialsProviding, - signingName: Swift.String, - signingRegion: Swift.String, - date: ClientRuntime.Date) async throws -> SdkHttpRequest? - { + public func sigV4SignedRequest( + requestBuilder: SdkHttpRequestBuilder, + credentialsProvider: AWSClientRuntime.CredentialsProviding, + signingName: Swift.String, + signingRegion: Swift.String, + date: ClientRuntime.Date + ) async throws -> SdkHttpRequest? { do { let credentials = try await credentialsProvider.getCredentials() - 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: signingRegion, - signatureType: .requestHeaders, - signingAlgorithm: .sigv4) + let signingConfig = AWSSigningConfig( + credentials: credentials, + signedBodyHeader: signedBodyHeader, + signedBodyValue: signedBodyValue, + flags: flags, + date: date, + service: signingName, + region: signingRegion, + signatureType: .requestHeaders, + signingAlgorithm: .sigv4 + ) let httpRequest = await AWSSigV4Signer.sigV4SignedRequest( requestBuilder: requestBuilder, diff --git a/AmplifyPlugins/Core/AmplifyCredentialsTests/Auth/AWSAuthServiceTests.swift b/AmplifyPlugins/Core/AmplifyCredentialsTests/Auth/AWSAuthServiceTests.swift index 9e4f98bf5f..0f2ba244cc 100644 --- a/AmplifyPlugins/Core/AmplifyCredentialsTests/Auth/AWSAuthServiceTests.swift +++ b/AmplifyPlugins/Core/AmplifyCredentialsTests/Auth/AWSAuthServiceTests.swift @@ -166,7 +166,8 @@ class AWSAuthServiceTests: XCTestCase { sessionToken: "somesession", accessKeyId: "accessKeyId", secretAccessKey: "secretAccessKey", - expiration: Date().addingTimeInterval(100)) + expiration: Date().addingTimeInterval(100) + ) let sdkCredentials = 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 = credentials.toAWSSDKCredentials() XCTAssertNotNil(sdkCredentials) } From 70dba9512e795cb7d38b8a3d7566bf0c8f5fe673 Mon Sep 17 00:00:00 2001 From: Tuan Pham Date: Tue, 10 Sep 2024 10:29:47 -0500 Subject: [PATCH 3/5] fix build error --- .../Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift index db484eccfe..f1a4d36532 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift @@ -133,11 +133,11 @@ extension Model { return nil } - // swiftlint:disable:next syntactic_sugar - guard case .some(Any?.some(let value)) = fieldValue else { + // swiftformat:disable all + guard case .some(Optional.some(let value)) = fieldValue else { return nil } - + // swiftformat:enable all switch modelField.type { case .date, .dateTime, .time: if let date = value as? TemporalSpec { From 4416c7445e8929552597d7d04759c7841da4bd01 Mon Sep 17 00:00:00 2001 From: Tuan Pham Date: Tue, 10 Sep 2024 10:51:24 -0500 Subject: [PATCH 4/5] fix build error --- .../Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift index f1a4d36532..2a371a5f66 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift @@ -133,11 +133,12 @@ extension Model { return nil } - // swiftformat:disable all + // swiftlint:disable:next syntactic_sugar + // swiftformat:disable typeSugar guard case .some(Optional.some(let value)) = fieldValue else { return nil } - // swiftformat:enable all + // swiftformat:enable typeSugar switch modelField.type { case .date, .dateTime, .time: if let date = value as? TemporalSpec { From c418da376fa182cb11d2e9022f7e31dedafef097 Mon Sep 17 00:00:00 2001 From: Tuan Pham Date: Fri, 13 Sep 2024 18:57:07 -0500 Subject: [PATCH 5/5] update rules --- .../Model/Decorator/ModelIdDecorator.swift | 3 +-- .../Model/Support/AuthRule+Extension.swift | 13 +++++++------ .../Model/Support/Model+GraphQL.swift | 3 +-- .../Model/Support/ModelSchema+GraphQL.swift | 17 +++++++++-------- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift index 88d76167e6..df7c5595a7 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift @@ -20,8 +20,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { guard let value = model.graphQLInputForPrimaryKey( modelFieldName: fieldName, modelSchema: schema - ) - else { + ) else { return nil } if firstField { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift index 5629ac0589..9c181f2d5c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift @@ -12,17 +12,18 @@ public extension AuthRuleProvider { /// Returns corresponding `AWSAuthorizationType` for each `AuthRuleProvider` /// - Returns: AWS authorization type func toAWSAuthorizationType() -> AWSAuthorizationType { - var authType: AWSAuthorizationType = switch self { + var authType: AWSAuthorizationType + switch self { case .apiKey: - .apiKey + authType = .apiKey case .oidc: - .openIDConnect + authType = .openIDConnect case .iam: - .awsIAM + authType = .awsIAM case .userPools: - .amazonCognitoUserPools + authType = .amazonCognitoUserPools case .function: - .function + authType = .function } return authType } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift index 2a371a5f66..4908fbca39 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift @@ -23,8 +23,7 @@ extension Model { let fieldValue = getFieldValue( for: field.name, modelSchema: modelSchema - ) - else { + ) else { return nil } return (field, fieldValue) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift index 2cf10d8881..a88ed8907d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift @@ -13,25 +13,26 @@ extension ModelSchema { /// The GraphQL directive name translated from a GraphQL query operation and model schema data func graphQLName(queryType: GraphQLQueryType) -> String { - let graphQLName: String = switch queryType { + let graphQLName: String + switch queryType { case .list: if let listPluralName { - queryType.rawValue + listPluralName + graphQLName = queryType.rawValue + listPluralName } else if let pluralName { - queryType.rawValue + pluralName + graphQLName = queryType.rawValue + pluralName } else { - (queryType.rawValue + name).pluralize() + graphQLName = (queryType.rawValue + name).pluralize() } case .sync: if let syncPluralName { - queryType.rawValue + syncPluralName + graphQLName = queryType.rawValue + syncPluralName } else if let pluralName { - queryType.rawValue + pluralName + graphQLName = queryType.rawValue + pluralName } else { - (queryType.rawValue + name).pluralize() + graphQLName = (queryType.rawValue + name).pluralize() } case .get: - queryType.rawValue + name + graphQLName = queryType.rawValue + name } return graphQLName