diff --git a/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift b/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift index f3035b76f0..d496276231 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/AWSAPIPluginDataStoreOptions.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Plugin specific options type /// @@ -20,8 +20,10 @@ public struct AWSAPIPluginDataStoreOptions { /// name of the model public let modelName: String - public init(authType: AWSAuthorizationType?, - modelName: String) { + public init( + authType: AWSAuthorizationType?, + modelName: String + ) { self.authType = authType self.modelName = modelName } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift b/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift index b6f83ec2b3..a6a11decb4 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Plugin specific options type /// @@ -37,8 +37,10 @@ public struct AWSPluginOptions { /// name of the model public let modelName: String? - public init(authType: AWSAuthorizationType?, - modelName: String) { + public init( + authType: AWSAuthorizationType?, + modelName: String + ) { self.authType = authType self.modelName = modelName } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift index d53920f158..15d338b1dc 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import Combine import Amplify +import Combine +import Foundation /// Represents different auth strategies supported by a client /// interfacing with an AppSync backend @@ -56,7 +56,7 @@ public protocol AuthorizationTypeIterator { /// Total number of values var count: Int { get } - + /// Whether iterator has next available `AuthorizationType` to return or not var hasNext: Bool { get } @@ -85,7 +85,7 @@ public struct AWSAuthorizationTypeIterator: AuthorizationTypeIterator, Sequence, public var count: Int { _count } - + public var hasNext: Bool { _position < _count } @@ -95,7 +95,7 @@ public struct AWSAuthorizationTypeIterator: AuthorizationTypeIterator, Sequence, _position += 1 return value } - + return nil } } @@ -108,15 +108,19 @@ public struct AWSAuthorizationTypeIterator: AuthorizationTypeIterator, Sequence, /// registered as interceptor for the API public class AWSDefaultAuthModeStrategy: AuthModeStrategy { public weak var authDelegate: AuthModeStrategyDelegate? - required public init() {} + public required init() {} - public func authTypesFor(schema: ModelSchema, - operation: ModelOperation) -> AWSAuthorizationTypeIterator { + public func authTypesFor( + schema: ModelSchema, + operation: ModelOperation + ) -> AWSAuthorizationTypeIterator { return AWSAuthorizationTypeIterator(withValues: [.inferred]) } - public func authTypesFor(schema: ModelSchema, - operations: [ModelOperation]) -> AWSAuthorizationTypeIterator { + public func authTypesFor( + schema: ModelSchema, + operations: [ModelOperation] + ) -> AWSAuthorizationTypeIterator { return AWSAuthorizationTypeIterator(withValues: [.inferred]) } } @@ -129,7 +133,7 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { private typealias AuthPriority = Int - required public init() {} + public required init() {} private static func defaultAuthTypeFor(authStrategy: AuthStrategy) -> AWSAuthorizationType { switch authStrategy { @@ -210,8 +214,10 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { /// - schema: model schema /// - operation: model operation /// - Returns: an iterator for the applicable auth rules - public func authTypesFor(schema: ModelSchema, - operation: ModelOperation) async -> AWSAuthorizationTypeIterator { + public func authTypesFor( + schema: ModelSchema, + operation: ModelOperation + ) async -> AWSAuthorizationTypeIterator { return await authTypesFor(schema: schema, operations: [operation]) } @@ -220,19 +226,21 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { /// - schema: model schema /// - operations: model operations /// - Returns: an iterator for the applicable auth rules - public func authTypesFor(schema: ModelSchema, - operations: [ModelOperation]) async -> AWSAuthorizationTypeIterator { + public func authTypesFor( + schema: ModelSchema, + operations: [ModelOperation] + ) async -> AWSAuthorizationTypeIterator { var sortedRules = operations .flatMap { schema.authRules.filter(modelOperation: $0) } - .reduce(into: [AuthRule](), { array, rule in + .reduce(into: [AuthRule]()) { array, rule in if !array.contains(rule) { array.append(rule) } - }) + } .sorted(by: AWSMultiAuthModeStrategy.comparator) // if there isn't a user signed in, returns only public or custom rules - if let authDelegate = authDelegate, await !authDelegate.isUserLoggedIn() { + if let authDelegate, await !authDelegate.isUserLoggedIn() { sortedRules = sortedRules.filter { rule in return rule.allow == .public || rule.allow == .custom } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift index b15b4b7d6c..338fdfaf7a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public class AWSAuthService: AWSAuthServiceBehavior { @@ -44,8 +44,12 @@ public class AWSAuthService: AWSAuthServiceBehavior { guard let claimsData = encodedData else { return .failure( - .validation("", "Cannot get claims in `Data` form. Token is not valid base64 encoded string.", - "", nil)) + .validation( + "", + "Cannot get claims in `Data` form. Token is not valid base64 encoded string.", + "", + nil + )) } let jsonObject: Any? @@ -53,14 +57,22 @@ public class AWSAuthService: AWSAuthServiceBehavior { jsonObject = try JSONSerialization.jsonObject(with: claimsData, options: []) } catch { return .failure( - .validation("", "Cannot get claims in `Data` form. Token is not valid JSON string.", - "", error)) + .validation( + "", + "Cannot get claims in `Data` form. Token is not valid JSON string.", + "", + error + )) } guard let convertedDictionary = jsonObject as? [String: AnyObject] else { return .failure( - .validation("", "Cannot get claims in `Data` form. Unable to convert to [String: AnyObject].", - "", nil)) + .validation( + "", + "Cannot get claims in `Data` form. Unable to convert to [String: AnyObject].", + "", + nil + )) } return .success(convertedDictionary) } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift index 1c23190588..2c18a89648 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public protocol AWSAuthServiceBehavior: AnyObject { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift index 36d71a87e8..6351485758 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Defines the contract for an AuthSession that can vend AWS credentials and store a user ID /// (`sub`) for the underlying OIDC-compliant authentication provider such as Cognito user pools. @@ -19,13 +19,13 @@ import Amplify /// successfully completed a `signIn` flow, and has not subsequently signed out. public protocol AWSAuthSessionBehavior: AuthSession { - /// The concrete type holding the OIDC tokens from the authentication provider. + /// The concrete type holding the OIDC tokens from the authentication provider. /// Generally, this type will have at least methods for retrieving an identity token and an access token. associatedtype Tokens /// The result of the most recent attempt to get AWS Credentials. There is no guarantee that the credentials /// are not expired, but conforming types may have logic in place to automatically refresh the credentials. - /// The credentials may be fore either the unauthenticated or authenticated role, depending on the + /// The credentials may be fore either the unauthenticated or authenticated role, depending on the /// configuration of the identity pool and the tokens used to retrieve the identity ID from Cognito. /// /// If the most recent attempt caused an error, the result will contain the details of the error. @@ -34,7 +34,7 @@ public protocol AWSAuthSessionBehavior: AuthSession { // swiftlint:disable line_length /// The result of the most recent attempt to get a /// [Cognito identity pool identity ID](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html#CognitoIdentity-GetId-response-IdentityId). - /// The identityID may represent either an unauthenticated or authenticated identity, + /// The identityID may represent either an unauthenticated or authenticated identity, /// depending on the configuration of the identity pool and the tokens used to /// retrieve the identity ID from Cognito. /// @@ -49,7 +49,7 @@ public protocol AWSAuthSessionBehavior: AuthSession { /// If the most recent attempt caused an error, the result will contain the details of the error. var userSubResult: Result { get } - /// The result of the most recent attempt to get the current user's `sub` (unique User ID). + /// The result of the most recent attempt to get the current user's `sub` (unique User ID). /// Depending on the underlying implementation, /// the details of the tokens may vary, but it is expected that the type will have at least methods for /// retrieving an identity token and an access token. diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthorizationType.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthorizationType.swift index 10e03c70a9..ebd4e05d4d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthorizationType.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthorizationType.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation // swiftlint:disable line_length @@ -49,8 +49,8 @@ extension AWSAuthorizationType: CaseIterable { } extension AWSAuthorizationType: Codable { } /// Indicates whether the authotization type requires the auth plugin to operate. -extension AWSAuthorizationType { - public var requiresAuthPlugin: Bool { +public extension AWSAuthorizationType { + var requiresAuthPlugin: Bool { switch self { case .none, .apiKey, .openIDConnect, .function: return false diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AmplifyAuthorizationType.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AmplifyAuthorizationType.swift index 18a90e3106..562a2f9c87 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AmplifyAuthorizationType.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AmplifyAuthorizationType.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation /// - Warning: Although this has `public` access, it is intended for internal use and should not be used directly diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AuthAWSCredentialsProvider.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AuthAWSCredentialsProvider.swift index 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..57168ab230 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Configuration/AWSAuthorizationConfiguration.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Configuration/AWSAuthorizationConfiguration.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public enum AWSAuthorizationConfiguration { case none @@ -21,9 +21,11 @@ public enum AWSAuthorizationConfiguration { extension AWSAuthorizationConfiguration { private static func awsIAMAuthorizationConfiguration(region: String?) throws -> AWSAuthorizationConfiguration { - guard let region = region else { - throw PluginError.pluginConfigurationError("Region is not set for IAM", - "Set the region") + guard let region else { + throw PluginError.pluginConfigurationError( + "Region is not set for IAM", + "Set the region" + ) } return .awsIAM(AWSIAMConfiguration(region: region)) } @@ -31,7 +33,7 @@ extension AWSAuthorizationConfiguration { private static func apiKeyAuthorizationConfiguration(apiKey: String?) throws -> AWSAuthorizationConfiguration { - guard let apiKey = apiKey else { + guard let apiKey else { throw PluginError.pluginConfigurationError( "Could not get `ApiKey` from plugin configuration", """ @@ -53,9 +55,11 @@ extension AWSAuthorizationConfiguration { /// - Throws: if the region is not valid and `authType` is `iam` /// or if `apiKey` is not valid and `authType` is `apiKey` /// - Returns: an `AWSAuthorizationConfiguration` according to the provided `authType` - public static func makeConfiguration(authType: AWSAuthorizationType, - region: String?, - apiKey: String?) throws -> AWSAuthorizationConfiguration { + public static func makeConfiguration( + authType: AWSAuthorizationType, + region: String?, + apiKey: String? + ) throws -> AWSAuthorizationConfiguration { switch authType { case .none: return .none diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift index 3b7ccee072..7cc6f37e33 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift @@ -24,11 +24,11 @@ extension KeychainStatus: CustomStringConvertible { self = .success case -128: self = .userCanceled - case -25299: + case -25_299: self = .duplicateItem - case -25300: + case -25_300: self = .itemNotFound - case -34018: + case -34_018: self = .missingEntitlement default: self = .unexpectedError(status) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift index 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..d739bde176 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/AnyModel/AnyModel.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public struct AnyModel: Model { public let id: String @@ -33,24 +33,26 @@ public struct AnyModel: Model { } } -extension AnyModel { +public extension AnyModel { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case instance case modelName } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { definition in + static let schema = defineSchema { definition in let anyModel = AnyModel.keys - definition.attributes(.isSystem, - .primaryKey(fields: [anyModel.id])) + definition.attributes( + .isSystem, + .primaryKey(fields: [anyModel.id]) + ) definition.fields( .field(anyModel.id, is: .required, ofType: .string), diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift index 0cf0f79d04..384e2564c6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public typealias IdentityClaimsDictionary = [String: AnyObject] @@ -37,19 +37,25 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { /// - authRuleDecoratorInput: decorator input /// - authType: authentication type, if provided will be used to filter the auth rules based on the provider field. /// Only use when multi-auth is enabled. - public init(_ authRuleDecoratorInput: AuthRuleDecoratorInput, - authType: AWSAuthorizationType? = nil) { + public init( + _ authRuleDecoratorInput: AuthRuleDecoratorInput, + authType: AWSAuthorizationType? = nil + ) { self.input = authRuleDecoratorInput self.authType = authType } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { let authRules = modelSchema.authRules .filterBy(authType: authType) .filterBy(ownerFieldType: .string, modelSchema: modelSchema) @@ -59,19 +65,24 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { var decorateDocument = document let readRestrictingStaticGroups = authRules.groupClaimsToReadRestrictingStaticGroups() - authRules.forEach { authRule in - decorateDocument = decorateAuthStrategy(document: decorateDocument, - authRule: authRule, - readRestrictingStaticGroups: readRestrictingStaticGroups) + for authRule in authRules { + decorateDocument = decorateAuthStrategy( + document: decorateDocument, + authRule: authRule, + readRestrictingStaticGroups: readRestrictingStaticGroups + ) } return decorateDocument } - private func decorateAuthStrategy(document: SingleDirectiveGraphQLDocument, - authRule: AuthRule, - readRestrictingStaticGroups: [String: Set]) -> SingleDirectiveGraphQLDocument { + private func decorateAuthStrategy( + document: SingleDirectiveGraphQLDocument, + authRule: AuthRule, + readRestrictingStaticGroups: [String: Set] + ) -> SingleDirectiveGraphQLDocument { guard authRule.allow == .owner, - var selectionSet = document.selectionSet else { + var selectionSet = document.selectionSet + else { return document } @@ -81,12 +92,16 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { if case let .subscription(_, claims) = input, let tokenClaims = claims, authRule.isReadRestrictingOwner() && - isNotInReadRestrictingStaticGroup(jwtTokenClaims: tokenClaims, - readRestrictingStaticGroups: readRestrictingStaticGroups) { + isNotInReadRestrictingStaticGroup( + jwtTokenClaims: tokenClaims, + readRestrictingStaticGroups: readRestrictingStaticGroups + ) { var inputs = document.inputs - let identityClaimValue = resolveIdentityClaimValue(identityClaim: authRule.identityClaimOrDefault(), - claims: tokenClaims) - if let identityClaimValue = identityClaimValue { + let identityClaimValue = resolveIdentityClaimValue( + identityClaim: authRule.identityClaimOrDefault(), + claims: tokenClaims + ) + if let identityClaimValue { inputs[ownerField] = GraphQLDocumentInput(type: "String!", value: .scalar(identityClaimValue)) } return document.copy(inputs: inputs, selectionSet: selectionSet) @@ -106,8 +121,10 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { return document.copy(selectionSet: selectionSet) } - private func isNotInReadRestrictingStaticGroup(jwtTokenClaims: IdentityClaimsDictionary, - readRestrictingStaticGroups: [String: Set]) -> Bool { + private func isNotInReadRestrictingStaticGroup( + jwtTokenClaims: IdentityClaimsDictionary, + readRestrictingStaticGroups: [String: Set] + ) -> Bool { for (groupClaim, readRestrictingStaticGroupsPerClaim) in readRestrictingStaticGroups { let groupsFromClaim = groupsFrom(jwtTokenClaims: jwtTokenClaims, groupClaim: groupClaim) let doesNotBelongToGroupsFromClaim = readRestrictingStaticGroupsPerClaim.isEmpty || @@ -121,8 +138,10 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { return true } - private func groupsFrom(jwtTokenClaims: IdentityClaimsDictionary, - groupClaim: String) -> Set { + private func groupsFrom( + jwtTokenClaims: IdentityClaimsDictionary, + groupClaim: String + ) -> Set { var groupSet = Set() if let groups = (jwtTokenClaims[groupClaim] as? NSArray) as Array? { for group in groups { @@ -146,11 +165,13 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { } /// First finds the first `model` SelectionSet. Then, only append it when the `ownerField` does not exist. - private func appendOwnerFieldToSelectionSetIfNeeded(selectionSet: SelectionSet, - ownerField: String) -> SelectionSet { + private func appendOwnerFieldToSelectionSetIfNeeded( + selectionSet: SelectionSet, + ownerField: String + ) -> SelectionSet { var selectionSetModel = selectionSet while selectionSetModel.value.fieldType != .model { - selectionSetModel.children.forEach { selectionSet in + for selectionSet in selectionSetModel.children { if selectionSet.value.fieldType == .model { selectionSetModel = selectionSet } @@ -158,7 +179,7 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { } - let containersOwnerField = selectionSetModel.children.contains { (field) -> Bool in + let containersOwnerField = selectionSetModel.children.contains { field -> Bool in if let fieldName = field.value.name, fieldName == ownerField { return true } @@ -175,7 +196,7 @@ public struct AuthRuleDecorator: ModelBasedGraphQLDocumentDecorator { private extension AuthRule { func ownerField(inSchema schema: ModelSchema) -> ModelField? { - guard let fieldName = self.ownerField else { + guard let fieldName = ownerField else { return nil } return schema.field(withName: fieldName) @@ -184,7 +205,7 @@ private extension AuthRule { private extension AuthRules { func filterBy(authType: AWSAuthorizationType?) -> AuthRules { - guard let authType = authType else { + guard let authType else { return self } @@ -199,8 +220,10 @@ private extension AuthRules { } } - func filterBy(ownerFieldType: ModelFieldType, - modelSchema: ModelSchema) -> AuthRules { + func filterBy( + ownerFieldType: ModelFieldType, + modelSchema: ModelSchema + ) -> AuthRules { return filter { guard let modelField = $0.ownerField(inSchema: modelSchema) else { // if we couldn't find the owner field means it has been implicitly diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift index 7d17b01e57..455d8f35c1 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift @@ -19,30 +19,36 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { private let graphQLType: GraphQLOperationType private var primaryKeysOnly: Bool - public init(version: Int? = nil, - lastSync: Int64? = nil, - graphQLType: GraphQLOperationType, - primaryKeysOnly: Bool = true) { + public init( + version: Int? = nil, + lastSync: Int64? = nil, + graphQLType: GraphQLOperationType, + primaryKeysOnly: Bool = true + ) { self.version = version self.lastSync = lastSync self.graphQLType = graphQLType self.primaryKeysOnly = primaryKeysOnly } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { var primaryKeysOnly = primaryKeysOnly if primaryKeysOnly && ModelRegistry.modelType(from: modelSchema.name)?.rootPath == nil { primaryKeysOnly = false } var inputs = document.inputs - if let version = version, + if let version, case .mutation = document.operationType, var input = inputs["input"], case var .object(value) = input.value { @@ -52,7 +58,7 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { inputs["input"] = input } - if let lastSync = lastSync, case .query = document.operationType { + if let lastSync, case .query = document.operationType { inputs["lastSync"] = GraphQLDocumentInput(type: "AWSTimestamp", value: .scalar(lastSync)) } @@ -69,9 +75,11 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { case deletedFieldOnly } /// Append the correct conflict resolution fields for `model` and `pagination` selection sets. - private func addConflictResolution(selectionSet: SelectionSet, - primaryKeysOnly: Bool, - includeSyncMetadataFields: SyncMetadataFields = .full) { + private func addConflictResolution( + selectionSet: SelectionSet, + primaryKeysOnly: Bool, + includeSyncMetadataFields: SyncMetadataFields = .full + ) { var includeSyncMetadataFields = includeSyncMetadataFields switch selectionSet.value.fieldType { case .value, .embedded: @@ -93,23 +101,27 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { if !primaryKeysOnly || graphQLType == .mutation { // Continue to add version fields for all levels, for backwards compatibility // Reduce the selection set only when the type is "subscription" and "query" - // (specifically for syncQuery). Selection set for mutation should not be reduced + // (specifically for syncQuery). Selection set for mutation should not be reduced // because it needs to be the full selection set to send mutation events to older iOS clients, // which do not have the reduced subscription selection set. // subscriptions and sync query is to receive data, so it can be reduced to allow decoding to the // LazyReference type. - selectionSet.children.forEach { child in - addConflictResolution(selectionSet: child, - primaryKeysOnly: primaryKeysOnly, - includeSyncMetadataFields: .full) + for child in selectionSet.children { + addConflictResolution( + selectionSet: child, + primaryKeysOnly: primaryKeysOnly, + includeSyncMetadataFields: .full + ) } } else { // Only add all the sync metadata fields once. Once this was done once, `includeSyncMetadataFields` // should be set to `.deletedFieldOnly` and passed down to the recursive call stack. - selectionSet.children.forEach { child in - addConflictResolution(selectionSet: child, - primaryKeysOnly: primaryKeysOnly, - includeSyncMetadataFields: includeSyncMetadataFields) + for child in selectionSet.children { + addConflictResolution( + selectionSet: child, + primaryKeysOnly: primaryKeysOnly, + includeSyncMetadataFields: includeSyncMetadataFields + ) } } } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/DirectiveNameDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/DirectiveNameDecorator.swift index 5776552be9..9e2ec3671a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/DirectiveNameDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/DirectiveNameDecorator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Replaces the directive name of the GraphQL document based on Amplify GraphQL operation types such as "get", "list", /// "sync", "create", "update", "delete", "onCreate", "onUpdate", and "onDelete". The GraphQL name is constructed based @@ -35,23 +35,27 @@ public struct DirectiveNameDecorator: ModelBasedGraphQLDocumentDecorator { self.subscriptionType = type } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { - if let queryType = queryType { + if let queryType { return document.copy(name: modelSchema.graphQLName(queryType: queryType)) } - if let mutationType = mutationType { + if let mutationType { return document.copy(name: modelSchema.graphQLName(mutationType: mutationType)) } - if let subscriptionType = subscriptionType { + if let subscriptionType { return document.copy(name: modelSchema.graphQLName(subscriptionType: subscriptionType)) } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift index bd78aad37f..6d7dea2894 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/FilterDecorator.swift @@ -18,13 +18,17 @@ public struct FilterDecorator: ModelBasedGraphQLDocumentDecorator { self.filter = filter } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { guard !filter.isEmpty else { return document.copy(inputs: document.inputs) } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/IncludeAssociationDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/IncludeAssociationDecorator.swift index 66da65a63d..8ee92d10ab 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/IncludeAssociationDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/IncludeAssociationDecorator.swift @@ -18,13 +18,17 @@ public struct IncludeAssociationDecorator: ModelBasedGraphQLDocumentDecorator { self.includedAssociations = includedAssociations } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { return decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { if includedAssociations.isEmpty { return document } @@ -32,7 +36,7 @@ public struct IncludeAssociationDecorator: ModelBasedGraphQLDocumentDecorator { return document } - includedAssociations.forEach { association in + for association in includedAssociations { // we don't include the root reference because it refers to the root model // fields in the selection set, only the nested/included ones are needed if let associationSelectionSet = association.asSelectionSet(includeRoot: false) { @@ -82,7 +86,7 @@ extension PropertyContainerPath { let selectionSets = nodesInPath(node: self).map(getSelectionSet(node:)) return selectionSets.dropFirst().reduce(selectionSets.first) { partialResult, selectionSet in - guard let partialResult = partialResult else { + guard let partialResult else { return selectionSet } selectionSet.replaceChild(partialResult) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift index 8a848b48a9..328da76ab0 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelBasedGraphQLDocumentDecorator.swift @@ -5,17 +5,21 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public protocol ModelBasedGraphQLDocumentDecorator { @available(*, deprecated, message: """ Decorating using Model.Type is deprecated, instead use modelSchema method. """) - func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument + func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument - func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument + func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift index 7a7ef66cfb..ef6b871951 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Decorate the GraphQL document with the data from an instance of the model. This is added as a single parameter /// called "input" that can be referenced by other decorators to append additional document inputs. This decorator @@ -21,21 +21,25 @@ public struct ModelDecorator: ModelBasedGraphQLDocumentDecorator { self.mutationType = mutationType } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { var inputs = document.inputs var graphQLInput = model.graphQLInputForMutation(modelSchema, mutationType: mutationType) if !modelSchema.authRules.isEmpty { - modelSchema.authRules.forEach { authRule in + for authRule in modelSchema.authRules { if authRule.allow == .owner { let ownerField = authRule.getOwnerFieldOrDefault() - graphQLInput = graphQLInput.filter { (field, value) -> Bool in + graphQLInput = graphQLInput.filter { field, value -> Bool in if field == ownerField, value == nil { return false } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift index 07a9a2d523..df7c5595a7 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Decorate the GraphQLDocument with the value of `ModelIdentifier` for a "delete" mutation or "get" query. public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { @@ -17,8 +17,10 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { var firstField = true self.identifierFields = model.identifier(schema: schema).fields.compactMap { fieldName, _ in - guard let value = model.graphQLInputForPrimaryKey(modelFieldName: fieldName, - modelSchema: schema) else { + guard let value = model.graphQLInputForPrimaryKey( + modelFieldName: fieldName, + modelSchema: schema + ) else { return nil } if firstField { @@ -32,7 +34,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { public init(identifierFields: [(name: String, value: Persistable)]) { var firstField = true - identifierFields.forEach { name, value in + for (name, value) in identifierFields { self.identifierFields.append((name: name, value: Self.convert(persistable: value), type: firstField == true ? "ID!" : "String!")) firstField = false } @@ -40,10 +42,10 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { public init(identifiers: [LazyReferenceIdentifier]) { var firstField = true - identifiers.forEach({ identifier in - self.identifierFields.append((name: identifier.name, value: identifier.value, type: firstField == true ? "ID!": "String!")) + for identifier in identifiers { + identifierFields.append((name: identifier.name, value: identifier.value, type: firstField == true ? "ID!" : "String!")) firstField = false - }) + } } @available(*, deprecated, message: "Use init(model:schema:)") @@ -56,7 +58,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { let identifier = (name: ModelIdentifierFormat.Default.name, value: id, type: "ID!") var identifierFields = [identifier] - if let fields = fields { + if let fields { identifierFields.append(contentsOf: fields.map { key, value in (name: key, value: value, type: "String!") }) @@ -64,13 +66,17 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { self.identifierFields = identifierFields } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { var inputs = document.inputs if case .mutation = document.operationType { @@ -94,7 +100,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { } } -fileprivate extension ModelIdDecorator { +private extension ModelIdDecorator { private static func convert(persistable: Persistable) -> GraphQLDocumentValueRepresentable { switch persistable { case let data as Double: diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/PaginationDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/PaginationDecorator.swift index bfe683ee55..3de8605169 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/PaginationDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/PaginationDecorator.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Decorate the document input with "limit" and "nextToken". Also paginates the selection set with pagination fields. public struct PaginationDecorator: ModelBasedGraphQLDocumentDecorator { @@ -19,29 +19,35 @@ public struct PaginationDecorator: ModelBasedGraphQLDocumentDecorator { self.nextToken = nextToken } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelType: Model.Type) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelType: Model.Type + ) -> SingleDirectiveGraphQLDocument { decorate(document, modelSchema: modelType.schema) } - public func decorate(_ document: SingleDirectiveGraphQLDocument, - modelSchema: ModelSchema) -> SingleDirectiveGraphQLDocument { + public func decorate( + _ document: SingleDirectiveGraphQLDocument, + modelSchema: ModelSchema + ) -> SingleDirectiveGraphQLDocument { var inputs = document.inputs - if let limit = limit { + if let limit { inputs["limit"] = GraphQLDocumentInput(type: "Int", value: .scalar(limit)) } else { inputs["limit"] = GraphQLDocumentInput(type: "Int", value: .scalar(1_000)) } - if let nextToken = nextToken { + if let nextToken { inputs["nextToken"] = GraphQLDocumentInput(type: "String", value: .scalar(nextToken)) } if let selectionSet = document.selectionSet { - return document.copy(inputs: inputs, - selectionSet: withPagination(selectionSet: selectionSet)) + return document.copy( + inputs: inputs, + selectionSet: withPagination(selectionSet: selectionSet) + ) } return document.copy(inputs: inputs) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift index ca03962ded..e681be161c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLMutation.swift @@ -5,16 +5,18 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// A concrete implementation of `SingleDirectiveGraphQLDocument` that represents a mutation operation. public struct GraphQLMutation: SingleDirectiveGraphQLDocument { - public init(operationType: GraphQLOperationType, - name: String, - inputs: [GraphQLParameterName: GraphQLDocumentInput], - selectionSet: SelectionSet?) { + public init( + operationType: GraphQLOperationType, + name: String, + inputs: [GraphQLParameterName: GraphQLDocumentInput], + selectionSet: SelectionSet? + ) { self.operationType = operationType self.name = name self.inputs = inputs diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift index 2f86d9cb44..1c7b60732f 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift @@ -5,16 +5,18 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// A concrete implementation of `SingleDirectiveGraphQLDocument` that represents a query operation. public struct GraphQLQuery: SingleDirectiveGraphQLDocument { - public init(operationType: GraphQLOperationType, - name: String, - inputs: [GraphQLParameterName: GraphQLDocumentInput], - selectionSet: SelectionSet?) { + public init( + operationType: GraphQLOperationType, + name: String, + inputs: [GraphQLParameterName: GraphQLDocumentInput], + selectionSet: SelectionSet? + ) { self.operationType = operationType self.name = name self.inputs = inputs diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLSubscription.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLSubscription.swift index d2cfdf77a0..a558138dc3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLSubscription.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLSubscription.swift @@ -11,10 +11,12 @@ import Foundation /// A concrete implementation of `SingleDirectiveGraphQLDocument` that represents a subscription operation. public struct GraphQLSubscription: SingleDirectiveGraphQLDocument { - public init(operationType: GraphQLOperationType, - name: String, - inputs: [GraphQLParameterName: GraphQLDocumentInput], - selectionSet: SelectionSet?) { + public init( + operationType: GraphQLOperationType, + name: String, + inputs: [GraphQLParameterName: GraphQLDocumentInput], + selectionSet: SelectionSet? + ) { self.operationType = operationType self.name = name self.inputs = inputs diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift index a737d57d2f..7247580d35 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Helps construct a `SingleDirectiveGraphQLDocument`. Collects instances of the decorators and applies the changes /// on the document. @@ -54,7 +54,7 @@ public struct ModelBasedGraphQLDocumentBuilder { public mutating func build() -> SingleDirectiveGraphQLDocument { let decoratedDocument = decorators.reduce(document) { doc, decorator in - decorator.decorate(doc, modelSchema: self.modelSchema) + decorator.decorate(doc, modelSchema: modelSchema) } return decoratedDocument diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift index a219bf3ad7..2fad197f59 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/SingleDirectiveGraphQLDocument.swift @@ -32,37 +32,43 @@ public protocol SingleDirectiveGraphQLDocument { var selectionSet: SelectionSet? { get set } /// Simple constructor to be implemented by the concrete types, used by the `copy` method. - init(operationType: GraphQLOperationType, - name: String, - inputs: [GraphQLParameterName: GraphQLDocumentInput], - selectionSet: SelectionSet?) + init( + operationType: GraphQLOperationType, + name: String, + inputs: [GraphQLParameterName: GraphQLDocumentInput], + selectionSet: SelectionSet? + ) } // Provides default implementation -extension SingleDirectiveGraphQLDocument { +public extension SingleDirectiveGraphQLDocument { /// Method to create a deep copy of the document, useful for `ModelBasedGraphQLDocumentDecorator` decorators /// when decorating a document and returning a new document. - public func copy(operationType: GraphQLOperationType? = nil, - name: String? = nil, - inputs: [GraphQLParameterName: GraphQLDocumentInput]? = nil, - selectionSet: SelectionSet? = nil) -> Self { - - return Self.init(operationType: operationType ?? self.operationType, - name: name ?? self.name, - inputs: inputs ?? self.inputs, - selectionSet: selectionSet ?? self.selectionSet) + func copy( + operationType: GraphQLOperationType? = nil, + name: String? = nil, + inputs: [GraphQLParameterName: GraphQLDocumentInput]? = nil, + selectionSet: SelectionSet? = nil + ) -> Self { + + return Self.init( + operationType: operationType ?? self.operationType, + name: name ?? self.name, + inputs: inputs ?? self.inputs, + selectionSet: selectionSet ?? self.selectionSet + ) } /// Returns nil when there are no `inputs`. Otherwise, consolidates the `inputs` /// into a single object that can be used for the GraphQL request. - public var variables: [String: Any]? { + var variables: [String: Any]? { if inputs.isEmpty { return nil } var variables = [String: Any]() - inputs.forEach { input in + for input in inputs { switch input.value.value { case .object(let values): variables.updateValue(values, forKey: input.key) @@ -78,7 +84,7 @@ extension SingleDirectiveGraphQLDocument { } /// Provides default construction of the graphQL document based on the components of the document. - public var stringValue: String { + var stringValue: String { let selectionSetString = selectionSet?.stringValue(indentSize: 2) ?? "" @@ -106,7 +112,7 @@ extension SingleDirectiveGraphQLDocument { return """ \(operationType.rawValue) \(name.pascalCased())\(variableInputTypes.isEmpty ? "" : "(\(variableInputTypes))") { - \(name)(\(inputParameters.map({ "\($0.0): \($0.1)"}).joined(separator: ", "))) { + \(name)(\(inputParameters.map { "\($0.0): \($0.1)"}.joined(separator: ", "))) { \(selectionSetString) } } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift index 44af846765..613b75e2ca 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift @@ -15,42 +15,56 @@ public typealias MutationSyncResult = MutationSync /// publicly exposed to developers protocol ModelSyncGraphQLRequestFactory { - static func query(modelName: String, - byId id: String, - authType: AWSAuthorizationType?) -> GraphQLRequest - - static func createMutation(of model: Model, - modelSchema: ModelSchema, - version: Int?, - authType: AWSAuthorizationType?) -> GraphQLRequest - - static func updateMutation(of model: Model, - modelSchema: ModelSchema, - where filter: GraphQLFilter?, - version: Int?, - authType: AWSAuthorizationType?) -> GraphQLRequest - - static func deleteMutation(of model: Model, - modelSchema: ModelSchema, - where filter: GraphQLFilter?, - version: Int?, - authType: AWSAuthorizationType?) -> GraphQLRequest - - static func subscription(to modelSchema: ModelSchema, - subscriptionType: GraphQLSubscriptionType, - authType: AWSAuthorizationType?) -> GraphQLRequest - - static func subscription(to modelSchema: ModelSchema, - subscriptionType: GraphQLSubscriptionType, - claims: IdentityClaimsDictionary, - authType: AWSAuthorizationType?) -> GraphQLRequest - - static func syncQuery(modelSchema: ModelSchema, - where predicate: QueryPredicate?, - limit: Int?, - nextToken: String?, - lastSync: Int64?, - authType: AWSAuthorizationType?) -> GraphQLRequest + static func query( + modelName: String, + byId id: String, + authType: AWSAuthorizationType? + ) -> GraphQLRequest + + static func createMutation( + of model: Model, + modelSchema: ModelSchema, + version: Int?, + authType: AWSAuthorizationType? + ) -> GraphQLRequest + + static func updateMutation( + of model: Model, + modelSchema: ModelSchema, + where filter: GraphQLFilter?, + version: Int?, + authType: AWSAuthorizationType? + ) -> GraphQLRequest + + static func deleteMutation( + of model: Model, + modelSchema: ModelSchema, + where filter: GraphQLFilter?, + version: Int?, + authType: AWSAuthorizationType? + ) -> GraphQLRequest + + static func subscription( + to modelSchema: ModelSchema, + subscriptionType: GraphQLSubscriptionType, + authType: AWSAuthorizationType? + ) -> GraphQLRequest + + static func subscription( + to modelSchema: ModelSchema, + subscriptionType: GraphQLSubscriptionType, + claims: IdentityClaimsDictionary, + authType: AWSAuthorizationType? + ) -> GraphQLRequest + + static func syncQuery( + modelSchema: ModelSchema, + where predicate: QueryPredicate?, + limit: Int?, + nextToken: String?, + lastSync: Int64?, + authType: AWSAuthorizationType? + ) -> GraphQLRequest } @@ -58,12 +72,16 @@ protocol ModelSyncGraphQLRequestFactory { /// as `version` and `lastSync` and returns a model that has been erased to `AnyModel`. extension GraphQLRequest: ModelSyncGraphQLRequestFactory { - public static func query(modelName: String, - byId id: String, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: modelName, - operationType: .query, - primaryKeysOnly: false) + public static func query( + modelName: String, + byId id: String, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: modelName, + operationType: .query, + primaryKeysOnly: false + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: ModelIdDecorator(id: id)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .query)) @@ -73,85 +91,111 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { let awsPluginOptions = AWSAPIPluginDataStoreOptions(authType: authType, modelName: modelName) let requestOptions = GraphQLRequest.Options(pluginOptions: awsPluginOptions) - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult?.self, - decodePath: document.name, - options: requestOptions) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult?.self, + decodePath: document.name, + options: requestOptions + ) } - public static func createMutation(of model: Model, - version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func createMutation( + of model: Model, + version: Int? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { createMutation(of: model, modelSchema: model.schema, version: version, authType: authType) } - public static func updateMutation(of model: Model, - where filter: GraphQLFilter? = nil, - version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func updateMutation( + of model: Model, + where filter: GraphQLFilter? = nil, + version: Int? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { updateMutation(of: model, modelSchema: model.schema, where: filter, version: version, authType: authType) } - public static func subscription(to modelType: Model.Type, - subscriptionType: GraphQLSubscriptionType, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func subscription( + to modelType: Model.Type, + subscriptionType: GraphQLSubscriptionType, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { subscription(to: modelType.schema, subscriptionType: subscriptionType, authType: authType) } - public static func subscription(to modelType: Model.Type, - subscriptionType: GraphQLSubscriptionType, - claims: IdentityClaimsDictionary, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func subscription( + to modelType: Model.Type, + subscriptionType: GraphQLSubscriptionType, + claims: IdentityClaimsDictionary, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { subscription(to: modelType.schema, subscriptionType: subscriptionType, claims: claims, authType: authType) } - public static func syncQuery(modelType: Model.Type, - where predicate: QueryPredicate? = nil, - limit: Int? = nil, - nextToken: String? = nil, - lastSync: Int64? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - syncQuery(modelSchema: modelType.schema, - where: predicate, - limit: limit, - nextToken: nextToken, - lastSync: lastSync, - authType: authType) + public static func syncQuery( + modelType: Model.Type, + where predicate: QueryPredicate? = nil, + limit: Int? = nil, + nextToken: String? = nil, + lastSync: Int64? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + syncQuery( + modelSchema: modelType.schema, + where: predicate, + limit: limit, + nextToken: nextToken, + lastSync: lastSync, + authType: authType + ) } - public static func createMutation(of model: Model, - modelSchema: ModelSchema, - version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func createMutation( + of model: Model, + modelSchema: ModelSchema, + version: Int? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { createOrUpdateMutation(of: model, modelSchema: modelSchema, type: .create, version: version, authType: authType) } - public static func updateMutation(of model: Model, - modelSchema: ModelSchema, - where filter: GraphQLFilter? = nil, - version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - createOrUpdateMutation(of: model, - modelSchema: modelSchema, - where: filter, - type: .update, - version: version, - authType: authType) + public static func updateMutation( + of model: Model, + modelSchema: ModelSchema, + where filter: GraphQLFilter? = nil, + version: Int? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + createOrUpdateMutation( + of: model, + modelSchema: modelSchema, + where: filter, + type: .update, + version: version, + authType: authType + ) } - public static func deleteMutation(of model: Model, - modelSchema: ModelSchema, - where filter: GraphQLFilter? = nil, - version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: modelSchema.name, - operationType: .mutation, - primaryKeysOnly: false) + public static func deleteMutation( + of model: Model, + modelSchema: ModelSchema, + where filter: GraphQLFilter? = nil, + version: Int? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: modelSchema.name, + operationType: .mutation, + primaryKeysOnly: false + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) - documentBuilder.add(decorator: ModelIdDecorator(model: model, - schema: modelSchema)) - if let filter = filter { + documentBuilder.add(decorator: ModelIdDecorator( + model: model, + schema: modelSchema + )) + if let filter { documentBuilder.add(decorator: FilterDecorator(filter: filter)) } documentBuilder.add(decorator: ConflictResolutionDecorator(version: version, graphQLType: .mutation, primaryKeysOnly: false)) @@ -161,20 +205,26 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { let awsPluginOptions = AWSAPIPluginDataStoreOptions(authType: authType, modelName: modelSchema.name) let requestOptions = GraphQLRequest.Options(pluginOptions: awsPluginOptions) - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult.self, - decodePath: document.name, - options: requestOptions) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult.self, + decodePath: document.name, + options: requestOptions + ) } - public static func subscription(to modelSchema: ModelSchema, - subscriptionType: GraphQLSubscriptionType, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func subscription( + to modelSchema: ModelSchema, + subscriptionType: GraphQLSubscriptionType, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, - operationType: .subscription, - primaryKeysOnly: true) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelSchema, + operationType: .subscription, + primaryKeysOnly: true + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: subscriptionType)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription, primaryKeysOnly: true)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(subscriptionType, nil), authType: authType)) @@ -182,21 +232,27 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { let awsPluginOptions = AWSAPIPluginDataStoreOptions(authType: authType, modelName: modelSchema.name) let requestOptions = GraphQLRequest.Options(pluginOptions: awsPluginOptions) - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult.self, - decodePath: document.name, - options: requestOptions) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult.self, + decodePath: document.name, + options: requestOptions + ) } - public static func subscription(to modelSchema: ModelSchema, - subscriptionType: GraphQLSubscriptionType, - claims: IdentityClaimsDictionary, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, - operationType: .subscription, - primaryKeysOnly: true) + public static func subscription( + to modelSchema: ModelSchema, + subscriptionType: GraphQLSubscriptionType, + claims: IdentityClaimsDictionary, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelSchema, + operationType: .subscription, + primaryKeysOnly: true + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: subscriptionType)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription, primaryKeysOnly: true)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(subscriptionType, claims), authType: authType)) @@ -207,22 +263,28 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { modelName: modelSchema.name ) let requestOptions = GraphQLRequest.Options(pluginOptions: awsPluginOptions) - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult.self, - decodePath: document.name, - options: requestOptions) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult.self, + decodePath: document.name, + options: requestOptions + ) } - public static func syncQuery(modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil, - limit: Int? = nil, - nextToken: String? = nil, - lastSync: Int64? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, - operationType: .query, - primaryKeysOnly: true) + public static func syncQuery( + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil, + limit: Int? = nil, + nextToken: String? = nil, + lastSync: Int64? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelSchema, + operationType: .query, + primaryKeysOnly: true + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) if let predicate = optimizePredicate(predicate) { documentBuilder.add(decorator: FilterDecorator(filter: predicate.graphQLFilter(for: modelSchema))) @@ -235,27 +297,33 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { let awsPluginOptions = AWSAPIPluginDataStoreOptions(authType: authType, modelName: modelSchema.name) let requestOptions = GraphQLRequest.Options(pluginOptions: awsPluginOptions) - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: SyncQueryResult.self, - decodePath: document.name, - options: requestOptions) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: SyncQueryResult.self, + decodePath: document.name, + options: requestOptions + ) } // MARK: Private methods - private static func createOrUpdateMutation(of model: Model, - modelSchema: ModelSchema, - where filter: GraphQLFilter? = nil, - type: GraphQLMutationType, - version: Int? = nil, - authType: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: modelSchema.name, - operationType: .mutation, - primaryKeysOnly: false) + private static func createOrUpdateMutation( + of model: Model, + modelSchema: ModelSchema, + where filter: GraphQLFilter? = nil, + type: GraphQLMutationType, + version: Int? = nil, + authType: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: modelSchema.name, + operationType: .mutation, + primaryKeysOnly: false + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: type)) documentBuilder.add(decorator: ModelDecorator(model: model, mutationType: type)) - if let filter = filter { + if let filter { documentBuilder.add(decorator: FilterDecorator(filter: filter)) } documentBuilder.add(decorator: ConflictResolutionDecorator(version: version, graphQLType: .mutation, primaryKeysOnly: false)) @@ -265,11 +333,13 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { let awsPluginOptions = AWSAPIPluginDataStoreOptions(authType: authType, modelName: modelSchema.name) let requestOptions = GraphQLRequest.Options(pluginOptions: awsPluginOptions) - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult.self, - decodePath: document.name, - options: requestOptions) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult.self, + decodePath: document.name, + options: requestOptions + ) } /// This function tries to optimize provided `QueryPredicate` to perform a DynamoDB query instead of a scan. @@ -278,7 +348,7 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { /// If the provided group is of type AND, the optimization will occur. /// If the top level group is OR or NOT, the optimization is not possible anyway. private static func optimizePredicate(_ predicate: QueryPredicate?) -> QueryPredicate? { - guard let predicate = predicate else { + guard let predicate else { return nil } if predicate as? QueryPredicateGroup != nil { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift index 7338fab830..47e3557d0a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift @@ -32,11 +32,13 @@ protocol ModelGraphQLRequestFactory { /// - Returns: a valid `GraphQLRequest` instance /// /// - seealso: `GraphQLQuery`, `GraphQLQueryType.list` - static func list(_ modelType: M.Type, - where predicate: QueryPredicate?, - includes: IncludedAssociations, - limit: Int?, - authMode: AWSAuthorizationType?) -> GraphQLRequest> + static func list( + _ modelType: M.Type, + where predicate: QueryPredicate?, + includes: IncludedAssociations, + limit: Int?, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest> /// Creates a `GraphQLRequest` that represents a query that expects a single value as a result. /// The request will be created with the correct correct document based on the `ModelSchema` and @@ -49,21 +51,27 @@ protocol ModelGraphQLRequestFactory { /// - Returns: a valid `GraphQLRequest` instance /// /// - seealso: `GraphQLQuery`, `GraphQLQueryType.get` - static func get(_ modelType: M.Type, - byId id: String, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest - - static func get(_ modelType: M.Type, - byIdentifier id: String, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func get( + _ modelType: M.Type, + byId id: String, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest + + static func get( + _ modelType: M.Type, + byIdentifier id: String, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default - static func get(_ modelType: M.Type, - byIdentifier id: ModelIdentifier, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func get( + _ modelType: M.Type, + byIdentifier id: ModelIdentifier, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest where M: ModelIdentifiable // MARK: Mutation @@ -76,12 +84,14 @@ protocol ModelGraphQLRequestFactory { /// - predicate: a predicate passed as the condition to apply the mutation /// - type: the mutation type, either `.create`, `.update`, or `.delete` /// - Returns: a valid `GraphQLRequest` instance - static func mutation(of model: M, - modelSchema: ModelSchema, - where predicate: QueryPredicate?, - includes: IncludedAssociations, - type: GraphQLMutationType, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func mutation( + of model: M, + modelSchema: ModelSchema, + where predicate: QueryPredicate?, + includes: IncludedAssociations, + type: GraphQLMutationType, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest /// Creates a `GraphQLRequest` that represents a create mutation /// for a given `model` instance. @@ -90,9 +100,11 @@ protocol ModelGraphQLRequestFactory { /// - model: the model instance populated with values /// - Returns: a valid `GraphQLRequest` instance /// - seealso: `GraphQLRequest.mutation(of:where:type:)` - static func create(_ model: M, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func create( + _ model: M, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest /// Creates a `GraphQLRequest` that represents an update mutation /// for a given `model` instance. @@ -102,10 +114,12 @@ protocol ModelGraphQLRequestFactory { /// - predicate: a predicate passed as the condition to apply the mutation /// - Returns: a valid `GraphQLRequest` instance /// - seealso: `GraphQLRequest.mutation(of:where:type:)` - static func update(_ model: M, - where predicate: QueryPredicate?, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func update( + _ model: M, + where predicate: QueryPredicate?, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest /// Creates a `GraphQLRequest` that represents a delete mutation /// for a given `model` instance. @@ -115,10 +129,12 @@ protocol ModelGraphQLRequestFactory { /// - predicate: a predicate passed as the condition to apply the mutation /// - Returns: a valid `GraphQLRequest` instance /// - seealso: `GraphQLRequest.mutation(of:where:type:)` - static func delete(_ model: M, - where predicate: QueryPredicate?, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func delete( + _ model: M, + where predicate: QueryPredicate?, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest // MARK: Subscription @@ -132,10 +148,12 @@ protocol ModelGraphQLRequestFactory { /// - Returns: a valid `GraphQLRequest` instance /// /// - seealso: `GraphQLSubscription`, `GraphQLSubscriptionType` - static func subscription(of: M.Type, - type: GraphQLSubscriptionType, - includes: IncludedAssociations, - authMode: AWSAuthorizationType?) -> GraphQLRequest + static func subscription( + of: M.Type, + type: GraphQLSubscriptionType, + includes: IncludedAssociations, + authMode: AWSAuthorizationType? + ) -> GraphQLRequest } // MARK: - Extension @@ -146,7 +164,7 @@ protocol ModelGraphQLRequestFactory { /// This is particularly useful when using the GraphQL API to interact /// with static types that conform to the `Model` protocol. extension GraphQLRequest: ModelGraphQLRequestFactory { - private static func modelSchema(for model: M) -> ModelSchema { + private static func modelSchema(for model: some Model) -> ModelSchema { let modelType = ModelRegistry.modelType(from: model.modelName) ?? Swift.type(of: model) return modelType.schema } @@ -154,96 +172,124 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { public static func create( _ model: M, includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { return create( model, modelSchema: modelSchema(for: model), includes: includes, - authMode: authMode) + authMode: authMode + ) } - public static func update(_ model: M, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func update( + _ model: M, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { return update( model, modelSchema: modelSchema(for: model), where: predicate, includes: includes, - authMode: authMode) + authMode: authMode + ) } - public static func delete(_ model: M, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { + public static func delete( + _ model: M, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { return delete( model, modelSchema: modelSchema(for: model), - where: predicate, + where: predicate, includes: includes, - authMode: authMode) + authMode: authMode + ) } - public static func create(_ model: M, - modelSchema: ModelSchema, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - return mutation(of: model, - modelSchema: modelSchema, - includes: includes, - type: .create, - authMode: authMode) + public static func create( + _ model: M, + modelSchema: ModelSchema, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + return mutation( + of: model, + modelSchema: modelSchema, + includes: includes, + type: .create, + authMode: authMode + ) } - public static func update(_ model: M, - modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - return mutation(of: model, - modelSchema: modelSchema, - where: predicate, - includes: includes, - type: .update, - authMode: authMode) + public static func update( + _ model: M, + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + return mutation( + of: model, + modelSchema: modelSchema, + where: predicate, + includes: includes, + type: .update, + authMode: authMode + ) } - public static func delete(_ model: M, - modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - return mutation(of: model, - modelSchema: modelSchema, - where: predicate, - includes: includes, - type: .delete, - authMode: authMode) + public static func delete( + _ model: M, + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + return mutation( + of: model, + modelSchema: modelSchema, + where: predicate, + includes: includes, + type: .delete, + authMode: authMode + ) } - public static func mutation(of model: M, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - type: GraphQLMutationType, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - mutation(of: model, - modelSchema: model.schema, - where: predicate, - includes: includes, - type: type, - authMode: authMode) + public static func mutation( + of model: M, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + type: GraphQLMutationType, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + mutation( + of: model, + modelSchema: model.schema, + where: predicate, + includes: includes, + type: type, + authMode: authMode + ) } - public static func mutation(of model: M, - modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - type: GraphQLMutationType, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, - operationType: .mutation) + public static func mutation( + of model: M, + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + type: GraphQLMutationType, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelSchema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: type)) if let modelPath = M.rootPath as? ModelPath { @@ -255,32 +301,40 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { case .create: documentBuilder.add(decorator: ModelDecorator(model: model, mutationType: type)) case .delete: - documentBuilder.add(decorator: ModelIdDecorator(model: model, - schema: modelSchema)) - if let predicate = predicate { + documentBuilder.add(decorator: ModelIdDecorator( + model: model, + schema: modelSchema + )) + if let predicate { documentBuilder.add(decorator: FilterDecorator(filter: predicate.graphQLFilter(for: modelSchema))) } case .update: documentBuilder.add(decorator: ModelDecorator(model: model, mutationType: type)) - if let predicate = predicate { + if let predicate { documentBuilder.add(decorator: FilterDecorator(filter: predicate.graphQLFilter(for: modelSchema))) } } let document = documentBuilder.build() - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: M.self, - decodePath: document.name, - authMode: authMode) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: M.self, + decodePath: document.name, + authMode: authMode + ) } - public static func get(_ modelType: M.Type, - byId id: String, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .query) + public static func get( + _ modelType: M.Type, + byId id: String, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) if let modelPath = modelType.rootPath as? ModelPath { @@ -291,28 +345,36 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { documentBuilder.add(decorator: ModelIdDecorator(id: id)) let document = documentBuilder.build() - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: M?.self, - decodePath: document.name, - authMode: authMode) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: M?.self, + decodePath: document.name, + authMode: authMode + ) } - public static func get(_ modelType: M.Type, - byIdentifier id: String, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + public static func get( + _ modelType: M.Type, + byIdentifier id: String, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { return .get(modelType, byId: id, includes: includes, authMode: authMode) } - public static func get(_ modelType: M.Type, - byIdentifier id: ModelIdentifier, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest + public static func get( + _ modelType: M.Type, + byIdentifier id: ModelIdentifier, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest where M: ModelIdentifiable { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) if let modelPath = modelType.rootPath as? ModelPath { @@ -322,21 +384,27 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { documentBuilder.add(decorator: ModelIdDecorator(identifierFields: id.fields)) let document = documentBuilder.build() - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: M?.self, - decodePath: document.name, - authMode: authMode) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: M?.self, + decodePath: document.name, + authMode: authMode + ) } - public static func list(_ modelType: M.Type, - where predicate: QueryPredicate? = nil, - includes: IncludedAssociations = { _ in [] }, - limit: Int? = nil, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest> { + public static func list( + _ modelType: M.Type, + where predicate: QueryPredicate? = nil, + includes: IncludedAssociations = { _ in [] }, + limit: Int? = nil, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest> { let primaryKeysOnly = (M.rootPath != nil) ? true : false - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) if let modelPath = modelType.rootPath as? ModelPath { @@ -344,26 +412,32 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { documentBuilder.add(decorator: IncludeAssociationDecorator(associations)) } - if let predicate = predicate { + if let predicate { documentBuilder.add(decorator: FilterDecorator(filter: predicate.graphQLFilter(for: modelType.schema))) } documentBuilder.add(decorator: PaginationDecorator(limit: limit)) let document = documentBuilder.build() - return GraphQLRequest>(document: document.stringValue, - variables: document.variables, - responseType: List.self, - decodePath: document.name, - authMode: authMode) + return GraphQLRequest>( + document: document.stringValue, + variables: document.variables, + responseType: List.self, + decodePath: document.name, + authMode: authMode + ) } - public static func subscription(of modelType: M.Type, - type: GraphQLSubscriptionType, - includes: IncludedAssociations = { _ in [] }, - authMode: AWSAuthorizationType? = nil) -> GraphQLRequest { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + public static func subscription( + of modelType: M.Type, + type: GraphQLSubscriptionType, + includes: IncludedAssociations = { _ in [] }, + authMode: AWSAuthorizationType? = nil + ) -> GraphQLRequest { + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: type)) if let modelPath = modelType.rootPath as? ModelPath { @@ -373,10 +447,12 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { let document = documentBuilder.build() - return GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: modelType, - decodePath: document.name, - authMode: authMode) + return GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: modelType, + decodePath: document.name, + authMode: authMode + ) } } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift index 72d6c1bcde..9c181f2d5c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/AuthRule+Extension.swift @@ -7,11 +7,11 @@ import Amplify -extension AuthRuleProvider { +public extension AuthRuleProvider { /// Returns corresponding `AWSAuthorizationType` for each `AuthRuleProvider` /// - Returns: AWS authorization type - public func toAWSAuthorizationType() -> AWSAuthorizationType { + func toAWSAuthorizationType() -> AWSAuthorizationType { var authType: AWSAuthorizationType switch self { case .apiKey: @@ -31,7 +31,7 @@ extension AuthRuleProvider { extension AuthRule { func getOwnerFieldOrDefault() -> String { - guard let ownerField = ownerField else { + guard let ownerField else { return "owner" } return ownerField @@ -53,7 +53,7 @@ extension AuthRule { } public func identityClaimOrDefault() -> String { - guard let identityClaim = self.identityClaim else { + guard let identityClaim else { return "username" } if identityClaim == "cognito:username" { @@ -63,7 +63,7 @@ extension AuthRule { } } -extension Array where Element == AuthRule { +extension [AuthRule] { // This function returns a map of all of the read restricting static groups defined for your app's schema // Example 1: Single group with implicit read restriction @@ -95,7 +95,7 @@ extension Array where Element == AuthRule { let readRestrictingGroupRules = filter { $0.isReadRestrictingStaticGroup() } for groupRule in readRestrictingGroupRules { let groupClaim = groupRule.groupClaim ?? "cognito:groups" - groupRule.groups.forEach { group in + for group in groupRule.groups { if var existingSet = readRestrictingStaticGroupsMap[groupClaim] { existingSet.insert(group) readRestrictingStaticGroupsMap[groupClaim] = existingSet diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift index 7b78a2dc47..4908fbca39 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation typealias GraphQLInput = [String: Any?] @@ -20,8 +20,10 @@ extension Model { private func fieldsForMutation(_ modelSchema: ModelSchema) -> [(ModelField, Any?)] { modelSchema.sortedFields.compactMap { field in guard !field.isReadOnly, - let fieldValue = getFieldValue(for: field.name, - modelSchema: modelSchema) else { + let fieldValue = getFieldValue( + for: field.name, + modelSchema: modelSchema + ) else { return nil } return (field, fieldValue) @@ -86,10 +88,12 @@ extension Model { input[name] = (value as? EnumPersistable)?.rawValue case .model(let associateModelName): // get the associated model target names and their values - let associatedModelIds = associatedModelIdentifierFields(fromModelValue: value, - field: modelField, - associatedModelName: associateModelName, - mutationType: mutationType) + let associatedModelIds = associatedModelIdentifierFields( + fromModelValue: value, + field: modelField, + associatedModelName: associateModelName, + mutationType: mutationType + ) for (fieldName, fieldValue) in associatedModelIds { input.updateValue(fieldValue, forKey: fieldName) } @@ -113,8 +117,10 @@ extension Model { /// Retrieve the custom primary key's value used for the GraphQL input. /// Only a subset of data types are applicable as custom indexes such as /// `date`, `dateTime`, `time`, `enum`, `string`, `double`, and `int`. - func graphQLInputForPrimaryKey(modelFieldName: ModelFieldName, - modelSchema: ModelSchema) -> String? { + func graphQLInputForPrimaryKey( + modelFieldName: ModelFieldName, + modelSchema: ModelSchema + ) -> String? { guard let modelField = modelSchema.field(withName: modelFieldName) else { return nil @@ -127,10 +133,11 @@ extension Model { } // swiftlint:disable:next syntactic_sugar + // swiftformat:disable typeSugar guard case .some(Optional.some(let value)) = fieldValue else { return nil } - + // swiftformat:enable typeSugar switch modelField.type { case .date, .dateTime, .time: if let date = value as? TemporalSpec { @@ -157,10 +164,12 @@ extension Model { /// - modelSchema: model schema /// - Returns: an array of key-value pairs where `key` is the field name /// and `value` its value in the associated model - private func associatedModelIdentifierFields(fromModelValue value: Any, - field: ModelField, - associatedModelName: String, - mutationType: GraphQLMutationType) -> [(String, Persistable?)] { + private func associatedModelIdentifierFields( + fromModelValue value: Any, + field: ModelField, + associatedModelName: String, + mutationType: GraphQLMutationType + ) -> [(String, Persistable?)] { guard let associateModelSchema = ModelRegistry.modelSchema(from: associatedModelName) else { preconditionFailure("Associated model \(associatedModelName) not found.") } @@ -199,13 +208,13 @@ extension Model { } else if let lazyModel = value as? (any _LazyReferenceValue) { switch lazyModel._state { case .notLoaded(let identifiers): - if let identifiers = identifiers { + if let identifiers { return identifiers.map { identifier in return identifier.value } } case .loaded(let model): - if let model = model { + if let model { return model.identifier(schema: modelSchema).values } } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift index 86f1d9445a..a88ed8907d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/ModelSchema+GraphQL.swift @@ -16,17 +16,17 @@ extension ModelSchema { let graphQLName: String switch queryType { case .list: - if let listPluralName = listPluralName { + if let listPluralName { graphQLName = queryType.rawValue + listPluralName - } else if let pluralName = pluralName { + } else if let pluralName { graphQLName = queryType.rawValue + pluralName } else { graphQLName = (queryType.rawValue + name).pluralize() } case .sync: - if let syncPluralName = syncPluralName { + if let syncPluralName { graphQLName = queryType.rawValue + syncPluralName - } else if let pluralName = pluralName { + } else if let pluralName { graphQLName = queryType.rawValue + pluralName } else { graphQLName = (queryType.rawValue + name).pluralize() diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift index f2e3a6f816..dcb600567d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public typealias GraphQLFilter = [String: Any] @@ -20,12 +20,16 @@ public struct GraphQLFilterConverter { /// Serialize the translated GraphQL query variable object to JSON string. /// - Warning: Although this has `public` access, it is intended for internal use and should not be used directly /// by host applications. The behavior of this may change without warning. - public static func toJSON(_ queryPredicate: QueryPredicate, - modelSchema: ModelSchema, - options: JSONSerialization.WritingOptions = []) throws -> String { + public static func toJSON( + _ queryPredicate: QueryPredicate, + modelSchema: ModelSchema, + options: JSONSerialization.WritingOptions = [] + ) throws -> String { let graphQLFilterData = - try JSONSerialization.data(withJSONObject: queryPredicate.graphQLFilter(for: modelSchema), - options: options) + try JSONSerialization.data( + withJSONObject: queryPredicate.graphQLFilter(for: modelSchema), + options: options + ) guard let serializedString = String(data: graphQLFilterData, encoding: .utf8) else { return Fatal.preconditionFailure(""" @@ -41,10 +45,14 @@ public struct GraphQLFilterConverter { Use `toJSON(_:modelSchema:options)` instead. See https://github.com/aws-amplify/amplify-ios/pull/965 for more details. """) /// Serialize the translated GraphQL query variable object to JSON string. - public static func toJSON(_ queryPredicate: QueryPredicate, - options: JSONSerialization.WritingOptions = []) throws -> String { - let graphQLFilterData = try JSONSerialization.data(withJSONObject: queryPredicate.graphQLFilter, - options: options) + public static func toJSON( + _ queryPredicate: QueryPredicate, + options: JSONSerialization.WritingOptions = [] + ) throws -> String { + let graphQLFilterData = try JSONSerialization.data( + withJSONObject: queryPredicate.graphQLFilter, + options: options + ) guard let serializedString = String(data: graphQLFilterData, encoding: .utf8) else { return Fatal.preconditionFailure(""" @@ -68,11 +76,11 @@ public struct GraphQLFilterConverter { } /// Extension to translate a `QueryPredicate` into a GraphQL query variables object -extension QueryPredicate { +public extension QueryPredicate { /// - Warning: Although this has `public` access, it is intended for internal use and should not be used directly /// by host applications. The behavior of this may change without warning. - public func graphQLFilter(for modelSchema: ModelSchema?) -> GraphQLFilter { + func graphQLFilter(for modelSchema: ModelSchema?) -> GraphQLFilter { if let operation = self as? QueryPredicateOperation { return operation.graphQLFilter(for: modelSchema) } else if let group = self as? QueryPredicateGroup { @@ -88,7 +96,7 @@ extension QueryPredicate { @available(*, deprecated, message: """ Use `graphQLFilter(for:)` instead. See https://github.com/aws-amplify/amplify-ios/pull/965 for more details. """) - public var graphQLFilter: GraphQLFilter { + var graphQLFilter: GraphQLFilter { if let operation = self as? QueryPredicateOperation { return operation.graphQLFilter(for: nil) } else if let group = self as? QueryPredicateGroup { @@ -113,7 +121,7 @@ extension QueryPredicateOperation: GraphQLFilterConvertible { func graphQLFilter(for modelSchema: ModelSchema?) -> GraphQLFilter { let filterValue = [self.operator.graphQLOperator: self.operator.value] - guard let modelSchema = modelSchema else { + guard let modelSchema else { return [field: filterValue] } return [columnName(modelSchema): filterValue] @@ -150,7 +158,7 @@ extension QueryPredicateGroup: GraphQLFilterConvertible { switch type { case .and, .or: var graphQLPredicateOperation = [logicalOperator: [Any]()] - predicates.forEach { predicate in + for predicate in predicates { graphQLPredicateOperation[logicalOperator]?.append(predicate.graphQLFilter(for: modelSchema)) } return graphQLPredicateOperation @@ -194,7 +202,7 @@ extension QueryOperator { switch self { case .notEqual(let value), .equals(let value): - if let value = value { + if let value { return value.graphQLValue() } @@ -217,7 +225,7 @@ extension QueryOperator { } extension Persistable { - internal func graphQLValue() -> Any { + func graphQLValue() -> Any { switch self { case is Bool: return self diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift index b926808de4..8a0d8d2bf3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public typealias SelectionSet = Tree @@ -43,11 +43,11 @@ extension SelectionSet { } func withModelFields(_ fields: [ModelField], recursive: Bool = true, primaryKeysOnly: Bool) { - fields.forEach { field in + for field in fields { if field.isEmbeddedType, let embeddedTypeSchema = field.embeddedTypeSchema { let child = SelectionSet(value: .init(name: field.name, fieldType: .embedded)) child.withEmbeddableFields(embeddedTypeSchema.sortedFields) - self.addChild(settingParentOf: child) + addChild(settingParentOf: child) } else if field._isBelongsToOrHasOne, let associatedModelName = field.associatedModelName, let schema = ModelRegistry.modelSchema(from: associatedModelName) { @@ -64,10 +64,10 @@ extension SelectionSet { child.withModelFields(schema.graphQLFields, recursive: recursive, primaryKeysOnly: primaryKeysOnly) } - self.addChild(settingParentOf: child) + addChild(settingParentOf: child) } } else { - self.addChild(settingParentOf: .init(value: .init(name: field.graphQLName, fieldType: .value))) + addChild(settingParentOf: .init(value: .init(name: field.graphQLName, fieldType: .value))) } } @@ -75,13 +75,13 @@ extension SelectionSet { } func withEmbeddableFields(_ fields: [ModelField]) { - fields.forEach { field in + for field in fields { if field.isEmbeddedType, let embeddedTypeSchema = field.embeddedTypeSchema { let child = SelectionSet(value: .init(name: field.name, fieldType: .embedded)) child.withEmbeddableFields(embeddedTypeSchema.sortedFields) - self.addChild(settingParentOf: child) + addChild(settingParentOf: child) } else { - self.addChild(settingParentOf: .init(value: .init(name: field.name, fieldType: .value))) + addChild(settingParentOf: .init(value: .init(name: field.name, fieldType: .value))) } } addChild(settingParentOf: .init(value: .typename)) @@ -112,12 +112,12 @@ extension SelectionSet { case .model, .pagination, .embedded: if let name = value.name { result.append(indent + name + " {") - children.forEach { innerSelectionSetField in + for innerSelectionSetField in children { result.append(innerSelectionSetField.stringValue(indentSize: indentSize + 1)) } result.append(indent + "}") } else { - children.forEach { innerSelectionSetField in + for innerSelectionSetField in children { result.append(innerSelectionSetField.stringValue(indentSize: indentSize)) } } @@ -125,7 +125,7 @@ extension SelectionSet { let doubleIndent = String(repeating: indentValue, count: indentSize + 1) result.append(indent + (value.name ?? "") + " {") result.append(doubleIndent + "items {") - children.forEach { innerSelectionSetField in + for innerSelectionSetField in children { result.append(innerSelectionSetField.stringValue(indentSize: indentSize + 2)) } result.append(doubleIndent + "}") @@ -181,7 +181,7 @@ extension SelectionSet { let name = selectionSet.value.name ?? "" if let existingField = findChild(byName: name) { var replaceFields: [SelectionSet] = [] - selectionSet.children.forEach { child in + for child in selectionSet.children { if child.value.fieldType != .value, let childName = child.value.name { if existingField.findChild(byName: childName) != nil { existingField.merge(with: child) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata+Schema.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata+Schema.swift index 99ec90c255..14675f4b99 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata+Schema.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata+Schema.swift @@ -8,21 +8,21 @@ import Amplify import Foundation -extension ModelSyncMetadata { +public extension ModelSyncMetadata { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case lastSync case syncPredicate } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { definition in + static let schema = defineSchema { definition in definition.attributes(.isSystem) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift index d6723f4835..fe17daa10c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift @@ -17,9 +17,11 @@ public struct ModelSyncMetadata: Model { /// The sync predicate for this model, extracted out from the sync expression. public var syncPredicate: String? - public init(id: String, - lastSync: Int64? = nil, - syncPredicate: String? = nil) { + public init( + id: String, + lastSync: Int64? = nil, + syncPredicate: String? = nil + ) { self.id = id self.lastSync = lastSync self.syncPredicate = syncPredicate diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSync.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSync.swift index 8348ac5132..1e2bf1f054 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSync.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSync.swift @@ -37,12 +37,14 @@ public struct MutationSync: Decodable { guard case let .string(modelName) = json["__typename"] else { throw DataStoreError.decodingError( "The key `__typename` was not found", - "Check if the parsed JSON contains the expected `__typename`") + "Check if the parsed JSON contains the expected `__typename`" + ) } guard let actualModelType = ModelRegistry.modelType(from: modelName) else { throw DataStoreError.decodingError( "Model named `\(modelName)` could not be resolved.", - "Make sure `\(modelName)` was registered using `ModelRegistry.register`") + "Make sure `\(modelName)` was registered using `ModelRegistry.register`" + ) } let model = try actualModelType.init(from: decoder) guard let anyModel = try model.eraseToAnyModel() as? ModelType else { @@ -52,7 +54,8 @@ public struct MutationSync: Decodable { Please take a look at https://github.com/aws-amplify/amplify-ios/issues to see if there are any existing issues that match your scenario, and file an issue with the details of the bug if there isn't. - """) + """ + ) } self.model = anyModel resolvedModelName = modelName @@ -67,10 +70,10 @@ public struct MutationSync: Decodable { // TODO query name could be useful for the message, but re-creating it here is not great let queryName = modelType.schema.syncPluralName ?? modelType.schema.pluralName ?? modelType.modelName throw DataStoreError.decodingError( - """ + """ Error decoding the the sync metadata from the delta sync query result. """, - """ + """ The sync metadata should contain fields named `_deleted`, `_lastChangedAt` and `_version`. Check your sync`\(queryName)` query and make sure it returns the correct set of sync fields. """ @@ -84,10 +87,12 @@ public struct MutationSync: Decodable { let modelIdentifier = model.identifier(schema: modelSchema).stringValue - self.syncMetadata = MutationSyncMetadata(modelId: modelIdentifier, - modelName: resolvedModelName, - deleted: deleted, - lastChangedAt: Int64(lastChangedAt), - version: Int(version)) + self.syncMetadata = MutationSyncMetadata( + modelId: modelIdentifier, + modelName: resolvedModelName, + deleted: deleted, + lastChangedAt: Int64(lastChangedAt), + version: Int(version) + ) } } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift index 718e3348f6..86e49d3fd6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift @@ -8,22 +8,22 @@ import Amplify import Foundation -extension MutationSyncMetadata { +public extension MutationSyncMetadata { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case deleted case lastChangedAt case version } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { definition in + static let schema = defineSchema { definition in let sync = MutationSyncMetadata.keys definition.attributes(.isSystem) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/PaginatedList.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/PaginatedList.swift index 1458988802..5b31f43057 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/PaginatedList.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/PaginatedList.swift @@ -28,18 +28,18 @@ public struct PaginatedList: Decodable { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let optimisticDecodedResults = try values.decode([OptimisticDecoded>].self, forKey: .items) - items = optimisticDecodedResults.compactMap { try? $0.result.get() } - nextToken = try values.decode(String?.self, forKey: .nextToken) - startedAt = try values.decode(Int64?.self, forKey: .startedAt) + self.items = optimisticDecodedResults.compactMap { try? $0.result.get() } + self.nextToken = try values.decode(String?.self, forKey: .nextToken) + self.startedAt = try values.decode(Int64?.self, forKey: .startedAt) } } -fileprivate struct OptimisticDecoded: Decodable { +private struct OptimisticDecoded: Decodable { let result: Result init(from decoder: Decoder) throws { - result = Result(catching: { + self.result = Result(catching: { try T(from: decoder) }) } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/AmplifyNetworkMonitor.swift b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/AmplifyNetworkMonitor.swift index 85801c4bd5..22a0a5546a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/AmplifyNetworkMonitor.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/AmplifyNetworkMonitor.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Network import Combine +import Network @_spi(WebSocket) public final class AmplifyNetworkMonitor { @@ -28,7 +28,7 @@ public final class AmplifyNetworkMonitor { } public init(on interface: NWInterface.InterfaceType? = nil) { - monitor = interface.map(NWPathMonitor.init(requiredInterfaceType:)) ?? NWPathMonitor() + self.monitor = interface.map(NWPathMonitor.init(requiredInterfaceType:)) ?? NWPathMonitor() monitor.pathUpdateHandler = { [weak self] path in self?.subject.send(path.status == .satisfied ? .online : .offline) } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/RetryWithJitter.swift b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/RetryWithJitter.swift index 9da51cb03f..502301fdb1 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/RetryWithJitter.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/RetryWithJitter.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation @_spi(WebSocket) @@ -17,7 +16,7 @@ public actor RetryWithJitter { let max: UInt var retryCount: UInt = 0 - init(base: UInt = 25, max: UInt = 6400) { + init(base: UInt = 25, max: UInt = 6_400) { self.base = base self.max = max } @@ -28,16 +27,16 @@ public actor RetryWithJitter { func next() -> UInt { let expo = min(max, powerOf2(count: retryCount) * base) retryCount += 1 - return UInt.random(in: 0..( +public extension RetryWithJitter { + static func execute( maxRetryCount: UInt = 8, shouldRetryOnError: (Swift.Error) -> Bool = { _ in true }, _ operation: @escaping () async throws -> Output @@ -51,7 +50,7 @@ extension RetryWithJitter { let backoffInterval = retryCount == 0 ? 0 : await retryWithJitter.next() do { try await Task.sleep(nanoseconds: UInt64(backoffInterval) * 1_000_000) - return .success(try await operation()) + return try await .success(operation()) } catch { print("[RetryWithJitter] operation failed with error \(error), retrying(\(retryCount))") if shouldRetryOnError(error) { @@ -65,7 +64,7 @@ extension RetryWithJitter { } } -fileprivate func powerOf2(count: UInt) -> UInt { +private func powerOf2(count: UInt) -> UInt { count == 0 ? 1 : 2 * powerOf2(count: count - 1) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketClient.swift b/AmplifyPlugins/Core/AWSPluginsCore/WebSocket/WebSocketClient.swift index 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..32a41d8d7b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Auth/AuthModeStrategyTests.swift @@ -89,9 +89,11 @@ class AuthModeStrategyTests: XCTestCase { let authMode = AWSMultiAuthModeStrategy() let delegate = UnauthenticatedUserDelegate() authMode.authDelegate = delegate - - var authTypesIterator = await authMode.authTypesFor(schema: ModelWithOwnerAndPublicAuth.schema, - operation: .create) + + var authTypesIterator = await authMode.authTypesFor( + schema: ModelWithOwnerAndPublicAuth.schema, + operation: .create + ) XCTAssertEqual(authTypesIterator.count, 1) XCTAssertEqual(authTypesIterator.next()?.awsAuthType, .apiKey) } @@ -101,8 +103,10 @@ class AuthModeStrategyTests: XCTestCase { // Then: applicable auth types returned respect the priority rules func testMultiAuthPriorityWithCustomStrategy() async { let authMode = AWSMultiAuthModeStrategy() - var authTypesIterator = await authMode.authTypesFor(schema: ModelWithCustomStrategy.schema, - operation: .create) + var authTypesIterator = await authMode.authTypesFor( + schema: ModelWithCustomStrategy.schema, + operation: .create + ) XCTAssertEqual(authTypesIterator.count, 3) XCTAssertEqual(authTypesIterator.next()?.awsAuthType, .function) XCTAssertEqual(authTypesIterator.next()?.awsAuthType, .amazonCognitoUserPools) @@ -117,8 +121,10 @@ class AuthModeStrategyTests: XCTestCase { let delegate = UnauthenticatedUserDelegate() authMode.authDelegate = delegate - var authTypesIterator = await authMode.authTypesFor(schema: ModelWithCustomStrategy.schema, - operation: .create) + var authTypesIterator = await authMode.authTypesFor( + schema: ModelWithCustomStrategy.schema, + operation: .create + ) XCTAssertEqual(authTypesIterator.count, 2) XCTAssertEqual(authTypesIterator.next()?.awsAuthType, .function) XCTAssertEqual(authTypesIterator.next()?.awsAuthType, .awsIAM) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelMultipleOwnerAuthRuleTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelMultipleOwnerAuthRuleTests.swift index b6ae079862..a9a50bce1a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelMultipleOwnerAuthRuleTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelMultipleOwnerAuthRuleTests.swift @@ -9,6 +9,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSPluginsCore + /* type ModelMultipleOwner @model @auth(rules: [ @@ -26,9 +27,11 @@ public struct ModelMultipleOwner: Model { public let id: String public var content: String public var editors: [String]? - public init(id: String = UUID().uuidString, - content: String, - editors: [String]? = []) { + public init( + id: String = UUID().uuidString, + content: String, + editors: [String]? = [] + ) { self.id = id self.content = content self.editors = editors @@ -71,11 +74,13 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { override func tearDown() { ModelRegistry.reset() } - + // Ensure that the `owner` field is added to the model fields func testModelMultipleOwner_CreateMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -97,8 +102,10 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelMultipleOwner_DeleteMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -120,8 +127,10 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelMultipleOwner_UpdateMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -143,8 +152,10 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelMultipleOwner_GetQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: AuthRuleDecorator(.query)) let document = documentBuilder.build() @@ -166,8 +177,10 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // A List query is a paginated selection set, make sure the `owner` field is added to the model fields func testModelMultipleOwner_ListQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: AuthRuleDecorator(.query)) @@ -191,8 +204,10 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { } func testModelMultipleOwner_SyncQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .query)) @@ -219,13 +234,17 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { XCTAssertEqual(document.name, "syncModelMultipleOwners") XCTAssertEqual(document.stringValue, expectedQueryDocument) } - + // Only the 'owner' inherently has `.create` operation, requiring the subscription operation to contain the input func testModelMultipleOwner_OnCreateSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -251,10 +270,14 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // Each owner with `.update` operation requires the ownerField on the corresponding subscription operation func testModelMultipleOwner_OnUpdateSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onUpdate, claims))) let document = documentBuilder.build() @@ -280,10 +303,14 @@ class ModelMultipleOwnerAuthRuleTests: XCTestCase { // Only the 'owner' inherently has `.delete` operation, requiring the subscription operation to contain the input func testModelMultipleOwner_OnDeleteSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelMultipleOwner.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelMultipleOwner.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, claims))) let document = documentBuilder.build() diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift index 778945a24f..d31f860e4c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelReadUpdateAuthRuleTests.swift @@ -23,8 +23,10 @@ import XCTest public struct ModelReadUpdateField: Model { public let id: String public var content: String - public init(id: String = UUID().uuidString, - content: String) { + public init( + id: String = UUID().uuidString, + content: String + ) { self.id = id self.content = content } @@ -41,7 +43,8 @@ public struct ModelReadUpdateField: Model { ] model.fields( .id(), - .field(modelReadUpdateField.content, is: .required, ofType: .string)) + .field(modelReadUpdateField.content, is: .required, ofType: .string) + ) } } @@ -57,8 +60,10 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelReadUpdateField_CreateMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -79,8 +84,10 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelReadUpdateField_DeleteMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -101,8 +108,10 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelReadUpdateField_UpdateMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -123,8 +132,10 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // Ensure that the `owner` field is added to the model fields func testModelReadUpdateField_GetQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: AuthRuleDecorator(.query)) let document = documentBuilder.build() @@ -145,8 +156,10 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // A List query is a paginated selection set, make sure the `owner` field is added to the model fields func testModelReadUpdateField_ListQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: AuthRuleDecorator(.query)) @@ -169,8 +182,10 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { } func testModelReadUpdateField_SyncQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .query)) @@ -199,10 +214,14 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // The owner auth rule contains `.create` operation, requiring the subscription operation to contain the input func testModelReadUpdateField_OnCreateSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -223,10 +242,14 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // Others can `.update` this model, which means the update subscription does not require owner input func testModelReadUpdateField_OnUpdateSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onUpdate, claims))) let document = documentBuilder.build() @@ -246,10 +269,14 @@ class ModelReadUpdateAuthRuleTests: XCTestCase { // The owner auth rule contains `.delete` operation, requiring the subscription operation to contain the input func testModelReadUpdateField_OnDeleteSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelReadUpdateField.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelReadUpdateField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, claims))) let document = documentBuilder.build() diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift index a1d37b50fd..a321edca6e 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndGroupWithGroupClaim.swift @@ -32,9 +32,11 @@ public struct OIDCGroupPost: Model { public var title: String public var owner: String? - public init(id: String = UUID().uuidString, - title: String, - owner: String? = nil) { + public init( + id: String = UUID().uuidString, + title: String, + owner: String? = nil + ) { self.id = id self.title = title self.owner = owner @@ -52,23 +54,27 @@ public struct OIDCGroupPost: Model { let oIDCGroupPost = OIDCGroupPost.keys model.authRules = [ - rule(allow: .owner, - ownerField: "owner", - identityClaim: "sub", - operations: [.create, .update, .delete, .read]), - rule(allow: .groups, - groupClaim: "https://myapp.com/claims/groups", - groups: ["Admins"], - operations: [.create, .update, .delete, .read]) + rule( + allow: .owner, + ownerField: "owner", + identityClaim: "sub", + operations: [.create, .update, .delete, .read] + ), + rule( + allow: .groups, + groupClaim: "https://myapp.com/claims/groups", + groups: ["Admins"], + operations: [.create, .update, .delete, .read] + ) ] model.listPluralName = "OIDCGroupPosts" model.syncPluralName = "OIDCGroupPosts" model.fields( - .id(), - .field(oIDCGroupPost.title, is: .required, ofType: .string), - .field(oIDCGroupPost.owner, is: .optional, ofType: .string) + .id(), + .field(oIDCGroupPost.title, is: .required, ofType: .string), + .field(oIDCGroupPost.owner, is: .optional, ofType: .string) ) } } @@ -83,10 +89,14 @@ class ModelWithOwnerAuthAndGroupWithGroupClaim: XCTestCase { } func testOnCreateSubscription_NoGroupInfoPassed() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -110,11 +120,15 @@ class ModelWithOwnerAuthAndGroupWithGroupClaim: XCTestCase { } func testOnCreateSubscription_InAdminsGroup() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://myapp.com/claims/groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://myapp.com/claims/groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -134,11 +148,15 @@ class ModelWithOwnerAuthAndGroupWithGroupClaim: XCTestCase { } func testOnCreateSubscription_InAdminsGroupAndAnother() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://myapp.com/claims/groups": ["Admins", "Users"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://myapp.com/claims/groups": ["Admins", "Users"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -158,11 +176,15 @@ class ModelWithOwnerAuthAndGroupWithGroupClaim: XCTestCase { } func testOnCreateSubscription_NotInAdminsGroup() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://myapp.com/claims/groups": ["Users"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://myapp.com/claims/groups": ["Users"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift index 03ac101b21..e302631d99 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerAuthAndMultiGroup.swift @@ -34,9 +34,11 @@ public struct OIDCMultiGroupPost: Model { public var title: String public var owner: String? - public init(id: String = UUID().uuidString, - title: String, - owner: String? = nil) { + public init( + id: String = UUID().uuidString, + title: String, + owner: String? = nil + ) { self.id = id self.title = title self.owner = owner @@ -54,18 +56,24 @@ public struct OIDCMultiGroupPost: Model { let oIDCMultiGroupPost = OIDCMultiGroupPost.keys model.authRules = [ - rule(allow: .owner, - ownerField: "owner", - identityClaim: "sub", - operations: [.create, .update, .delete, .read]), - rule(allow: .groups, - groupClaim: "https://myapp.com/claims/groups", - groups: ["Admins"], - operations: [.create, .update, .delete, .read]), - rule(allow: .groups, - groupClaim: "https://differentapp.com/claims/groups", - groups: ["Moderators", "Editors"], - operations: [.create, .update, .delete, .read]) + rule( + allow: .owner, + ownerField: "owner", + identityClaim: "sub", + operations: [.create, .update, .delete, .read] + ), + rule( + allow: .groups, + groupClaim: "https://myapp.com/claims/groups", + groups: ["Admins"], + operations: [.create, .update, .delete, .read] + ), + rule( + allow: .groups, + groupClaim: "https://differentapp.com/claims/groups", + groups: ["Moderators", "Editors"], + operations: [.create, .update, .delete, .read] + ) ] model.listPluralName = "OIDCMultiGroupPosts" model.syncPluralName = "OIDCMultiGroupPosts" @@ -87,10 +95,14 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { } func testOnCreateSubscription_NoGroupInfoPassed() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCMultiGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCMultiGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -110,17 +122,23 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { XCTFail("The document doesn't contain variables") return } - XCTAssertEqual(variables["owner"] as? String, - "123e4567-dead-beef-a456-426614174000", - "owner should exist since there were no groups present in the claims to match the schema") + XCTAssertEqual( + variables["owner"] as? String, + "123e4567-dead-beef-a456-426614174000", + "owner should exist since there were no groups present in the claims to match the schema" + ) } func testOnCreateSubscription_InDifferentAppWithModerators() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://differentapp.com/claims/groups": ["Moderators"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCMultiGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://differentapp.com/claims/groups": ["Moderators"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCMultiGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -136,16 +154,22 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { """ XCTAssertEqual(document.name, "onCreateOIDCMultiGroupPost") XCTAssertEqual(document.stringValue, expectedQueryDocument) - XCTAssertTrue(document.variables.isEmpty, - "variables should be empty since claim group value matches the auth rule schema") + XCTAssertTrue( + document.variables.isEmpty, + "variables should be empty since claim group value matches the auth rule schema" + ) } func testOnCreateSubscription_InDifferentAppWithModeratorsAndEditors() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://differentapp.com/claims/groups": ["Moderators", "Editors"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCMultiGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://differentapp.com/claims/groups": ["Moderators", "Editors"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCMultiGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -161,16 +185,22 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { """ XCTAssertEqual(document.name, "onCreateOIDCMultiGroupPost") XCTAssertEqual(document.stringValue, expectedQueryDocument) - XCTAssertTrue(document.variables.isEmpty, - "variables should be empty since claim group value matches the auth rule schema") + XCTAssertTrue( + document.variables.isEmpty, + "variables should be empty since claim group value matches the auth rule schema" + ) } func testOnCreateSubscription_InDifferentAppWithAdminsFromMyApp() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://myapp.com/claims/groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCMultiGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://myapp.com/claims/groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCMultiGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -186,16 +216,22 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { """ XCTAssertEqual(document.name, "onCreateOIDCMultiGroupPost") XCTAssertEqual(document.stringValue, expectedQueryDocument) - XCTAssertTrue(document.variables.isEmpty, - "variables should be empty since claim group value matches the auth rule schema") + XCTAssertTrue( + document.variables.isEmpty, + "variables should be empty since claim group value matches the auth rule schema" + ) } func testOnCreateSubscription_InAdminsGroupInDifferentClaim() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://differentapp.com/claims/groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCMultiGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://differentapp.com/claims/groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCMultiGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -215,17 +251,23 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { XCTFail("The document doesn't contain variables") return } - XCTAssertEqual(variables["owner"] as? String, - "123e4567-dead-beef-a456-426614174000", - "owner should exist since `Admins` is part of myapp.com, not differntapp.com") + XCTAssertEqual( + variables["owner"] as? String, + "123e4567-dead-beef-a456-426614174000", + "owner should exist since `Admins` is part of myapp.com, not differntapp.com" + ) } func testOnCreateSubscription_InGroupButNotInSchema() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "https://differentapp.com/claims/groups": ["Users"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelType: OIDCMultiGroupPost.self, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "https://differentapp.com/claims/groups": ["Users"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelType: OIDCMultiGroupPost.self, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -245,8 +287,10 @@ class ModelWithOwnerAuthAndMultiGroup: XCTestCase { XCTFail("The document doesn't contain variables") return } - XCTAssertEqual(variables["owner"] as? String, - "123e4567-dead-beef-a456-426614174000", - "owner should exist since `Users` is not part of differentapp.com") + XCTAssertEqual( + variables["owner"] as? String, + "123e4567-dead-beef-a456-426614174000", + "owner should exist since `Users` is not part of differentapp.com" + ) } } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerFieldAuthRuleTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerFieldAuthRuleTests.swift index 7e0856eced..7967b8e730 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerFieldAuthRuleTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/AuthRuleDecorator/ModelWithOwnerFieldAuthRuleTests.swift @@ -24,8 +24,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // Since the owner field already exists on the model, ensure that it is not added again func testModelWithOwnerField_CreateMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -46,8 +48,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // Since the owner field already exists on the model, ensure that it is not added again func testModelWithOwnerField_DeleteMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -68,8 +72,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // Since the owner field already exists on the model, ensure that it is not added again func testModelWithOwnerField_UpdateMutation() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: AuthRuleDecorator(.mutation)) let document = documentBuilder.build() @@ -90,8 +96,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // Since the owner field already exists on the model, ensure that it is not added again func testModelWithOwnerField_GetQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: AuthRuleDecorator(.query)) let document = documentBuilder.build() @@ -112,8 +120,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // Since the owner field already exists on the model, ensure that it is not added again func testModelWithOwnerField_ListQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: AuthRuleDecorator(.query)) @@ -136,8 +146,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { } func testModelWithOwnerField_SyncQuery() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) documentBuilder.add(decorator: PaginationDecorator()) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .query)) @@ -166,10 +178,14 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // The owner auth rule contains `.create` operation, requiring the subscription operation to contain the input func testModelWithOwnerField_OnCreateSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) let document = documentBuilder.build() @@ -194,10 +210,14 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // The owner auth rule contains `.update` operation, requiring the subscription operation to contain the input func testModelWithOwnerField_OnUpdateSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onUpdate, claims))) let document = documentBuilder.build() @@ -222,10 +242,14 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { // The owner auth rule contains `.delete` operation, requiring the subscription operation to contain the input func testModelWithOwnerField_OnDeleteSubscription() { - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOwnerField.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOwnerField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, claims))) let document = documentBuilder.build() @@ -249,8 +273,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { } func testModelWithMultipleAuthRules_Subscription() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithMultipleAuthRules.schema, - operationType: .subscription) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithMultipleAuthRules.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, nil))) let document = documentBuilder.build() @@ -269,11 +295,15 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { } func testModelWithMultipleAuthRulesAPIKey_Subscription() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithMultipleAuthRules.schema, - operationType: .subscription) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithMultipleAuthRules.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) - documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, nil), - authType: .apiKey)) + documentBuilder.add(decorator: AuthRuleDecorator( + .subscription(.onCreate, nil), + authType: .apiKey + )) let document = documentBuilder.build() let expectedQueryDocument = """ subscription OnCreateModelWithMultipleAuthRules { @@ -290,8 +320,10 @@ class ModelWithOwnerFieldAuthRuleTests: XCTestCase { } func testModelWithOIDCOwner_Subscription() { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: ModelWithOIDCOwnerField.schema, - operationType: .subscription) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: ModelWithOIDCOwnerField.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, nil))) let document = documentBuilder.build() @@ -326,9 +358,11 @@ public struct ModelWithOwnerField: Model { public let id: String public var content: String public var author: String? - public init(id: String = UUID().uuidString, - content: String, - author: String?) { + public init( + id: String = UUID().uuidString, + content: String, + author: String? + ) { self.id = id self.content = content self.author = author @@ -348,7 +382,8 @@ public struct ModelWithOwnerField: Model { model.fields( .id(), .field(modelWithOwnerField.content, is: .required, ofType: .string), - .field(modelWithOwnerField.author, is: .optional, ofType: .string)) + .field(modelWithOwnerField.author, is: .optional, ofType: .string) + ) } } @@ -366,9 +401,11 @@ public struct ModelWithOIDCOwnerField: Model { public let id: String public var content: String public var author: String? - public init(id: String = UUID().uuidString, - content: String, - author: String?) { + public init( + id: String = UUID().uuidString, + content: String, + author: String? + ) { self.id = id self.content = content self.author = author @@ -388,7 +425,8 @@ public struct ModelWithOIDCOwnerField: Model { model.fields( .id(), .field(modelWithOwnerField.content, is: .required, ofType: .string), - .field(modelWithOwnerField.author, is: .optional, ofType: .string)) + .field(modelWithOwnerField.author, is: .optional, ofType: .string) + ) } } @@ -412,9 +450,11 @@ public struct ModelWithMultipleAuthRules: Model { public let id: String public var content: String public var author: String? - public init(id: String = UUID().uuidString, - content: String, - author: String?) { + public init( + id: String = UUID().uuidString, + content: String, + author: String? + ) { self.id = id self.content = content self.author = author @@ -435,6 +475,7 @@ public struct ModelWithMultipleAuthRules: Model { model.fields( .id(), .field(modelWithMultipleAuthRules.content, is: .required, ofType: .string), - .field(modelWithMultipleAuthRules.author, is: .optional, ofType: .string)) + .field(modelWithMultipleAuthRules.author, is: .optional, ofType: .string) + ) } } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/IncludeAssociationDecoratorTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/IncludeAssociationDecoratorTests.swift index a2098a2a69..ca9c861d4d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/IncludeAssociationDecoratorTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Decorator/IncludeAssociationDecoratorTests.swift @@ -37,9 +37,11 @@ class IncludeAssociationDecoratorTests: XCTestCase { for modelType: M.Type, includes includedAssociations: IncludedAssociations = { _ in [] } ) -> String { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .query, - primaryKeysOnly: true) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .query, + primaryKeysOnly: true + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .list)) guard let modelPath = modelType.rootPath as? ModelPath else { XCTFail("Model path for \(modelType.modelName) not found. Make sure it was defined for the model") diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLCreateMutationTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLCreateMutationTests.swift index f528dfb1c0..777427dfb7 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLCreateMutationTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLCreateMutationTests.swift @@ -33,10 +33,12 @@ class GraphQLCreateMutationTests: XCTestCase { /// - it contains an `input` of type `CreatePostInput` /// - it has a list of fields with no nested models func testCreateGraphQLMutationFromSimpleModel() { - let post = Post(title: "title", - content: "content", - createdAt: .now(), - status: .private) + let post = Post( + title: "title", + content: "content", + createdAt: .now(), + status: .private + ) var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Post.schema, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: ModelDecorator(model: post, mutationType: .create)) @@ -118,7 +120,7 @@ class GraphQLCreateMutationTests: XCTestCase { } XCTAssertEqual(input["commentPostId"] as? String, post.id) } - + /// - Given: a `Model` instance /// - When: /// - the model is of type `Comment` @@ -276,7 +278,7 @@ class GraphQLCreateMutationTests: XCTestCase { } XCTAssertEqual(input["commentPostId"] as? String, post.id) } - + /// - Given: a `Model` instance /// - When: /// - the model is of type `Comment` @@ -341,8 +343,10 @@ class GraphQLCreateMutationTests: XCTestCase { func testCreateGraphQLMutationFromModelWithReadonlyFields() { let recordCover = RecordCover(artist: "artist") let record = Record(name: "name", description: "description", cover: recordCover) - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Record.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: Record.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: ModelDecorator(model: record, mutationType: .create)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .mutation)) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLDeleteMutationTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLDeleteMutationTests.swift index 8cacb82de6..71de7ba07d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLDeleteMutationTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLDeleteMutationTests.swift @@ -122,8 +122,10 @@ class GraphQLDeleteMutationTests: XCTestCase { func testDeleteGraphQLMutationModelWithReadOnlyFields() { let recordCover = RecordCover(artist: "artist") let record = Record(name: "name", description: "description", cover: recordCover) - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Record.schema, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: Record.schema, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: ModelDecorator(model: record, mutationType: .create)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .mutation)) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLGetQueryTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLGetQueryTests.swift index fb753b4c60..3c1e17ae14 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLGetQueryTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLGetQueryTests.swift @@ -129,7 +129,7 @@ class GraphQLGetQueryTests: XCTestCase { } XCTAssertEqual(variables["id"] as? String, "id") } - + /// - Given: a `Model` type /// - When: /// - the model is of type `Comment` @@ -208,7 +208,7 @@ class GraphQLGetQueryTests: XCTestCase { } XCTAssertEqual(variables["id"] as? String, "id") } - + func testGetGraphQLQueryFromModelWithAssociationAndSyncEnabled() { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Comment.schema, operationType: .query, primaryKeysOnly: false) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLListQueryTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLDocument/GraphQLListQueryTests.swift index 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 5b2e3f60eb..f23e5bd2fc 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeJSONTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeJSONTests.swift @@ -16,48 +16,76 @@ class GraphQLRequestEmbeddableTypeJSONTests: XCTestCase { override func setUp() { let sectionName = ModelField(name: "name", type: .string, isRequired: true) let sectionNumber = ModelField(name: "number", type: .double, isRequired: true) - let sectionSchema = ModelSchema(name: "Section", - fields: [sectionName.name: sectionName, - sectionNumber.name: sectionNumber]) + let sectionSchema = ModelSchema( + name: "Section", + fields: [ + sectionName.name: sectionName, + sectionNumber.name: sectionNumber + ] + ) let colorName = ModelField(name: "name", type: .string, isRequired: true) let colorR = ModelField(name: "red", type: .int, isRequired: true) let colorG = ModelField(name: "green", type: .int, isRequired: true) let colorB = ModelField(name: "blue", type: .int, isRequired: true) - let colorSchema = ModelSchema(name: "Color", listPluralName: "Colors", syncPluralName: "Colors", - fields: [colorName.name: colorName, - colorR.name: colorR, - colorG.name: colorG, - colorB.name: colorB]) + let colorSchema = ModelSchema( + name: "Color", + listPluralName: "Colors", + syncPluralName: "Colors", + fields: [ + colorName.name: colorName, + colorR.name: colorR, + colorG.name: colorG, + colorB.name: colorB + ] + ) let categoryName = ModelField(name: "name", type: .string, isRequired: true) - let categoryColor = ModelField(name: "color", - type: .embeddedCollection(of: DynamicEmbedded.self, schema: colorSchema), - isRequired: true) - let categorySchema = ModelSchema(name: "Category", listPluralName: "Categories", syncPluralName: "Categories", - fields: [categoryName.name: categoryName, - categoryColor.name: categoryColor]) + let categoryColor = ModelField( + name: "color", + type: .embeddedCollection(of: DynamicEmbedded.self, schema: colorSchema), + isRequired: true + ) + let categorySchema = ModelSchema( + name: "Category", + listPluralName: "Categories", + syncPluralName: "Categories", + fields: [ + categoryName.name: categoryName, + categoryColor.name: categoryColor + ] + ) let todoId = ModelFieldDefinition.id("id").modelField let todoName = ModelField(name: "name", type: .string, isRequired: true) let todoDescription = ModelField(name: "description", type: .string) - let todoCategories = ModelField(name: "categories", - type: .embeddedCollection(of: DynamicEmbedded.self, schema: categorySchema)) - let todoSection = ModelField(name: "section", - type: .embedded(type: DynamicEmbedded.self, schema: sectionSchema)) + let todoCategories = ModelField( + name: "categories", + type: .embeddedCollection(of: DynamicEmbedded.self, schema: categorySchema) + ) + let todoSection = ModelField( + name: "section", + type: .embedded(type: DynamicEmbedded.self, schema: sectionSchema) + ) let todoStickies = ModelField(name: "stickies", type: .embedded(type: String.self)) - let todoSchema = ModelSchema(name: "Todo", - listPluralName: "Todos", - syncPluralName: "Todos", - fields: [todoId.name: todoId, - todoName.name: todoName, - todoDescription.name: todoDescription, - todoCategories.name: todoCategories, - todoSection.name: todoSection, - todoStickies.name: todoStickies]) + let todoSchema = ModelSchema( + name: "Todo", + listPluralName: "Todos", + syncPluralName: "Todos", + fields: [ + todoId.name: todoId, + todoName.name: todoName, + todoDescription.name: todoDescription, + todoCategories.name: todoCategories, + todoSection.name: todoSection, + todoStickies.name: todoStickies + ] + ) - ModelRegistry.register(modelType: DynamicModel.self, - modelSchema: todoSchema) { (_, _) -> Model in + ModelRegistry.register( + modelType: DynamicModel.self, + modelSchema: todoSchema + ) { _, _ -> Model in return DynamicModel(id: "1", map: [:]) } } @@ -67,24 +95,30 @@ class GraphQLRequestEmbeddableTypeJSONTests: XCTestCase { } func testCreateTodoGraphQLRequest() { - let color1 = ["name": JSONValue.string("color1"), - "red": JSONValue.number(1), - "green": JSONValue.number(2), - "blue": JSONValue.number(3)] - let color2 = ["name": JSONValue.string("color1"), - "red": JSONValue.number(12), - "green": JSONValue.number(13), - "blue": JSONValue.number(14)] + let color1 = [ + "name": JSONValue.string("color1"), + "red": JSONValue.number(1), + "green": JSONValue.number(2), + "blue": JSONValue.number(3) + ] + let color2 = [ + "name": JSONValue.string("color1"), + "red": JSONValue.number(12), + "green": JSONValue.number(13), + "blue": JSONValue.number(14) + ] let category1 = ["name": JSONValue.string("green"), "color": JSONValue.object(color1)] let category2 = ["name": JSONValue.string("red"), "color": JSONValue.object(color2)] let section = ["name": JSONValue.string("section"), "number": JSONValue.number(1.1)] - let todo = ["name": JSONValue.string("my first todo"), - "description": JSONValue.string("todo description"), - "categories": JSONValue.array([JSONValue.object(category1), JSONValue.object(category2)]), - "section": JSONValue.object(section)] + let todo = [ + "name": JSONValue.string("my first todo"), + "description": JSONValue.string("todo description"), + "categories": JSONValue.array([JSONValue.object(category1), JSONValue.object(category2)]), + "section": JSONValue.object(section) + ] let todoModel = DynamicModel(map: todo) let documentStringValue = """ diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeTests.swift index b974ea1c79..9ee63921bf 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestEmbeddableTypeTests.swift @@ -27,10 +27,12 @@ class GraphQLRequestEmbeddableTypeTests: XCTestCase { let category1 = Category(name: "green", color: color1) let category2 = Category(name: "red", color: color2) let section = Section(name: "section", number: 1.1) - let todo = Todo(name: "my first todo", - description: "todo description", - categories: [category1, category2], - section: section) + let todo = Todo( + name: "my first todo", + description: "todo description", + categories: [category1, category2], + section: section + ) let documentStringValue = """ mutation CreateTodo($input: CreateTodoInput!) { createTodo(input: $input) { @@ -76,68 +78,116 @@ class GraphQLRequestEmbeddableTypeTests: XCTestCase { class GraphQLRequestJSONNonModelTests: XCTestCase { override func setUp() { - let sectionName = ModelField(name: "name", - type: .string, - isRequired: true) - let sectionNumber = ModelField(name: "number", - type: .double, - isRequired: true) - let sectionSchema = ModelSchema(name: "Section", - fields: [sectionName.name: sectionName, - sectionNumber.name: sectionNumber]) - - let colorName = ModelField(name: "name", - type: .string, - isRequired: true) - let colorR = ModelField(name: "red", - type: .int, - isRequired: true) - let colorG = ModelField(name: "green", - type: .int, - isRequired: true) - let colorB = ModelField(name: "blue", - type: .int, - isRequired: true) - let colorSchema = ModelSchema(name: "Color", listPluralName: "Colors", syncPluralName: "Colors", - fields: [colorName.name: colorName, - colorR.name: colorR, - colorG.name: colorG, - colorB.name: colorB]) - - let categoryName = ModelField(name: "name", - type: .string, - isRequired: true) - let categoryColor = ModelField(name: "color", - type: .embeddedCollection(of: DynamicEmbedded.self, schema: colorSchema), - isRequired: true) - let categorySchema = ModelSchema(name: "Category", listPluralName: "Categories", syncPluralName: "Categories", - fields: [categoryName.name: categoryName, - categoryColor.name: categoryColor]) + let sectionName = ModelField( + name: "name", + type: .string, + isRequired: true + ) + let sectionNumber = ModelField( + name: "number", + type: .double, + isRequired: true + ) + let sectionSchema = ModelSchema( + name: "Section", + fields: [ + sectionName.name: sectionName, + sectionNumber.name: sectionNumber + ] + ) + + let colorName = ModelField( + name: "name", + type: .string, + isRequired: true + ) + let colorR = ModelField( + name: "red", + type: .int, + isRequired: true + ) + let colorG = ModelField( + name: "green", + type: .int, + isRequired: true + ) + let colorB = ModelField( + name: "blue", + type: .int, + isRequired: true + ) + let colorSchema = ModelSchema( + name: "Color", + listPluralName: "Colors", + syncPluralName: "Colors", + fields: [ + colorName.name: colorName, + colorR.name: colorR, + colorG.name: colorG, + colorB.name: colorB + ] + ) + + let categoryName = ModelField( + name: "name", + type: .string, + isRequired: true + ) + let categoryColor = ModelField( + name: "color", + type: .embeddedCollection(of: DynamicEmbedded.self, schema: colorSchema), + isRequired: true + ) + let categorySchema = ModelSchema( + name: "Category", + listPluralName: "Categories", + syncPluralName: "Categories", + fields: [ + categoryName.name: categoryName, + categoryColor.name: categoryColor + ] + ) let todoId = ModelFieldDefinition.id("id").modelField - let todoName = ModelField(name: "name", - type: .string, - isRequired: true) - let todoDescription = ModelField(name: "description", - type: .string) - let todoCategories = ModelField(name: "categories", - type: .embeddedCollection(of: DynamicEmbedded.self, schema: categorySchema)) - let todoSection = ModelField(name: "section", - type: .embedded(type: DynamicEmbedded.self, schema: sectionSchema)) - let todoStickies = ModelField(name: "stickies", - type: .embedded(type: String.self)) - let todoSchema = ModelSchema(name: "Todo", - listPluralName: "Todos", - syncPluralName: "Todos", - fields: [todoId.name: todoId, - todoName.name: todoName, - todoDescription.name: todoDescription, - todoCategories.name: todoCategories, - todoSection.name: todoSection, - todoStickies.name: todoStickies]) - - ModelRegistry.register(modelType: DynamicModel.self, - modelSchema: todoSchema) { (_, _) -> Model in + let todoName = ModelField( + name: "name", + type: .string, + isRequired: true + ) + let todoDescription = ModelField( + name: "description", + type: .string + ) + let todoCategories = ModelField( + name: "categories", + type: .embeddedCollection(of: DynamicEmbedded.self, schema: categorySchema) + ) + let todoSection = ModelField( + name: "section", + type: .embedded(type: DynamicEmbedded.self, schema: sectionSchema) + ) + let todoStickies = ModelField( + name: "stickies", + type: .embedded(type: String.self) + ) + let todoSchema = ModelSchema( + name: "Todo", + listPluralName: "Todos", + syncPluralName: "Todos", + fields: [ + todoId.name: todoId, + todoName.name: todoName, + todoDescription.name: todoDescription, + todoCategories.name: todoCategories, + todoSection.name: todoSection, + todoStickies.name: todoStickies + ] + ) + + ModelRegistry.register( + modelType: DynamicModel.self, + modelSchema: todoSchema + ) { _, _ -> Model in return DynamicModel(id: "1", map: [:]) } } @@ -147,24 +197,30 @@ class GraphQLRequestJSONNonModelTests: XCTestCase { } func testCreateTodoGraphQLRequest() { - let color1 = ["name": JSONValue.string("color1"), - "red": JSONValue.number(1), - "green": JSONValue.number(2), - "blue": JSONValue.number(3)] - let color2 = ["name": JSONValue.string("color1"), - "red": JSONValue.number(12), - "green": JSONValue.number(13), - "blue": JSONValue.number(14)] + let color1 = [ + "name": JSONValue.string("color1"), + "red": JSONValue.number(1), + "green": JSONValue.number(2), + "blue": JSONValue.number(3) + ] + let color2 = [ + "name": JSONValue.string("color1"), + "red": JSONValue.number(12), + "green": JSONValue.number(13), + "blue": JSONValue.number(14) + ] let category1 = ["name": JSONValue.string("green"), "color": JSONValue.object(color1)] let category2 = ["name": JSONValue.string("red"), "color": JSONValue.object(color2)] let section = ["name": JSONValue.string("section"), "number": JSONValue.number(1.1)] - let todo = ["name": JSONValue.string("my first todo"), - "description": JSONValue.string("todo description"), - "categories": JSONValue.array([JSONValue.object(category1), JSONValue.object(category2)]), - "section": JSONValue.object(section)] + let todo = [ + "name": JSONValue.string("my first todo"), + "description": JSONValue.string("todo description"), + "categories": JSONValue.array([JSONValue.object(category1), JSONValue.object(category2)]), + "section": JSONValue.object(section) + ] let todoModel = DynamicModel(map: todo) let documentStringValue = """ diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOptionalAssociationTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOptionalAssociationTests.swift index f5155e6adb..e5c80d604d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOptionalAssociationTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOptionalAssociationTests.swift @@ -48,7 +48,7 @@ class GraphQLRequestOptionalAssociationTests: XCTestCase { XCTAssertEqual(input["name"] as? String, user.name) } - + func testCreateUserFollowingGraphQLRequest() { let user1 = User(name: "user1") let user2 = User(name: "user2") diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOwnerAndGroupTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOwnerAndGroupTests.swift index 581e744dc3..17b1faff10 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOwnerAndGroupTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestOwnerAndGroupTests.swift @@ -25,11 +25,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnCreateSubscriptionScenarioBInAdmins() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) @@ -48,9 +52,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -59,11 +65,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnUpdateSubscriptionScenarioBInAdmins() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onUpdate, claims))) @@ -82,9 +92,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onUpdate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onUpdate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -93,11 +105,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnDeleteSubscriptionScenarioBInAdmins() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, claims))) @@ -116,9 +132,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onDelete, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onDelete, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -127,11 +145,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnCreateSubscriptionScenarioBInAdminsAndAnotherGroup() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["Admins", "GroupX"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["Admins", "GroupX"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) @@ -150,9 +172,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -161,11 +185,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnCreateSubscriptionScenarioBNotInAdmins() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["GroupX"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["GroupX"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) @@ -184,9 +212,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -203,11 +233,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnUpdateSubscriptionScenarioBNotInAdmins() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["GroupX"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["GroupX"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onUpdate, claims))) @@ -226,9 +260,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onUpdate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onUpdate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -245,11 +281,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnDeleteSubscriptionScenarioBNotInAdmins() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["GroupX"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["GroupX"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, claims))) @@ -268,9 +308,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onDelete, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onDelete, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -287,12 +329,16 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnDeleteSubscriptionScenarioBNoGroupClaim() { let modelType = OGCScenarioBPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000"] as IdentityClaimsDictionary + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000" + ] as IdentityClaimsDictionary // Specifically, leave this out: // "cognito:groups": ["GroupX"]] - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onDelete, claims))) @@ -311,9 +357,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onDelete, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onDelete, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -330,11 +378,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnCreateSubscriptionScenarioBMGroupInAdmins() { let modelType = OGCScenarioBMGroupPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["Admins"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["Admins"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) @@ -353,9 +405,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) @@ -364,11 +418,15 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { func testOnCreateSubscriptionScenarioBMGroupInAdminsAndAnotherGroup() { let modelType = OGCScenarioBMGroupPost.self as Model.Type - let claims = ["username": "user1", - "sub": "123e4567-dead-beef-a456-426614174000", - "cognito:groups": ["Admins", "GroupX"]] as IdentityClaimsDictionary - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, - operationType: .subscription) + let claims = [ + "username": "user1", + "sub": "123e4567-dead-beef-a456-426614174000", + "cognito:groups": ["Admins", "GroupX"] + ] as IdentityClaimsDictionary + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelSchema: modelType.schema, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) documentBuilder.add(decorator: AuthRuleDecorator(.subscription(.onCreate, claims))) @@ -387,9 +445,11 @@ class GraphQLRequestOwnerAndGroupTests: XCTestCase { } } """ - let request = GraphQLRequest.subscription(to: modelType.schema, - subscriptionType: .onCreate, - claims: claims) + let request = GraphQLRequest.subscription( + to: modelType.schema, + subscriptionType: .onCreate, + claims: claims + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyTests.swift index 3ed2d970fe..c4dd31205a 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyTests.swift @@ -22,8 +22,10 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { func testQueryGraphQLRequest() throws { let order = CustomerOrder(orderId: "testOrderId", email: "testEmail@provider.com") - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: order.modelName, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: order.modelName, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: ModelIdDecorator(id: order.id, fields: ["orderId": "testOrderId"])) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .query)) @@ -44,10 +46,12 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { XCTAssertEqual(document.stringValue, documentStringValue) - let request = GraphQLRequest(document: document.stringValue, - variables: document.variables, - responseType: MutationSyncResult.self, - decodePath: document.name) + let request = GraphQLRequest( + document: document.stringValue, + variables: document.variables, + responseType: MutationSyncResult.self, + decodePath: document.name + ) XCTAssertEqual(request.document, document.stringValue) XCTAssert(request.responseType == MutationSyncResult.self) @@ -61,8 +65,10 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { func testCreateMutationGraphQLRequest() throws { let order = CustomerOrder(orderId: "testOrderId", email: "testEmail@provider.com") - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: order.modelName, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: order.modelName, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: ModelDecorator(model: order, mutationType: .create)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .mutation)) @@ -112,8 +118,10 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { func testUpdateMutationGraphQLRequest() throws { let order = CustomerOrder(orderId: "testOrderId", email: "testEmail@provider.com") - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: order.modelName, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: order.modelName, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: ModelDecorator(model: order, mutationType: .create)) documentBuilder.add(decorator: ConflictResolutionDecorator(version: 1, lastSync: nil, graphQLType: .mutation)) @@ -139,9 +147,11 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { return } - let request = GraphQLRequest.updateMutation(of: order, - modelSchema: order.schema, - version: 1) + let request = GraphQLRequest.updateMutation( + of: order, + modelSchema: order.schema, + version: 1 + ) XCTAssertEqual(request.document, document.stringValue) XCTAssert(request.responseType == MutationSyncResult.self) @@ -168,8 +178,10 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { func testDeleteMutationGraphQLRequest() throws { let order = CustomerOrder(orderId: "testOrderId", email: "testEmail@provider.com") - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: order.modelName, - operationType: .mutation) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: order.modelName, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: ModelIdDecorator(model: order)) documentBuilder.add(decorator: ConflictResolutionDecorator(version: 1, lastSync: nil, graphQLType: .mutation)) @@ -195,9 +207,11 @@ class GraphQLRequestSyncCustomPrimaryKeyTests: XCTestCase { return } - let request = GraphQLRequest.deleteMutation(of: order, - modelSchema: order.schema, - version: 1) + let request = GraphQLRequest.deleteMutation( + of: order, + modelSchema: order.schema, + version: 1 + ) XCTAssertEqual(request.document, document.stringValue) XCTAssert(request.responseType == MutationSyncResult.self) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests.swift index 694dcc8600..5b709c00ea 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests.swift @@ -22,16 +22,20 @@ class GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests: XCTestCase { } func testDeleteMutationGraphQLRequestWithDateInPK() throws { - let customer = CustomerWithMultipleFieldsinPK(dob: Temporal.DateTime.now(), - date: Temporal.Date.now(), - time: Temporal.Time.now(), - phoneNumber: 1_234_567, - priority: Priority.high, - height: 6.1, - firstName: "John", - lastName: "Doe") - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: customer.modelName, - operationType: .mutation) + let customer = CustomerWithMultipleFieldsinPK( + dob: Temporal.DateTime.now(), + date: Temporal.Date.now(), + time: Temporal.Time.now(), + phoneNumber: 1_234_567, + priority: Priority.high, + height: 6.1, + firstName: "John", + lastName: "Doe" + ) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: customer.modelName, + operationType: .mutation + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: ModelIdDecorator(model: customer)) documentBuilder.add(decorator: ConflictResolutionDecorator(version: 1, lastSync: nil, graphQLType: .mutation)) @@ -64,9 +68,11 @@ class GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests: XCTestCase { return } - let request = GraphQLRequest.deleteMutation(of: customer, - modelSchema: customer.schema, - version: 1) + let request = GraphQLRequest.deleteMutation( + of: customer, + modelSchema: customer.schema, + version: 1 + ) XCTAssertEqual(request.document, document.stringValue) XCTAssert(request.responseType == MutationSyncResult.self) @@ -100,8 +106,10 @@ class GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests: XCTestCase { } func testOnCreateSubscriptionGraphQLRequestWithDateInPK() throws { - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: CustomerWithMultipleFieldsinPK.modelName, - operationType: .subscription) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: CustomerWithMultipleFieldsinPK.modelName, + operationType: .subscription + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator(graphQLType: .subscription)) let document = documentBuilder.build() @@ -128,8 +136,10 @@ class GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests: XCTestCase { """ XCTAssertEqual(document.stringValue, documentStringValue) - let request = GraphQLRequest.subscription(to: CustomerWithMultipleFieldsinPK.self, - subscriptionType: .onCreate) + let request = GraphQLRequest.subscription( + to: CustomerWithMultipleFieldsinPK.self, + subscriptionType: .onCreate + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) } @@ -138,8 +148,10 @@ class GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests: XCTestCase { let nextToken = "nextToken" let limit = 100 let lastSync: Int64 = 123 - var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: CustomerWithMultipleFieldsinPK.modelName, - operationType: .query) + var documentBuilder = ModelBasedGraphQLDocumentBuilder( + modelName: CustomerWithMultipleFieldsinPK.modelName, + operationType: .query + ) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) documentBuilder.add(decorator: PaginationDecorator(limit: limit, nextToken: nextToken)) documentBuilder.add(decorator: ConflictResolutionDecorator(lastSync: lastSync, graphQLType: .query)) @@ -171,10 +183,12 @@ class GraphQLRequestSyncCustomPrimaryKeyWithMultipleFieldsTests: XCTestCase { """ XCTAssertEqual(document.stringValue, documentStringValue) - let request = GraphQLRequest.syncQuery(modelSchema: CustomerWithMultipleFieldsinPK.schema, - limit: limit, - nextToken: nextToken, - lastSync: lastSync) + let request = GraphQLRequest.syncQuery( + modelSchema: CustomerWithMultipleFieldsinPK.schema, + limit: limit, + nextToken: nextToken, + lastSync: lastSync + ) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/MockAWSAuthUser.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/MockAWSAuthUser.swift index 0c09bd927b..2eb1591ad3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/MockAWSAuthUser.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/GraphQLRequest/MockAWSAuthUser.swift @@ -6,6 +6,7 @@ // import Amplify + public struct MockAWSAuthUser: AuthUser { /// The username for the logged in user diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/AuthRuleExtensionTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/AuthRuleExtensionTests.swift index 7f284e404f..c73a14ea5c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/AuthRuleExtensionTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/AuthRuleExtensionTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify import AWSPluginsCore +import XCTest class AuthRuleExtensionTests: XCTestCase { func testAuthRuleProviderToAWSAuth() throws { diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelGraphQLTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelGraphQLTests.swift index 0a19109c59..e22e87f6ea 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelGraphQLTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelGraphQLTests.swift @@ -39,13 +39,15 @@ class ModelGraphQLTests: XCTestCase { func testPostModelToGraphQLInputSuccess() throws { let date: Temporal.DateTime = .now() let status = PostStatus.published - let post = Post(id: "id", - title: "title", - content: "content", - createdAt: date, - draft: true, - rating: 5.0, - status: status) + let post = Post( + id: "id", + title: "title", + content: "content", + createdAt: date, + draft: true, + rating: 5.0, + status: status + ) let graphQLInput = post.graphQLInputForMutation(Post.schema, mutationType: .update) @@ -63,10 +65,12 @@ class ModelGraphQLTests: XCTestCase { func testTodoModelToGraphQLInputSuccess() { let color = Color(name: "red", red: 255, green: 0, blue: 0) let category = Category(name: "green", color: color) - let todo = Todo(name: "name", - description: "description", - categories: [category], - stickies: ["stickie1"]) + let todo = Todo( + name: "name", + description: "description", + categories: [category], + stickies: ["stickie1"] + ) let graphQLInput = todo.graphQLInputForMutation(Todo.schema, mutationType: .create) @@ -175,22 +179,30 @@ class ModelGraphQLTests: XCTestCase { } func testModelWithAssociationAndCompositePrimaryKey() { - let owner = ModelCompositePkWithAssociation(id: "id2", - dob: Temporal.DateTime.now(), - name: "name") - let childModel = ModelCompositePkBelongsTo(id: "id1", - dob: Temporal.DateTime.now(), - name: "name", - owner: owner) + let owner = ModelCompositePkWithAssociation( + id: "id2", + dob: Temporal.DateTime.now(), + name: "name" + ) + let childModel = ModelCompositePkBelongsTo( + id: "id1", + dob: Temporal.DateTime.now(), + name: "name", + owner: owner + ) let graphQLInput = childModel.graphQLInputForMutation(childModel.schema, mutationType: .create) XCTAssertEqual(graphQLInput["id"] as? String, childModel.id) XCTAssertEqual(graphQLInput["dob"] as? String, childModel.dob.iso8601String) XCTAssertEqual(graphQLInput["name"] as? String, childModel.name) - XCTAssertEqual(graphQLInput["modelCompositePkWithAssociationOtherModelsId"] as? String, - owner.id) - XCTAssertEqual(graphQLInput["modelCompositePkWithAssociationOtherModelsDob"] as? Temporal.DateTime, - owner.dob) + XCTAssertEqual( + graphQLInput["modelCompositePkWithAssociationOtherModelsId"] as? String, + owner.id + ) + XCTAssertEqual( + graphQLInput["modelCompositePkWithAssociationOtherModelsDob"] as? Temporal.DateTime, + owner.dob + ) } func testModelWithHasManyAssociationAndCompositePrimaryKey() { @@ -206,9 +218,11 @@ class ModelGraphQLTests: XCTestCase { func testModelWithHasManyUnidirectionalAssociationAndCompositePrimaryKey() { let parent = PostWithCompositeKeyUnidirectional(title: "title") - let childModel = CommentWithCompositeKeyUnidirectional(content: "comment", - postWithCompositeKeyUnidirectionalCommentsId: parent.id, - postWithCompositeKeyUnidirectionalCommentsTitle: parent.title) + let childModel = CommentWithCompositeKeyUnidirectional( + content: "comment", + postWithCompositeKeyUnidirectionalCommentsId: parent.id, + postWithCompositeKeyUnidirectionalCommentsTitle: parent.title + ) let graphQLInput = childModel.graphQLInputForMutation(childModel.schema, mutationType: .create) XCTAssertEqual(graphQLInput["id"] as? String, childModel.id) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelSchemaGraphQLTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelSchemaGraphQLTests.swift index fd06d64025..47e7463da1 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelSchemaGraphQLTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/ModelSchemaGraphQLTests.swift @@ -29,8 +29,10 @@ class ModelSchemaGraphQLTests: XCTestCase { } func testGraphQLNameForWishWithPluralName() { - let wish = ModelSchema(name: "Wish", - pluralName: "Wishes") + let wish = ModelSchema( + name: "Wish", + pluralName: "Wishes" + ) XCTAssertEqual(wish.graphQLName(queryType: .get), "getWish") XCTAssertEqual(wish.graphQLName(queryType: .list), "listWishes") XCTAssertEqual(wish.graphQLName(queryType: .sync), "syncWishes") @@ -45,9 +47,11 @@ class ModelSchemaGraphQLTests: XCTestCase { } func testGraphQLNameForWishWithListPluralName() { - let wish = ModelSchema(name: "Wish", - listPluralName: "Wishes", - syncPluralName: "Wishes") + let wish = ModelSchema( + name: "Wish", + listPluralName: "Wishes", + syncPluralName: "Wishes" + ) XCTAssertEqual(wish.graphQLName(queryType: .get), "getWish") XCTAssertEqual(wish.graphQLName(queryType: .list), "listWishes") XCTAssertEqual(wish.graphQLName(queryType: .sync), "syncWishes") diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/QueryPredicateGraphQLTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/QueryPredicateGraphQLTests.swift index 2a699b0613..fd87c54ec6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/QueryPredicateGraphQLTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Model/Support/QueryPredicateGraphQLTests.swift @@ -264,9 +264,11 @@ class QueryPredicateGraphQLTests: XCTestCase { ] } """ - let result = try GraphQLFilterConverter.toJSON(predicate, - modelSchema: Comment4.schema, - options: [.prettyPrinted]) + let result = try GraphQLFilterConverter.toJSON( + predicate, + modelSchema: Comment4.schema, + options: [.prettyPrinted] + ) XCTAssertEqual(result, expected) } @@ -290,9 +292,11 @@ class QueryPredicateGraphQLTests: XCTestCase { ] } """ - let result = try GraphQLFilterConverter.toJSON(predicate, - modelSchema: Project2.schema, - options: [.prettyPrinted]) + let result = try GraphQLFilterConverter.toJSON( + predicate, + modelSchema: Project2.schema, + options: [.prettyPrinted] + ) XCTAssertEqual(result, expected) } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedBoolTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedBoolTests.swift index 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/QueryPredicateEvaluateGeneratedEnumTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedEnumTests.swift index c160885c40..8232761fb8 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedEnumTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedEnumTests.swift @@ -18,11 +18,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { func testEnumNotEqual_False() throws { let predicate = Post.keys.status.ne(PostStatus.published) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .published) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .published + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -31,11 +33,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { func testEnumNotEqual_True() throws { let predicate = Post.keys.status.ne(PostStatus.published) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .draft) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .draft + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -44,11 +48,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { func testEnumEquals_True() throws { let predicate = Post.keys.status.eq(PostStatus.published) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .published) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .published + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -57,11 +63,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { func testEnumEquals_False() throws { let predicate = Post.keys.status.eq(PostStatus.published) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .draft) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .draft + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -71,11 +79,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { /// Draft is not greater than published, evaluates to false func testEnumToStringGreaterThan_False() throws { let predicate = Post.keys.status.gt(PostStatus.published.rawValue) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .draft) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .draft + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -85,11 +95,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { /// Published is greater than draft, evaluates to true func testEnumToStringGreaterThan_True() throws { let predicate = Post.keys.status.gt(PostStatus.draft.rawValue) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .published) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .published + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -99,11 +111,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { /// Published is not less than draft, evalutates to false func testEnumToStringLessThan_False() throws { let predicate = Post.keys.status.lt(PostStatus.draft.rawValue) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .published) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .published + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) @@ -113,11 +127,13 @@ class QueryPredicateEvaluateGeneratedEnumTests: XCTestCase { /// Draft is less than publshed, evaluates to true func testEnumToStringLessThan_True() throws { let predicate = Post.keys.status.lt(PostStatus.published.rawValue) - let instance = Post(title: "title", - content: "content", - createdAt: .now(), - updatedAt: .now(), - status: .draft) + let instance = Post( + title: "title", + content: "content", + createdAt: .now(), + updatedAt: .now(), + status: .draft + ) let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedIntTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGeneratedIntTests.swift index 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..c8a74d2a40 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGenerator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateGenerator.swift @@ -203,7 +203,8 @@ class QueryPredicateGenerator: XCTestCase { func performGeneration(type1: String, type2: String, operation: String) -> Int { var count = 0 guard let values1 = typeToValuesMap[type1], - let values2 = typeToValuesMap[type2] else { + let values2 = typeToValuesMap[type2] + else { print("failed to find values map!") exit(1) } @@ -241,7 +242,8 @@ class QueryPredicateGenerator: XCTestCase { // handleBetween generates a test to check if v3 (value3) is between v1 and v2 func handleBetween(type1: String, val1: String, type2: String, val2: String, val3: String, operation: String) -> Bool { guard let oper = operationMap[operation], - let fieldName = fieldForType[type1] else { + let fieldName = fieldForType[type1] + else { print("Failed to look up operation") return false } @@ -287,20 +289,32 @@ class QueryPredicateGenerator: XCTestCase { print(" let timeNow = try Temporal.Time.init(iso8601String: \"10:16:44\")") } let v1LocalRef = val1 - .replacingOccurrences(of: "Temporal.DateTime.now()", - with: "dateTimeNow") - .replacingOccurrences(of: "Temporal.Time.now()", - with: "timeNow") + .replacingOccurrences( + of: "Temporal.DateTime.now()", + with: "dateTimeNow" + ) + .replacingOccurrences( + of: "Temporal.Time.now()", + with: "timeNow" + ) let v2LocalRef = val2 - .replacingOccurrences(of: "Temporal.DateTime.now()", - with: "dateTimeNow") - .replacingOccurrences(of: "Temporal.Time.now()", - with: "timeNow") + .replacingOccurrences( + of: "Temporal.DateTime.now()", + with: "dateTimeNow" + ) + .replacingOccurrences( + of: "Temporal.Time.now()", + with: "timeNow" + ) let v3LocalRef = val3 - .replacingOccurrences(of: "Temporal.DateTime.now()", - with: "dateTimeNow") - .replacingOccurrences(of: "Temporal.Time.now()", - with: "timeNow") + .replacingOccurrences( + of: "Temporal.DateTime.now()", + with: "dateTimeNow" + ) + .replacingOccurrences( + of: "Temporal.Time.now()", + with: "timeNow" + ) print(" let predicate = QPredGen.keys.\(fieldName).\(oper)(start: \(v1LocalRef), end: \(v2LocalRef))") if val3 != "" { @@ -338,7 +352,8 @@ class QueryPredicateGenerator: XCTestCase { func handleOtherOperations(type1: String, val1: String, type2: String, val2: String, operation: String) -> Bool { guard let oper = operationMap[operation], - let fieldName = fieldForType[type1] else { + let fieldName = fieldForType[type1] + else { print("Failed to look up operation") return false } @@ -371,15 +386,23 @@ class QueryPredicateGenerator: XCTestCase { print(" let timeNow = try Temporal.Time.init(iso8601String: \"10:16:44\")") } let v1LocalRef = val1 - .replacingOccurrences(of: "Temporal.DateTime.now()", - with: "dateTimeNow") - .replacingOccurrences(of: "Temporal.Time.now()", - with: "timeNow") + .replacingOccurrences( + of: "Temporal.DateTime.now()", + with: "dateTimeNow" + ) + .replacingOccurrences( + of: "Temporal.Time.now()", + with: "timeNow" + ) let v2LocalRef = val2 - .replacingOccurrences(of: "Temporal.DateTime.now()", - with: "dateTimeNow") - .replacingOccurrences(of: "Temporal.Time.now()", - with: "timeNow") + .replacingOccurrences( + of: "Temporal.DateTime.now()", + with: "dateTimeNow" + ) + .replacingOccurrences( + of: "Temporal.Time.now()", + with: "timeNow" + ) print(" let predicate = QPredGen.keys.\(fieldName).\(oper)(\(v1LocalRef))") @@ -393,9 +416,13 @@ class QueryPredicateGenerator: XCTestCase { print(" let evaluation = try predicate.evaluate(target: instance.eraseToAnyModel().instance)") print("") - if attemptToResolve(type1, - val1.replacingOccurrences(of: "\"", with: ""), type2, - val2.replacingOccurrences(of: "\"", with: ""), oper) { + if attemptToResolve( + type1, + val1.replacingOccurrences(of: "\"", with: ""), + type2, + val2.replacingOccurrences(of: "\"", with: ""), + oper + ) { print(" XCTAssert(evaluation)") } else { print(" XCTAssertFalse(evaluation)") @@ -405,9 +432,13 @@ class QueryPredicateGenerator: XCTestCase { return true } - func attemptToResolve(_ type1: String, _ val1: String, - _ type2: String, _ val2: String, - _ operation: String) -> Bool { + func attemptToResolve( + _ type1: String, + _ val1: String, + _ type2: String, + _ val2: String, + _ operation: String + ) -> Bool { if val2 == "" { return false } @@ -427,9 +458,11 @@ class QueryPredicateGenerator: XCTestCase { return false } - func attemptToResolveStringBool(_ val1: String, - _ val2: String, - _ operation: String) -> Bool { + func attemptToResolveStringBool( + _ val1: String, + _ val2: String, + _ operation: String + ) -> Bool { let rhs = val1 let lhs = val2 switch operation { @@ -455,11 +488,16 @@ class QueryPredicateGenerator: XCTestCase { } } - func attemptToResolveNumeric(_ type1: String, _ sv1: String, - _ type2: String, _ sv2: String, - _ operation: String) -> Bool { + func attemptToResolveNumeric( + _ type1: String, + _ sv1: String, + _ type2: String, + _ sv2: String, + _ operation: String + ) -> Bool { guard let val1 = Double(sv1), - let val2 = Double(sv2) else { + let val2 = Double(sv2) + else { print("FAILED attemptToResolveNumeric") return false } @@ -487,9 +525,13 @@ class QueryPredicateGenerator: XCTestCase { } } - func attemptToResolveTemporal(_ type1: String, _ sv1: String, - _ type2: String, _ sv2: String, - _ operation: String) -> Bool { + func attemptToResolveTemporal( + _ type1: String, + _ sv1: String, + _ type2: String, + _ sv2: String, + _ operation: String + ) -> Bool { // Use built-in Date to determine the assert logic let val1 = temporalToTimeMap[sv1]! let val2 = temporalToTimeMap[sv2]! @@ -515,9 +557,13 @@ class QueryPredicateGenerator: XCTestCase { } } - func attemptToResolveBetweenTemporal(_ st1: String, _ sv1: String, - _ st2: String, _ sv2: String, - _ sv3: String) -> Bool { + func attemptToResolveBetweenTemporal( + _ st1: String, + _ sv1: String, + _ st2: String, + _ sv2: String, + _ sv3: String + ) -> Bool { if sv3 == "" { return false } @@ -528,16 +574,19 @@ class QueryPredicateGenerator: XCTestCase { return val1 <= val3 && val2 >= val3 } - func attemptToResolveBetweenDouble(_ sv1: String, - _ sv2: String, - _ sv3: String) -> Bool { + func attemptToResolveBetweenDouble( + _ sv1: String, + _ sv2: String, + _ sv3: String + ) -> Bool { if sv3 == "" { return false } guard let val1 = Double(sv1), let val2 = Double(sv2), - let val3 = Double(sv3) else { + let val3 = Double(sv3) + else { print("FAILED DOUBLE!") return false } @@ -545,9 +594,11 @@ class QueryPredicateGenerator: XCTestCase { } - func attemptToResolveBetweenString(_ sv1: String, - _ sv2: String, - _ sv3: String) -> Bool { + func attemptToResolveBetweenString( + _ sv1: String, + _ sv2: String, + _ sv3: String + ) -> Bool { return sv1 <= sv3 && sv2 >= sv3 } } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateTests.swift index b897e1c1f0..5a5bd5e436 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Query/QueryPredicateEvaluateTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon + class QueryPredicateEvaluateTests: XCTestCase { override func setUp() { ModelRegistry.register(modelType: QPredGen.self) diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/LocalWebSocketServer.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/LocalWebSocketServer.swift index 1dc0fbd948..cea249064b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/LocalWebSocketServer.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/LocalWebSocketServer.swift @@ -5,12 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation import Network class LocalWebSocketServer { - let portNumber = UInt16.random(in: 49152..<65535) + let portNumber = UInt16.random(in: 49_152 ..< 65_535) var connections = [NWConnection]() var listener: NWListener? @@ -78,7 +77,6 @@ class LocalWebSocketServer { print("Socket in waiting state with error: \(error)") @unknown default: print("Socket in unkown state -> \(state)") - break } } @@ -88,14 +86,14 @@ class LocalWebSocketServer { } func stop() { - self.listener?.cancel() + listener?.cancel() } func sendTransientFailureToConnections() { - self.connections.forEach { + for connection in connections { var metadata = NWProtocolWebSocket.Metadata(opcode: .close) metadata.closeCode = .protocolCode(NWProtocolWebSocket.CloseCode.Defined.internalServerError) - $0.send( + connection.send( content: nil, contentContext: NWConnection.ContentContext(identifier: "WebSocket", metadata: [metadata]), completion: .idempotent diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/RetryWithJitterTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/RetryWithJitterTests.swift index 9ada954056..24d07abf2d 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/RetryWithJitterTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/RetryWithJitterTests.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import XCTest @testable @_spi(WebSocket) import AWSPluginsCore @@ -17,8 +16,8 @@ class RetryWithJitterTests: XCTestCase { func testNext_returnDistinctValues() async { let retryWithJitter = RetryWithJitter() var values = Set() - for _ in 0..<20 { - values.insert(await retryWithJitter.next()) + for _ in 0 ..< 20 { + await values.insert(retryWithJitter.next()) } XCTAssert(values.count > 10) } @@ -27,8 +26,8 @@ class RetryWithJitterTests: XCTestCase { let max: UInt = 100_000 let retryWithJitter = RetryWithJitter(max: max) var values = Set() - for _ in 0..<50 { - values.insert(await retryWithJitter.next()) + for _ in 0 ..< 50 { + await values.insert(retryWithJitter.next()) } XCTAssert(values.allSatisfy { $0 < max}) } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/WebSocketClientTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/WebSocket/WebSocketClientTests.swift index 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..a72f1de3fb 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 { @@ -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 abeb670efb..07ba6bcb50 100644 --- a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift +++ b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift @@ -5,18 +5,20 @@ // 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? { + 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/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/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/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..3c842ac3fd 100644 --- a/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSSignatureV4Signer.swift +++ b/AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSSignatureV4Signer.swift @@ -5,53 +5,61 @@ // 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, - 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, 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..0f2ba244cc 100644 --- a/AmplifyPlugins/Core/AmplifyCredentialsTests/Auth/AWSAuthServiceTests.swift +++ b/AmplifyPlugins/Core/AmplifyCredentialsTests/Auth/AWSAuthServiceTests.swift @@ -7,10 +7,10 @@ import XCTest +import AWSClientRuntime @testable import Amplify @testable import AWSPluginsCore @testable import InternalAmplifyCredentials -import AWSClientRuntime class AWSAuthServiceTests: XCTestCase { @@ -166,7 +166,8 @@ class AWSAuthServiceTests: XCTestCase { sessionToken: "somesession", accessKeyId: "accessKeyId", secretAccessKey: "secretAccessKey", - expiration: Date().addingTimeInterval(100)) + expiration: Date().addingTimeInterval(100) + ) let sdkCredentials = 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) } 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 {