From afa888e48c683b95ef89248b313e9b73d24960f3 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Wed, 14 Oct 2026 16:39:26 +0100 Subject: [PATCH] feat: SDK update for the 2.5.x majors --- CHANGELOG.md | 47 +- Package.swift | 5 +- README.md | 6 +- Sources/Appwrite/Client.swift | 86 +- Sources/Appwrite/Services/Account.swift | 335 ++++- Sources/Appwrite/Services/Analytics.swift | 81 ++ Sources/Appwrite/Services/Oauth2.swift | 20 +- Sources/Appwrite/Services/Push.swift | 1174 ----------------- Sources/Appwrite/Services/Teams.swift | 5 +- Sources/Appwrite/Topic.swift | 126 -- Sources/AppwriteModels/Account.swift | 49 +- Sources/AppwriteModels/AlgoArgon2.swift | 16 +- Sources/AppwriteModels/AlgoBcrypt.swift | 5 +- Sources/AppwriteModels/AlgoMd5.swift | 5 +- Sources/AppwriteModels/AlgoPhpass.swift | 5 +- Sources/AppwriteModels/AlgoScrypt.swift | 19 +- .../AppwriteModels/AlgoScryptModified.swift | 16 +- Sources/AppwriteModels/AlgoSha.swift | 5 +- Sources/AppwriteModels/App.swift | 82 +- Sources/AppwriteModels/AppInstallation.swift | 31 +- .../AppwriteModels/AppInstallationList.swift | 10 +- Sources/AppwriteModels/AppKey.swift | 28 +- Sources/AppwriteModels/AppKeyList.swift | 10 +- Sources/AppwriteModels/AppScope.swift | 19 +- Sources/AppwriteModels/AppScopeList.swift | 10 +- Sources/AppwriteModels/AppSecret.swift | 28 +- Sources/AppwriteModels/AppSecretList.swift | 10 +- .../AppwriteModels/AppSecretPlaintext.swift | 28 +- Sources/AppwriteModels/AppsList.swift | 10 +- Sources/AppwriteModels/Continent.swift | 10 +- Sources/AppwriteModels/ContinentList.swift | 10 +- Sources/AppwriteModels/Country.swift | 10 +- Sources/AppwriteModels/CountryList.swift | 10 +- Sources/AppwriteModels/Currency.swift | 25 +- Sources/AppwriteModels/CurrencyList.swift | 10 +- Sources/AppwriteModels/Document.swift | 25 +- Sources/AppwriteModels/DocumentList.swift | 10 +- Sources/AppwriteModels/Execution.swift | 52 +- Sources/AppwriteModels/ExecutionList.swift | 10 +- Sources/AppwriteModels/File.swift | 52 +- Sources/AppwriteModels/FileList.swift | 10 +- Sources/AppwriteModels/Headers.swift | 10 +- Sources/AppwriteModels/Identity.swift | 37 +- Sources/AppwriteModels/IdentityList.swift | 10 +- Sources/AppwriteModels/Jwt.swift | 5 +- Sources/AppwriteModels/Language.swift | 13 +- Sources/AppwriteModels/LanguageList.swift | 10 +- Sources/AppwriteModels/Locale.swift | 25 +- Sources/AppwriteModels/LocaleCode.swift | 10 +- Sources/AppwriteModels/LocaleCodeList.swift | 10 +- Sources/AppwriteModels/Membership.swift | 49 +- Sources/AppwriteModels/MembershipList.swift | 10 +- Sources/AppwriteModels/MfaChallenge.swift | 16 +- Sources/AppwriteModels/MfaFactors.swift | 19 +- Sources/AppwriteModels/MfaRecoveryCodes.swift | 5 +- Sources/AppwriteModels/MfaType.swift | 10 +- Sources/AppwriteModels/Oauth2Approve.swift | 5 +- Sources/AppwriteModels/Oauth2Authorize.swift | 10 +- Sources/AppwriteModels/Oauth2Consent.swift | 34 +- .../AppwriteModels/Oauth2ConsentList.swift | 10 +- .../AppwriteModels/Oauth2ConsentToken.swift | 37 +- .../Oauth2ConsentTokenList.swift | 10 +- .../Oauth2DeviceAuthorization.swift | 22 +- Sources/AppwriteModels/Oauth2Grant.swift | 40 +- .../AppwriteModels/Oauth2Organization.swift | 5 +- .../Oauth2OrganizationList.swift | 10 +- Sources/AppwriteModels/Oauth2PAR.swift | 10 +- Sources/AppwriteModels/Oauth2Project.swift | 13 +- .../AppwriteModels/Oauth2ProjectList.swift | 10 +- Sources/AppwriteModels/Oauth2Reject.swift | 5 +- Sources/AppwriteModels/Oauth2Token.swift | 19 +- Sources/AppwriteModels/Passkey.swift | 88 ++ Sources/AppwriteModels/PasskeyChallenge.swift | 88 ++ Sources/AppwriteModels/PasskeyList.swift | 58 + Sources/AppwriteModels/Phone.swift | 13 +- Sources/AppwriteModels/PhoneList.swift | 10 +- Sources/AppwriteModels/Presence.swift | 22 +- Sources/AppwriteModels/PresenceList.swift | 10 +- Sources/AppwriteModels/Row.swift | 25 +- Sources/AppwriteModels/RowList.swift | 10 +- Sources/AppwriteModels/Session.swift | 91 +- Sources/AppwriteModels/SessionList.swift | 10 +- Sources/AppwriteModels/Subscriber.swift | 28 +- Sources/AppwriteModels/Target.swift | 28 +- Sources/AppwriteModels/Team.swift | 19 +- Sources/AppwriteModels/TeamList.swift | 10 +- Sources/AppwriteModels/Token.swift | 22 +- Sources/AppwriteModels/TokenSecret.swift | 98 ++ Sources/AppwriteModels/Transaction.swift | 22 +- Sources/AppwriteModels/TransactionList.swift | 10 +- Sources/AppwriteModels/User.swift | 49 +- .../account/create-o-auth-2-session.md | 3 +- .../examples/account/create-o-auth-2-token.md | 3 +- docs/examples/account/create-passkey-token.md | 12 + docs/examples/account/create-passkey.md | 15 + docs/examples/account/delete-passkey.md | 14 + docs/examples/account/get-passkey.md | 14 + docs/examples/account/list-passkeys.md | 15 + docs/examples/account/update-passkey-token.md | 15 + .../account/update-passkey-verification.md | 15 + docs/examples/account/update-passkey.md | 15 + docs/examples/analytics/create-event.md | 26 + docs/examples/oauth2/approve.md | 4 +- docs/examples/oauth2/authorize-post.md | 18 +- docs/examples/oauth2/authorize.md | 18 +- .../oauth2/create-device-authorization.md | 6 +- docs/examples/oauth2/create-grant.md | 2 +- docs/examples/oauth2/create-par.md | 16 +- docs/examples/oauth2/create-token.md | 16 +- docs/examples/oauth2/get-grant.md | 2 +- docs/examples/oauth2/logout-post.md | 10 +- docs/examples/oauth2/logout.md | 10 +- docs/examples/oauth2/reject.md | 2 +- docs/examples/oauth2/revoke.md | 6 +- docs/examples/teams/create-membership.md | 3 +- 115 files changed, 2090 insertions(+), 1865 deletions(-) create mode 100644 Sources/Appwrite/Services/Analytics.swift delete mode 100644 Sources/Appwrite/Services/Push.swift delete mode 100644 Sources/Appwrite/Topic.swift create mode 100644 Sources/AppwriteModels/Passkey.swift create mode 100644 Sources/AppwriteModels/PasskeyChallenge.swift create mode 100644 Sources/AppwriteModels/PasskeyList.swift create mode 100644 Sources/AppwriteModels/TokenSecret.swift create mode 100644 docs/examples/account/create-passkey-token.md create mode 100644 docs/examples/account/create-passkey.md create mode 100644 docs/examples/account/delete-passkey.md create mode 100644 docs/examples/account/get-passkey.md create mode 100644 docs/examples/account/list-passkeys.md create mode 100644 docs/examples/account/update-passkey-token.md create mode 100644 docs/examples/account/update-passkey-verification.md create mode 100644 docs/examples/account/update-passkey.md create mode 100644 docs/examples/analytics/create-event.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 6097214..c510949 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,37 +1,30 @@ # Change Log -## 20.1.0-rc.3 +## 21.0.0 -* Added: `getInitialNotification()` and `onNotificationOpened(_:)` for background notification taps -* Added: `PushNotificationOpened` exposing the tapped notification `topic` and parsed `data` -* Added: `Push.handleNotificationResponse(_:)` for apps with their own notification-center delegate -* Fixed: `Push` reads the session the app signed in with from saved cookies -* Fixed: posts one notification per distinct title instead of only the first server title -* Fixed: image attachments fall back to the URL extension when the MIME type is missing +* Breaking: requests send `X-Appwrite-Response-Format: 2.5.0`; responses follow the 2.5 shapes +* Breaking: missing response fields decode to their documented defaults instead of throwing +* Added: `Apps` service to manage apps, installations, keys and secrets +* Added: `Oauth2` service for the OAuth2 authorize, token, device and grant flows +* Fixed: a file exactly `Client.chunkSize` bytes long uploads in a single request -## 20.1.0-rc.2 +## 20.2.0 -* Updated: regenerated with sdk-generator 5.5.0; no SDK code changes +* Added: `analytics.createEvent` in a new `Analytics` service to send tracking events +* Added: `avatars.updatePhoto` and `avatars.deletePhoto` to manage the user's custom profile photo, and the `Account` model +* Added: `Webflow` to the `OAuthProvider` enum +* Added: optional `state` on `account.createOAuth2Session` and `account.createOAuth2Token`, returned unchanged on the success and failure URLs +* Added: optional `duration` on `account.createEmailPasswordSession` to set the session length +* Added: optional `current` on `account.deleteSessions` to keep the current session signed in +* Added: optional `membershipId` on `teams.createMembership` +* Added: optional `total` on `account.listSessions`, the `locale` list methods and `listTransactions` +* Fixed: OAuth2 query parameters (`success`, `failure`, `scopes`, `state`) are URL-encoded, so values containing `&`, `+` or `#` survive the redirect -## 20.1.0-rc.1 +## 20.1.0 -* Added: background push notifications render the server `notification` title, body, and image -* Added: notification `userInfo` now carries `topic` and `payload` -* Fixed: a server-sent title replaces per-subscription titles and dedupes notifications - -## 20.1.0-rc.0 - -* Added: `Apps` service to manage OAuth2 apps, keys, secrets, and installations -* Added: `Oauth2` service for authorization, consent, device, PAR, and token flows -* Added: `Push` service for MQTT realtime push, backed by `mqtt-nio` -* Added: `Topic` builder for push targeting -* Added: `Client.setPushEndpoint()` and `Client.setPushClientId()` -* Added: `Avatars.updatePhoto()` and `Avatars.deletePhoto()` methods -* Added: `App`, `Oauth2*`, and `Account` models -* Added: `webflow` to the `OAuthProvider` enum -* Added: optional `duration` and `total` params on account and list methods -* Updated: `chunkedUpload` gained a `method` param for `PUT` uploads -* Fixed: `chunkedUpload` sends an exactly-chunk-sized file in a single request +* Added: `account` passkey methods `listPasskeys`, `createPasskey`, `getPasskey`, `updatePasskey`, `deletePasskey` and `updatePasskeyVerification` +* Added: `account.createPasskeyToken` and `account.updatePasskeyToken` for passkey sign-in +* Added: `Passkey`, `PasskeyList`, `PasskeyChallenge` and `TokenSecret` models ## 20.0.0 diff --git a/Package.swift b/Package.swift index 8a0c8cd..a572332 100644 --- a/Package.swift +++ b/Package.swift @@ -23,8 +23,9 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.36.1"), + // swift-distributed-tracing 1.6.0 makes ServiceContext ambiguous inside async-http-client. + .package(url: "https://github.com/apple/swift-distributed-tracing.git", "1.0.0"..<"1.6.0"), .package(url: "https://github.com/apple/swift-nio.git", from: "2.102.0"), - .package(url: "https://github.com/swift-server-community/mqtt-nio.git", from: "2.13.0"), ], targets: [ .target( @@ -32,8 +33,6 @@ let package = Package( dependencies: [ .product(name: "AsyncHTTPClient", package: "async-http-client"), .product(name: "NIOWebSocket", package: "swift-nio"), - .product(name: "NIOCore", package: "swift-nio"), - .product(name: "MQTTNIO", package: "mqtt-nio"), "AppwriteModels", "AppwriteEnums", "JSONCodable", diff --git a/README.md b/README.md index d3eacf5..de3a7d7 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,12 @@ ![Swift Package Manager](https://img.shields.io/github/v/release/appwrite/sdk-for-apple.svg?color=green&style=flat-square) ![License](https://img.shields.io/github/license/appwrite/sdk-for-apple.svg?style=flat-square) -![Version](https://img.shields.io/badge/api%20version-2.3.0-blue.svg?style=flat-square) +![Version](https://img.shields.io/badge/api%20version-2.5.0-blue.svg?style=flat-square) [![Build Status](https://img.shields.io/travis/com/appwrite/sdk-generator?style=flat-square)](https://travis-ci.com/appwrite/sdk-generator) [![Twitter Account](https://img.shields.io/twitter/follow/appwrite?color=00acee&label=twitter&style=flat-square)](https://twitter.com/appwrite) [![Discord](https://img.shields.io/discord/564160730845151244?label=discord&style=flat-square)](https://appwrite.io/discord) -**This SDK targets Appwrite server version 2.3.x as shipped on Appwrite Cloud.** Self-hosted releases can lag behind Cloud — if you run an older self-hosted build, use a matching older SDK from [previous releases](https://github.com/appwrite/sdk-for-apple/releases) when APIs differ. +**This SDK targets Appwrite server version 2.5.x as shipped on Appwrite Cloud.** Self-hosted releases can lag behind Cloud — if you run an older self-hosted build, use a matching older SDK from [previous releases](https://github.com/appwrite/sdk-for-apple/releases) when APIs differ. Appwrite is an open-source backend as a service server that abstracts and simplifies complex and repetitive development tasks behind a very simple to use REST API. Appwrite aims to help you develop your apps faster and in a more secure way. Use the Apple SDK to integrate your app with the Appwrite server to easily start interacting with all of Appwrite backend APIs and tools. For full API documentation and tutorials go to [https://appwrite.io/docs](https://appwrite.io/docs) @@ -31,7 +31,7 @@ Add the package to your `Package.swift` dependencies: ```swift dependencies: [ - .package(url: "git@github.com:appwrite/sdk-for-apple.git", from: "20.1.0-rc.3"), + .package(url: "git@github.com:appwrite/sdk-for-apple.git", from: "21.0.0"), ], ``` diff --git a/Sources/Appwrite/Client.swift b/Sources/Appwrite/Client.swift index e19f4e6..fd7d4c1 100644 --- a/Sources/Appwrite/Client.swift +++ b/Sources/Appwrite/Client.swift @@ -23,17 +23,13 @@ open class Client { open var endPointRealtime: String? = nil - open var endPointPush: String? = nil - - open var pushClientId: String? = nil - open var headers: [String: String] = [ "content-type": "application/json", "x-sdk-name": "Apple", "x-sdk-platform": "client", "x-sdk-language": "apple", - "x-sdk-version": "20.1.0-rc.3", - "x-appwrite-response-format": "2.3.0", + "x-sdk-version": "21.0.0", + "x-appwrite-response-format": "2.5.0", ] internal var config: [String: String] = [:] @@ -316,37 +312,6 @@ open class Client { return self } - /// - /// Set push endpoint. - /// - /// The MQTT broker URL the Push service connects to, e.g. `mqtt://host:1883` or - /// `mqtts://host:8883`. - /// - /// @param String endPoint - /// - /// @return Client - /// - open func setPushEndpoint(_ endPoint: String) -> Client { - self.endPointPush = endPoint - return self - } - - /// - /// Set push client id. - /// - /// A stable client id for the Push service. The broker keys its offline-replay cursor on - /// this id, so pass a stable value to resume replay across restarts. Defaults to a - /// per-connection id when unset. - /// - /// @param String pushClientId - /// - /// @return Client - /// - open func setPushClientId(_ pushClientId: String) -> Client { - self.pushClientId = pushClientId - return self - } - /// /// Add header /// @@ -377,43 +342,34 @@ open class Client { /// @return String /// open func parametersToQueryString(params: [String: Any?]) -> String { - var output: String = "" + // RFC 3986 unreserved characters only, so `&`, `=`, `+` and `#` inside a value are escaped + let allowed = CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" + ) - func appendWhenNotLast( - _ index: Int, ofTotal count: Int, outerIndex: Int? = nil, outerCount: Int? = nil - ) { - if index != count - 1 - || (outerIndex != nil - && outerCount != nil - && index == count - 1 - && outerIndex! != outerCount! - 1) - { - output += "&" - } + func encode(_ value: Any) -> String { + return "\(value)".addingPercentEncoding(withAllowedCharacters: allowed) ?? "" } - for (parameterIndex, element) in params.enumerated() { - switch element.value { + var output: [String] = [] + + for (key, value) in params { + switch value { case nil: - break - case is [Any?]: - let list = element.value as! [Any?] - for (nestedIndex, item) in list.enumerated() { - output += "\(element.key)[]=\(item!)" - appendWhenNotLast( - nestedIndex, ofTotal: list.count, outerIndex: parameterIndex, - outerCount: params.count) + continue + case let list as [Any?]: + for item in list { + guard let item = item else { + continue + } + output.append("\(encode("\(key)[]"))=\(encode(item))") } - appendWhenNotLast(parameterIndex, ofTotal: params.count) default: - output += "\(element.key)=\(element.value!)" - appendWhenNotLast(parameterIndex, ofTotal: params.count) + output.append("\(encode(key))=\(encode(value!))") } } - return output.addingPercentEncoding( - withAllowedCharacters: .urlHostAllowed - )?.replacingOccurrences(of: "+", with: "%2B") ?? "" // since urlHostAllowed doesn't include + + return output.joined(separator: "&") } /// diff --git a/Sources/Appwrite/Services/Account.swift b/Sources/Appwrite/Services/Account.swift index da5b9fc..aa8a3e1 100644 --- a/Sources/Appwrite/Services/Account.swift +++ b/Sources/Appwrite/Services/Account.swift @@ -1336,6 +1336,250 @@ open class Account: Service { ) } /// + /// Get the list of verified passkeys registered by the currently logged in + /// user. + /// + /// - Parameters: + /// - queries: [String] (optional) + /// - total: Bool (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.PasskeyList + /// + open func listPasskeys( + queries: [String]? = nil, + total: Bool? = nil + ) async throws -> AppwriteModels.PasskeyList { + let apiPath: String = "/account/passkeys" + + let apiParams: [String: Any?] = [ + "queries": queries, + "total": total, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.PasskeyList = { response in + return AppwriteModels.PasskeyList.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Start registering a passkey for the currently logged in user. The session + /// must have signed in or completed an MFA challenge within the last 10 + /// minutes. Pass the returned `publicKey` options to + /// `navigator.credentials.create()`, then complete the registration with + /// [Update passkey + /// verification](/docs/references/cloud/client-web/account#updatePasskeyVerification). + /// The passkey stays pending until verified, and the challenge expires after 5 + /// minutes. + /// + /// - Parameters: + /// - passkeyId: String (optional) + /// - name: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.PasskeyChallenge + /// + open func createPasskey( + passkeyId: String? = nil, + name: String? = nil + ) async throws -> AppwriteModels.PasskeyChallenge { + let apiPath: String = "/account/passkeys" + + let apiParams: [String: Any?] = [ + "passkeyId": passkeyId, + "name": name, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.PasskeyChallenge = { response in + return AppwriteModels.PasskeyChallenge.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Get a verified passkey of the currently logged in user by its unique ID. + /// + /// - Parameters: + /// - passkeyId: String + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Passkey + /// + open func getPasskey( + passkeyId: String + ) async throws -> AppwriteModels.Passkey { + if passkeyId.isEmpty { + throw AppwriteError(message: "Missing required parameter: \"passkeyId\"") + } + + let apiPath: String = "/account/passkeys/{passkeyId}" + .replacingOccurrences(of: "{passkeyId}", with: passkeyId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Passkey = { response in + return AppwriteModels.Passkey.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "GET", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Rename a passkey of the currently logged in user. + /// + /// - Parameters: + /// - passkeyId: String + /// - name: String + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Passkey + /// + open func updatePasskey( + passkeyId: String, + name: String + ) async throws -> AppwriteModels.Passkey { + if passkeyId.isEmpty { + throw AppwriteError(message: "Missing required parameter: \"passkeyId\"") + } + + let apiPath: String = "/account/passkeys/{passkeyId}" + .replacingOccurrences(of: "{passkeyId}", with: passkeyId) + + let apiParams: [String: Any?] = [ + "name": name + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Passkey = { response in + return AppwriteModels.Passkey.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PATCH", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Delete a passkey from the currently logged in user. The passkey can no + /// longer be used to sign in, although it may remain stored on the user's + /// device. The session must have signed in or completed an MFA challenge + /// within the last 10 minutes. + /// + /// - Parameters: + /// - passkeyId: String + /// - Throws: Exception if the request fails + /// - Returns: Any + /// + open func deletePasskey( + passkeyId: String + ) async throws -> Any { + if passkeyId.isEmpty { + throw AppwriteError(message: "Missing required parameter: \"passkeyId\"") + } + + let apiPath: String = "/account/passkeys/{passkeyId}" + .replacingOccurrences(of: "{passkeyId}", with: passkeyId) + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + return try await client.call( + method: "DELETE", + path: apiPath, + headers: apiHeaders, + params: apiParams + ) + } + /// + /// Complete a passkey registration started with [Create + /// passkey](/docs/references/cloud/client-web/account#createPasskey). Pass the + /// JSON form of the credential returned by `navigator.credentials.create()`, + /// for example `credential.toJSON()`. Each registration can be verified once; + /// a failed attempt requires starting it again. + /// + /// - Parameters: + /// - passkeyId: String + /// - credential: Any + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.Passkey + /// + open func updatePasskeyVerification( + passkeyId: String, + credential: Any + ) async throws -> AppwriteModels.Passkey { + if passkeyId.isEmpty { + throw AppwriteError(message: "Missing required parameter: \"passkeyId\"") + } + + let apiPath: String = "/account/passkeys/{passkeyId}/verification" + .replacingOccurrences(of: "{passkeyId}", with: passkeyId) + + let apiParams: [String: Any?] = [ + "credential": credential + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.Passkey = { response in + return AppwriteModels.Passkey.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PUT", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// /// Update currently logged in user password. For validation, user is required /// to pass in the new password, and the old password. For users created with /// OAuth, Team Invites and Magic URL, oldPassword is optional. @@ -2059,6 +2303,7 @@ open class Account: Service { /// - success: String (optional) /// - failure: String (optional) /// - scopes: [String] (optional) + /// - state: String (optional) /// - Throws: Exception if the request fails /// - Returns: Bool /// @@ -2067,7 +2312,8 @@ open class Account: Service { provider: AppwriteEnums.OAuthProvider, success: String? = nil, failure: String? = nil, - scopes: [String]? = nil + scopes: [String]? = nil, + state: String? = nil ) async throws -> Bool { let apiPath: String = "/account/sessions/oauth2/{provider}" .replacingOccurrences(of: "{provider}", with: provider.rawValue) @@ -2076,6 +2322,7 @@ open class Account: Service { "success": success, "failure": failure, "scopes": scopes, + "state": state, "project": client.config["project"], ] @@ -2606,6 +2853,7 @@ open class Account: Service { /// - success: String (optional) /// - failure: String (optional) /// - scopes: [String] (optional) + /// - state: String (optional) /// - Throws: Exception if the request fails /// - Returns: Bool /// @@ -2614,7 +2862,8 @@ open class Account: Service { provider: AppwriteEnums.OAuthProvider, success: String? = nil, failure: String? = nil, - scopes: [String]? = nil + scopes: [String]? = nil, + state: String? = nil ) async throws -> Bool { let apiPath: String = "/account/tokens/oauth2/{provider}" .replacingOccurrences(of: "{provider}", with: provider.rawValue) @@ -2623,6 +2872,7 @@ open class Account: Service { "success": success, "failure": failure, "scopes": scopes, + "state": state, "project": client.config["project"], ] @@ -2648,6 +2898,87 @@ open class Account: Service { } /// + /// Start signing in with a passkey. No email or user ID is needed: pass the + /// returned `publicKey` options to `navigator.credentials.get()` and the user + /// picks one of their passkeys. Then call [Update passkey + /// token](/docs/references/cloud/client-web/account#updatePasskeyToken) with + /// the credential to receive a token, and exchange it with [Create + /// session](/docs/references/cloud/client-web/account#createSession). The + /// challenge expires after 5 minutes. + /// + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.PasskeyChallenge + /// + open func createPasskeyToken() async throws -> AppwriteModels.PasskeyChallenge { + let apiPath: String = "/account/tokens/passkey" + + let apiParams: [String: Any] = [:] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.PasskeyChallenge = { response in + return AppwriteModels.PasskeyChallenge.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// + /// Complete a passkey sign-in started with [Create passkey + /// token](/docs/references/cloud/client-web/account#createPasskeyToken). Pass + /// the challenge ID and the JSON form of the credential returned by + /// `navigator.credentials.get()`, for example `credential.toJSON()`. The + /// returned token includes its secret and expires after 1 minute: exchange it + /// for a session with [Create + /// session](/docs/references/cloud/client-web/account#createSession). Passkeys + /// require user verification, so the session also satisfies MFA. Each + /// challenge can only be used once. + /// + /// - Parameters: + /// - challengeId: String + /// - credential: Any + /// - Throws: Exception if the request fails + /// - Returns: AppwriteModels.TokenSecret + /// + open func updatePasskeyToken( + challengeId: String, + credential: Any + ) async throws -> AppwriteModels.TokenSecret { + let apiPath: String = "/account/tokens/passkey" + + let apiParams: [String: Any?] = [ + "challengeId": challengeId, + "credential": credential, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + let converter: (Any) throws -> AppwriteModels.TokenSecret = { response in + return AppwriteModels.TokenSecret.from(map: response as! [String: Any]) + } + + return try await client.call( + method: "PUT", + path: apiPath, + headers: apiHeaders, + params: apiParams, + converter: converter + ) + } + /// /// Sends the user an SMS with a secret key for creating a session. If the /// provided user ID has not be registered, a new user will be created. Use the /// returned user ID and secret and submit a request to the [POST diff --git a/Sources/Appwrite/Services/Analytics.swift b/Sources/Appwrite/Services/Analytics.swift new file mode 100644 index 0000000..2fad41b --- /dev/null +++ b/Sources/Appwrite/Services/Analytics.swift @@ -0,0 +1,81 @@ +import AppwriteEnums +import AppwriteModels +import AsyncHTTPClient +import Foundation +import JSONCodable +import NIO + +/// +open class Analytics: Service { + + /// + /// Send a tracking event from a browser, native app, or server-side SDK. + /// + /// - Parameters: + /// - propertyId: String + /// - name: String + /// - url: String + /// - domain: String (optional) + /// - referrer: String (optional) + /// - screenWidth: Int (optional) + /// - sessionHash: String (optional) + /// - scrollDepth: Int (optional) + /// - engagementTime: Int (optional) + /// - props: [String] (optional) + /// - userId: String (optional) + /// - ip: String (optional) + /// - userAgent: String (optional) + /// - Throws: Exception if the request fails + /// - Returns: Any + /// + open func createEvent( + propertyId: String, + name: String, + url: String, + domain: String? = nil, + referrer: String? = nil, + screenWidth: Int? = nil, + sessionHash: String? = nil, + scrollDepth: Int? = nil, + engagementTime: Int? = nil, + props: [String]? = nil, + userId: String? = nil, + ip: String? = nil, + userAgent: String? = nil + ) async throws -> Any { + if propertyId.isEmpty { + throw AppwriteError(message: "Missing required parameter: \"propertyId\"") + } + + let apiPath: String = "/analytics/properties/{propertyId}/events" + .replacingOccurrences(of: "{propertyId}", with: propertyId) + + let apiParams: [String: Any?] = [ + "name": name, + "url": url, + "domain": domain, + "referrer": referrer, + "screenWidth": screenWidth, + "sessionHash": sessionHash, + "scrollDepth": scrollDepth, + "engagementTime": engagementTime, + "props": props, + "userId": userId, + "ip": ip, + "userAgent": userAgent, + ] + + let apiHeaders: [String: String] = [ + "X-Appwrite-Project": client.config["project"] ?? "", + "content-type": "application/json", + "accept": "application/json", + ] + + return try await client.call( + method: "POST", + path: apiPath, + headers: apiHeaders, + params: apiParams + ) + } +} diff --git a/Sources/Appwrite/Services/Oauth2.swift b/Sources/Appwrite/Services/Oauth2.swift index f216618..545b558 100644 --- a/Sources/Appwrite/Services/Oauth2.swift +++ b/Sources/Appwrite/Services/Oauth2.swift @@ -72,7 +72,7 @@ open class Oauth2: Service { /// - prompt: String (optional) /// - maxAge: Int (optional) /// - authorizationDetails: String (optional) - /// - resource: String (optional) + /// - resource: [String] (optional) /// - audience: String (optional) /// - requestUri: String (optional) /// - Throws: Exception if the request fails @@ -90,7 +90,7 @@ open class Oauth2: Service { prompt: String? = nil, maxAge: Int? = nil, authorizationDetails: String? = nil, - resource: String? = nil, + resource: [String]? = nil, audience: String? = nil, requestUri: String? = nil ) async throws -> AppwriteModels.Oauth2Authorize { @@ -149,7 +149,7 @@ open class Oauth2: Service { /// - prompt: String (optional) /// - maxAge: Int (optional) /// - authorizationDetails: String (optional) - /// - resource: String (optional) + /// - resource: [String] (optional) /// - audience: String (optional) /// - requestUri: String (optional) /// - Throws: Exception if the request fails @@ -167,7 +167,7 @@ open class Oauth2: Service { prompt: String? = nil, maxAge: Int? = nil, authorizationDetails: String? = nil, - resource: String? = nil, + resource: [String]? = nil, audience: String? = nil, requestUri: String? = nil ) async throws -> AppwriteModels.Oauth2Authorize { @@ -216,7 +216,7 @@ open class Oauth2: Service { /// - clientId: String (optional) /// - scope: String (optional) /// - authorizationDetails: String (optional) - /// - resource: String (optional) + /// - resource: [String] (optional) /// - audience: String (optional) /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.Oauth2DeviceAuthorization @@ -225,7 +225,7 @@ open class Oauth2: Service { clientId: String? = nil, scope: String? = nil, authorizationDetails: String? = nil, - resource: String? = nil, + resource: [String]? = nil, audience: String? = nil ) async throws -> AppwriteModels.Oauth2DeviceAuthorization { let apiPath: String = "/oauth2/{project_id}/device_authorization" @@ -486,7 +486,7 @@ open class Oauth2: Service { /// - prompt: String (optional) /// - maxAge: Int (optional) /// - authorizationDetails: String (optional) - /// - resource: String (optional) + /// - resource: [String] (optional) /// - audience: String (optional) /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.Oauth2PAR @@ -503,7 +503,7 @@ open class Oauth2: Service { prompt: String? = nil, maxAge: Int? = nil, authorizationDetails: String? = nil, - resource: String? = nil, + resource: [String]? = nil, audience: String? = nil ) async throws -> AppwriteModels.Oauth2PAR { let apiPath: String = "/oauth2/{project_id}/par" @@ -674,7 +674,7 @@ open class Oauth2: Service { /// - clientSecret: String (optional) /// - codeVerifier: String (optional) /// - redirectUri: String (optional) - /// - resource: String (optional) + /// - resource: [String] (optional) /// - audience: String (optional) /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.Oauth2Token @@ -688,7 +688,7 @@ open class Oauth2: Service { clientSecret: String? = nil, codeVerifier: String? = nil, redirectUri: String? = nil, - resource: String? = nil, + resource: [String]? = nil, audience: String? = nil ) async throws -> AppwriteModels.Oauth2Token { let apiPath: String = "/oauth2/{project_id}/token" diff --git a/Sources/Appwrite/Services/Push.swift b/Sources/Appwrite/Services/Push.swift deleted file mode 100644 index 33f7486..0000000 --- a/Sources/Appwrite/Services/Push.swift +++ /dev/null @@ -1,1174 +0,0 @@ -import Foundation -import MQTTNIO -import NIOCore - -#if canImport(UserNotifications) - import UserNotifications -#endif - -/// A message delivered on a subscribed topic — the MQTT push analog of a realtime event. -public struct PushMessage { - /// The topic the message was published to. - public let topic: String - - /// The raw message payload. - public let payload: [UInt8] - - /// The MQTT quality of service the message was delivered with. - public let qos: Int - - /// The payload decoded as UTF-8 text, as it was sent. - public var data: String { - String(decoding: payload, as: UTF8.self) - } -} - -/// A background notification the user tapped; see `Push.getInitialNotification()` and -/// `Push.onNotificationOpened(_:)`. -public struct PushNotificationOpened { - /// The topic the message was published to. - public let topic: String - - /// The `data` sent with the message (e.g. `createPush`), parsed; empty when it had none. - public let data: [String: Any] - - init(topic: String, payload: String) { - self.topic = topic - let object = (try? JSONSerialization.jsonObject(with: Data(payload.utf8))) as? [String: Any] - self.data = object?["data"] as? [String: Any] ?? [:] - } -} - -#if canImport(UserNotifications) - /// Receives taps on the notifications `Push` posts. It becomes the notification center's - /// delegate when the first `Push` is created and forwards everything else to the delegate it - /// replaced. A tap while nothing listens waits for `Push.getInitialNotification()`. - final class PushNotificationTaps: NSObject, UNUserNotificationCenterDelegate { - static let shared = PushNotificationTaps() - - private let lock = NSLock() - private var installed = false - private var pending: PushNotificationOpened? - private var listeners: [UUID: (PushNotificationOpened) -> Void] = [:] - private weak var forwarded: UNUserNotificationCenterDelegate? - - func install() { - // The notification center needs an app bundle; command-line tools have none. - guard Bundle.main.bundleIdentifier != nil else { - return - } - lock.lock() - defer { lock.unlock() } - guard !installed else { - return - } - installed = true - let center = UNUserNotificationCenter.current() - forwarded = center.delegate - center.delegate = self - } - - /// Report [response] when it is a tap on a notification `Push` posted; false otherwise. - func handle(_ response: UNNotificationResponse) -> Bool { - let info = response.notification.request.content.userInfo - guard response.actionIdentifier == UNNotificationDefaultActionIdentifier, - let topic = info["topic"] as? String, - let payload = info["payload"] as? String - else { - return false - } - let opened = PushNotificationOpened(topic: topic, payload: payload) - lock.lock() - let callbacks = Array(listeners.values) - if callbacks.isEmpty { - pending = opened - } - lock.unlock() - callbacks.forEach { $0(opened) } - return true - } - - func take() -> PushNotificationOpened? { - lock.lock() - defer { lock.unlock() } - let opened = pending - pending = nil - return opened - } - - func listen(_ callback: @escaping (PushNotificationOpened) -> Void) -> () -> Void { - let id = UUID() - lock.lock() - listeners[id] = callback - lock.unlock() - return { [weak self] in - guard let self else { - return - } - self.lock.lock() - self.listeners[id] = nil - self.lock.unlock() - } - } - - // Every other delegate method (e.g. `openSettingsFor`) goes to the delegate this one replaced. - override func responds(to aSelector: Selector!) -> Bool { - super.responds(to: aSelector) || (forwarded?.responds(to: aSelector) ?? false) - } - - override func forwardingTarget(for aSelector: Selector!) -> Any? { - if let forwarded, forwarded.responds(to: aSelector) { - return forwarded - } - return super.forwardingTarget(for: aSelector) - } - - func userNotificationCenter( - _ center: UNUserNotificationCenter, - didReceive response: UNNotificationResponse, - withCompletionHandler completionHandler: @escaping () -> Void - ) { - if handle(response) { - completionHandler() - } else if let forwarded, forwarded.responds(to: #selector(UNUserNotificationCenterDelegate.userNotificationCenter(_:didReceive:withCompletionHandler:))) { - forwarded.userNotificationCenter?(center, didReceive: response, withCompletionHandler: completionHandler) - } else { - completionHandler() - } - } - - func userNotificationCenter( - _ center: UNUserNotificationCenter, - willPresent notification: UNNotification, - withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void - ) { - if let forwarded, forwarded.responds(to: #selector(UNUserNotificationCenterDelegate.userNotificationCenter(_:willPresent:withCompletionHandler:))) { - forwarded.userNotificationCenter?(center, willPresent: notification, withCompletionHandler: completionHandler) - } else { - completionHandler([]) - } - } - } -#endif - -/// A topic as accepted by `Push.subscribe`: a raw `String`, a `Topic` or a `ResolvedTopic`. -public protocol TopicValue { - func toString() -> String -} - -// String already gets `toString()` from the `ChannelValue` conformance in Channel.swift. -extension String: TopicValue {} - -extension Topic: TopicValue {} - -extension ResolvedTopic: TopicValue {} - -/// Handle for a live subscription created with `Push.subscribe`. -/// -/// Unlike the realtime service's bare unsubscribe callable, a push subscription carries -/// per-subscription state (background delivery, notification title), so `subscribe` returns -/// this handle: `unsubscribe()` drops it (and closes the connection once the last one is -/// gone) and `update(background:title:)` toggles its options live without resubscribing. -public final class PushSubscription { - private let unsubscribeAction: () -> Void - private let updateAction: (Bool?, String?, Bool?) -> Void - - init(unsubscribe: @escaping () -> Void, update: @escaping (Bool?, String?, Bool?) -> Void) { - self.unsubscribeAction = unsubscribe - self.updateAction = update - } - - /// Drop this subscription. Closes the connection once the last one is gone. - public func unsubscribe() { - unsubscribeAction() - } - - /// Live-update this subscription's background delivery, notification title and/or - /// `retry` (QoS). Only the arguments you pass change; the rest stay as they - /// were. Changing `retry` re-subscribes this subscription's topics at the - /// new QoS. - public func update(background: Bool? = nil, title: String? = nil, retry: Bool? = nil) { - updateAction(background, title, retry) - } -} - -/// Appwrite native push service — the realtime analog delivered over an MQTT broker, -/// without FCM or APNS. Built on SwiftNIO (MQTTNIO), the same stack the rest of the SDK's -/// networking uses. While the app is alive the connection stays open and each message is -/// handed to your callback; a subscription can also opt into a local notification per message. -/// -/// The connection has no tunables — it always keeps its session (clean start off) so the -/// broker can redeliver missed messages, and reliability is chosen per subscription via -/// `subscribe`'s `retry`. TLS (and skipping cert verification via a -/// `?tlsInsecure=true` query flag) is derived from the endpoint, so the whole connection is -/// described in one place. `subscribe` opens the connection lazily and returns a -/// `PushSubscription` handle. The credential is read off the client: a JWT or session set on it -/// (`Client.setJWT` / `Client.setSession`), else the session the app signed in with through it -/// (e.g. `Account.createEmailPasswordSession`). -/// -/// let push = Push(client) -/// let sub = try await push.subscribe("user/123/#") { message in -/// print("\(message.topic): \(message.data)") -/// } -/// // sub.update(background: true, title: "Messages") -/// sub.unsubscribe() -open class Push: Service { - // Fixed keep-alive (PINGREQ interval) in seconds — not exposed as an option. - private static let keepAliveSeconds: UInt16 = 60 - - private let host: String - private let port: Int - private let tls: Bool - private let tlsInsecure: Bool - - // Resolved once per instance: a reconnect rebuilds the MQTTClient, and if each rebuild drew - // a new random id the broker would treat it as a new session and drop this client's replay - // cursor. A stable id from Client.setPushClientId() resumes replay across restarts; - // otherwise one is generated. Reusing one id keeps it stable. - private let resolvedClientId: String - - private var mqtt: MQTTClient? - private var connecting: Task? - private var connectedKey = "" - private var connectionEpoch = 0 - private var resubscribeOnConnect = false - private var retired = Set() - private var closedClients = Set() - private var closeGeneration = 0 - - private var onOpenCb: (() -> Void)? - private var onCloseCb: (() -> Void)? - private var onErrorCb: ((Swift.Error) -> Void)? - - // Set by close() so the close listener does not try to reconnect a deliberate teardown. - private var closing = false - // True while a reconnect loop is running, so a burst of close events starts only one. - private var reconnecting = false - - // Guards the mutable state below; the publish listener fires on an event loop. - private let sync = DispatchQueue(label: "appwrite.push") - - // Local id -> subscription (topic filter, callback, per-sub options). The id is never - // sent to the broker; it only lets the same topic carry more than one callback. - private var subscriptions: [String: (filter: String, callback: (PushMessage) -> Void, background: Bool, title: String?, retry: Bool)] = [:] - - public override init(_ client: Client) { - // The broker location is taken from Client.setPushEndpoint() when set (e.g. - // "mqtts://host:8883"), otherwise from the regular endpoint. - let pushEndpoint = client.endPointPush ?? client.endPoint - let url = URL(string: pushEndpoint) - let derivedHost = url?.host ?? "localhost" - // When no explicit push endpoint is set, default to a `push.` host on the regular - // endpoint (mirroring how realtime derives from the endpoint, on the push subdomain). - self.host = client.endPointPush != nil ? derivedHost : "push.\(derivedHost)" - // Secure by default: TLS on when the endpoint scheme is secure (https/wss/mqtts/ssl), - // so the credential in the CONNECT packet is not sent in the clear. - let secure = ["https", "wss", "mqtts", "ssl"].contains((url?.scheme ?? "").lowercased()) - self.tls = secure - // Take the port from the push endpoint only (a regular http/https endpoint's port is - // the API port, not the broker's); otherwise fall back to the MQTT default. - let pushPort = client.endPointPush != nil ? url?.port : nil - self.port = pushPort ?? (secure ? 8883 : 1883) - // Skip TLS cert verification (self-signed brokers / testing) via a query flag on the - // push endpoint, e.g. "mqtts://host:8883?tlsInsecure=true" — so the whole connection - // is described by one URL, not a second config knob. - let insecureFlag = URLComponents(string: pushEndpoint)?.queryItems?.first(where: { $0.name == "tlsInsecure" })?.value - self.tlsInsecure = insecureFlag == "true" || insecureFlag == "1" - // Empty when the app did not set one: the broker derives a stable id server-side - // (keyed on the credential/project) so the replay cursor resumes across restarts. - // Client.setPushClientId(id) overrides it with an explicit id. - let pushClientId = client.pushClientId - self.resolvedClientId = (pushClientId?.isEmpty == false) ? pushClientId! : "" - super.init(client) - #if canImport(UserNotifications) - PushNotificationTaps.shared.install() - #endif - } - - // The broker subscription for a filter uses the highest QoS any local subscription on - // it wants, so a QoS-0 subscription never downgrades a QoS-1 one sharing the filter. - // Call while holding `sync`. - private func effectiveQos(_ filter: String) -> MQTTQoS { - let reliable = subscriptions.values.contains { $0.filter == filter && $0.retry } - return reliable ? .atLeastOnce : .atMostOnce - } - - /// Register a callback invoked when the connection opens (CONNACK success). - @discardableResult - public func onOpen(_ callback: @escaping () -> Void) -> Self { - onOpenCb = callback - return self - } - - /// Register a callback invoked when the connection closes. - @discardableResult - public func onClose(_ callback: @escaping () -> Void) -> Self { - onCloseCb = callback - return self - } - - /// Register a callback invoked with every error the service hits: connection failures and - /// refusals (carrying the broker's reason when it sends one), an unexpected close by the - /// broker, refused or failed (re)subscriptions, reconnect attempts and notification failures. - /// Calls that throw to the caller still throw. Errors outside any call are never thrown, so - /// they cannot crash the app: with no callback registered they are logged. - @discardableResult - public func onError(_ callback: @escaping (Swift.Error) -> Void) -> Self { - onErrorCb = callback - return self - } - - /// The background notification whose tap launched the app, or nil. Reported once. The tap - /// reaches the SDK just after launch, so create `Push` while the app launches and call this - /// once it is running, or register `onNotificationOpened(_:)` at launch, which receives it. - /// - /// if let opened = push.getInitialNotification() { - /// openSale(opened.data["saleId"]) - /// } - public func getInitialNotification() -> PushNotificationOpened? { - #if canImport(UserNotifications) - return PushNotificationTaps.shared.take() - #else - return nil - #endif - } - - /// Call `callback` each time the user taps a background notification while the app is - /// running, including in the background. Returns a function that stops listening. A tap made - /// while nothing listens comes from `getInitialNotification()` instead. - /// - /// let stop = push.onNotificationOpened { opened in - /// openSale(opened.data["saleId"]) - /// } - @discardableResult - public func onNotificationOpened(_ callback: @escaping (PushNotificationOpened) -> Void) -> () -> Void { - #if canImport(UserNotifications) - return PushNotificationTaps.shared.listen(callback) - #else - return {} - #endif - } - - #if canImport(UserNotifications) - /// For apps that set their own `UNUserNotificationCenter` delegate after creating `Push`: - /// pass each response from `userNotificationCenter(_:didReceive:withCompletionHandler:)`. - /// Returns true when it was a tap on a notification `Push` posted, which `Push` reports. - @discardableResult - public static func handleNotificationResponse(_ response: UNNotificationResponse) -> Bool { - PushNotificationTaps.shared.handle(response) - } - #endif - - /// Subscribe to the signed-in user's own topic, `users/`. Returns a `PushSubscription` handle. - /// - /// The user id is read off the client's credential without a network call (the JWT's - /// `userId` claim, else the session's `id`), so this delivers "messages for me" without - /// knowing any topic. Throws when neither a JWT nor a session is set on the client. - /// Like FCM/APNs delivery it defaults to `background: true` and `retry: true` (QoS 1); - /// pass either to override. - /// - /// let sub = try await push.subscribe { message in - /// print(message.data) - /// } - @discardableResult - public func subscribe(background: Bool = true, title: String? = nil, retry: Bool = true, callback: @escaping (PushMessage) -> Void) async throws -> PushSubscription { - let userId: String - do { - userId = try currentUserId() - } catch { - try report(error) - throw error - } - return try await subscribe(["users/\(userId)"], background: background, title: title, retry: retry, callback: callback) - } - - /// Subscribe to a single topic. Returns a `PushSubscription` handle. - @discardableResult - public func subscribe(_ topic: TopicValue, background: Bool = false, title: String? = nil, retry: Bool = true, callback: @escaping (PushMessage) -> Void) async throws -> PushSubscription { - try await subscribe([topic], background: background, title: title, retry: retry, callback: callback) - } - - /// Subscribe to a list of raw string topics. Returns a `PushSubscription` handle. - /// - /// Kept alongside the `[TopicValue]` overload: Swift arrays are invariant, so an existing - /// `[String]` value would not convert to `[TopicValue]` on its own. - @discardableResult - public func subscribe(_ topics: [String], background: Bool = false, title: String? = nil, retry: Bool = true, callback: @escaping (PushMessage) -> Void) async throws - -> PushSubscription - { - try await subscribe(topics.map { $0 as TopicValue }, background: background, title: title, retry: retry, callback: callback) - } - - /// Subscribe to one or more topics. Returns a `PushSubscription` handle. - /// - /// Topics are raw strings or built with `Topic`, e.g. - /// `try await push.subscribe(try Topic.path(["user", userId]).all()) { message in ... }`. - /// Omit the topic (`try await push.subscribe { message in ... }`) to subscribe to the - /// signed-in user's own topic, `users/`. - /// - /// Suspends until the broker has acknowledged the SUBSCRIBE (SUBACK): the broker - /// only starts routing a topic once its subscription is registered, so publishing - /// before the ack races the message ahead of the subscription and it is dropped - /// (no retained replay on MQTT). - /// - /// Set `background` to also surface each matching message as a local notification (via - /// `UserNotifications`, requesting authorization on the spot) with `title` (defaulting to - /// the message topic), and `retry: false` for at-most-once (QoS 0) delivery. - /// Note: iOS cannot keep a raw MQTT socket alive once the app is fully killed (that - /// requires APNs) — this covers delivery while the app is running or briefly backgrounded. - /// Toggle either later with `PushSubscription.update`. - @discardableResult - public func subscribe(_ topics: [TopicValue], background: Bool = false, title: String? = nil, retry: Bool = true, callback: @escaping (PushMessage) -> Void) async throws - -> PushSubscription - { - let topics = topics.map { $0.toString() } - - if background { - requestNotificationAuthorization() - } - - let generation = sync.sync { closeGeneration } - let mqtt: MQTTClient - do { - mqtt = try await connect() - } catch is SupersededError { - if sync.sync(execute: { closeGeneration != generation }) { - throw Push.closedError() - } - return try await subscribe(topics.map { $0 as TopicValue }, background: background, title: title, retry: retry, callback: callback) - } - let epoch = sync.sync { connectionEpoch } - - var ids: [String] = [] - for topic in topics { - let id = UUID().uuidString - ids.append(id) - sync.sync { subscriptions[id] = (topic, callback, background, title, retry) } - } - - do { - let infos = sync.sync { - topics.map { MQTTSubscribeInfoV5(topicFilter: $0, qos: effectiveQos($0)) } - } - try await brokerSubscribe(mqtt, infos) - } catch { - let superseded = sync.sync { () -> Bool in - guard connectionEpoch != epoch else { return false } - for id in ids { - subscriptions.removeValue(forKey: id) - } - return true - } - if superseded { - if sync.sync(execute: { closeGeneration != generation }) { - throw Push.closedError() - } - return try await subscribe(topics.map { $0 as TopicValue }, background: background, title: title, retry: retry, callback: callback) - } - // The SUBSCRIBE failed; roll this call's registrations back (and drop any broker - // filter no other local subscriber owns) so a failed subscribe leaks no callback. - let filters = sync.sync { () -> [String] in - var removed: [String] = [] - for id in ids { - if let entry = subscriptions.removeValue(forKey: id) { - let stillUsed = subscriptions.values.contains { $0.filter == entry.filter } - if !stillUsed { - removed.append(entry.filter) - } - } - } - return removed - } - // Only while the connection is up: a dropped connection already failed the - // SUBSCRIBE, and its UNSUBSCRIBE would just fail again for the same reason. - if !filters.isEmpty && mqtt.isActive() { - do { - try await brokerUnsubscribe(mqtt, filters) - } catch { - // A side failure: surface it without masking the SUBSCRIBE error below. - surface(Push.describe(error)) - } - } - // Report, then throw as before. A broker DISCONNECT that lands while the SUBSCRIBE - // is in flight carries its Reason String (see `describe`). - let described = Push.describe(error) - try report(described) - throw described - } - - let unsubscribe: () -> Void = { [weak self] in - guard let self else { return } - let (removed, downgrade) = self.sync.sync { () -> ([String], [MQTTSubscribeInfoV5]) in - var removedFilters: [String] = [] - var maybeDowngrade = Set() - for id in ids { - if let entry = self.subscriptions.removeValue(forKey: id) { - if entry.retry { - maybeDowngrade.insert(entry.filter) - } - // Only unsubscribe the broker filter once its last local callback is gone. - let stillUsed = self.subscriptions.values.contains { $0.filter == entry.filter } - if !stillUsed { - removedFilters.append(entry.filter) - } - } - } - // A filter that lost its last QoS-1 sub but still has QoS-0 subs must be - // re-SUBSCRIBEd lower, or the broker keeps replaying to at-most-once subs. - let infos = - maybeDowngrade - .filter { f in self.subscriptions.values.contains { $0.filter == f } && self.effectiveQos(f) == .atMostOnce } - .map { MQTTSubscribeInfoV5(topicFilter: $0, qos: .atMostOnce) } - return (removedFilters, infos) - } - let client: MQTTClient? = self.sync.sync { self.mqtt } - if let client, !removed.isEmpty { - self.inBackground { try await self.brokerUnsubscribe(client, removed) } - } - if let client, !downgrade.isEmpty { - self.inBackground { try await self.brokerSubscribe(client, downgrade) } - } - if self.sync.sync(execute: { self.subscriptions.isEmpty }) { - self.close() - } - } - - let update: (Bool?, String?, Bool?) -> Void = { [weak self] newBackground, newTitle, newReDeliver in - guard let self else { return } - let (client, changed) = self.sync.sync { () -> (MQTTClient?, [String]) in - var changedFilters: [String] = [] - for id in ids { - if var entry = self.subscriptions[id] { - if let newBackground { - entry.background = newBackground - } - if let newTitle { - entry.title = newTitle - } - if let newReDeliver, newReDeliver != entry.retry { - entry.retry = newReDeliver - changedFilters.append(entry.filter) - } - self.subscriptions[id] = entry - } - } - return (self.mqtt, changedFilters) - } - if newBackground == true { - self.requestNotificationAuthorization() - } - // Re-SUBSCRIBE the affected filters at their new effective QoS. - if let client, !changed.isEmpty { - let infos = self.sync.sync { - changed.map { MQTTSubscribeInfoV5(topicFilter: $0, qos: self.effectiveQos($0)) } - } - self.inBackground { try await self.brokerSubscribe(client, infos) } - } - } - - return PushSubscription(unsubscribe: unsubscribe, update: update) - } - - /// Tear down the connection and drop all active subscriptions. - /// - /// Returns at once: the DISCONNECT and the client shutdown run on a background queue, - /// because a blocking wait is not allowed on the event loop that runs message callbacks, - /// and those callbacks may call `close()` or drop the last subscription. A connection - /// still being opened is abandoned, and any `subscribe` waiting on it throws. - public func close() { - let client = sync.sync { () -> MQTTClient? in - // Mark this a deliberate close so the close listener does not reconnect. - closing = true - connectionEpoch += 1 - closeGeneration += 1 - let existing = mqtt - mqtt = nil - connecting?.cancel() - connecting = nil - resubscribeOnConnect = false - subscriptions.removeAll() - if let existing { - closedClients.insert(ObjectIdentifier(existing)) - } - return existing - } - guard let client else { return } - DispatchQueue.global().async { [weak self] in - do { - try client.disconnect().wait() - } catch MQTTError.noConnection { - // Already disconnected (e.g. the broker dropped the connection); nothing to send. - } catch { - self?.surface(Push.describe(error)) - } - do { - try client.syncShutdownGracefully() - } catch { - self?.surface(error) - } - } - } - - private static func closedError() -> Swift.Error { - AppwriteError(message: "Push was closed before the subscription was established") - } - - private func requestNotificationAuthorization() { - #if canImport(UserNotifications) - UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] _, error in - if let error { - self?.surface(error) - } - } - #endif - } - - private func connect() async throws -> MQTTClient { - let key = credentialKey() - let superseded = sync.sync { () -> MQTTClient? in - guard self.mqtt != nil || self.connecting != nil, self.connectedKey != key else { return nil } - self.connectionEpoch += 1 - self.connecting = nil - let existing = self.mqtt - self.mqtt = nil - self.resubscribeOnConnect = !self.subscriptions.isEmpty - return existing - } - if let superseded { - retire(superseded) - } - if let existing = sync.sync(execute: { self.mqtt }) { - return existing - } - // Single-flight: concurrent callers await one in-flight connection instead of - // each opening its own (and never see a client before its CONNACK succeeds). - let task: Task = sync.sync { - if let inflight = self.connecting { - return inflight - } - self.connectedKey = key - let epoch = self.connectionEpoch - let created = Task { () throws -> MQTTClient in - do { - let client = try await self.open() - let current = self.sync.sync { () -> Bool in - guard self.connectionEpoch == epoch else { return false } - self.mqtt = client - self.connecting = nil - return true - } - guard current else { - self.retire(client) - throw SupersededError() - } - self.resubscribeIfSuperseded(client) - return client - } catch { - let current = self.sync.sync { () -> Bool in - guard self.connectionEpoch == epoch else { return false } - self.connecting = nil - return true - } - if !current { - throw SupersededError() - } - throw error - } - } - self.connecting = created - return created - } - return try await task.value - } - - /// The session set on the client (`Client.setSession`), else the one the app signed in with - /// through it (e.g. `Account.createEmailPasswordSession`), read from the cookies it saved. - private func session() -> String { - if let session = client.config["session"], !session.isEmpty { - return session - } - let name = "a_session_\(client.config["project"] ?? "")=" - guard let host = URL(string: client.endPoint)?.host, - let cookies = UserDefaults.standard.stringArray(forKey: host) - else { - return "" - } - for cookie in cookies { - let pair = cookie.split(separator: ";", maxSplits: 1).first.map { $0.trimmingCharacters(in: .whitespaces) } ?? "" - if pair.hasPrefix(name) { - let value = String(pair.dropFirst(name.count)) - return value.removingPercentEncoding ?? value - } - } - return "" - } - - private func credentialKey() -> String { - let jwt = client.config["jwt"] ?? "" - let credential = jwt.isEmpty ? "appwrite-session|\(session())" : "appwrite-jwt|\(jwt)" - return [host, String(port), client.config["project"] ?? "", resolvedClientId, credential].joined(separator: "|") - } - - private func retire(_ client: MQTTClient) { - sync.sync { _ = retired.insert(ObjectIdentifier(client)) } - DispatchQueue.global().async { - try? client.disconnect().wait() - try? client.syncShutdownGracefully() - } - } - - private func resubscribeIfSuperseded(_ client: MQTTClient) { - let infos = sync.sync { () -> [MQTTSubscribeInfoV5] in - guard resubscribeOnConnect else { return [] } - resubscribeOnConnect = false - return Set(subscriptions.values.map { $0.filter }).map { - MQTTSubscribeInfoV5(topicFilter: $0, qos: effectiveQos($0)) - } - } - if !infos.isEmpty { - inBackground { [weak self] in - try await self?.brokerSubscribe(client, infos) - } - } - } - - // Read the credential off the client and build the CONNECT properties (enhanced auth plus - // the project id). Rebuilt on every connect so a reconnect picks up a refreshed credential. - private func connectProperties() throws -> MQTTProperties { - let authMethod: String - let credential: String - if let jwt = client.config["jwt"], !jwt.isEmpty { - authMethod = "appwrite-jwt" - credential = jwt - } else if case let signedIn = session(), !signedIn.isEmpty { - authMethod = "appwrite-session" - credential = signedIn - } else { - throw AppwriteError(message: "No credential: sign in with this client, or call Client.setJWT() or Client.setSession() first.") - } - let project = client.config["project"] ?? "" - return MQTTProperties([ - .authenticationMethod(authMethod), - .authenticationData(ByteBuffer(bytes: Array(credential.utf8))), - .userProperty("projectId", project), - ]) - } - - // The signed-in user's id, read off the client's credential in the same order auth uses - // (JWT first, then session) without a network call: the JWT payload's `userId` claim, else - // the `id` in the session secret (standard base64 of `{"id": ..., "secret": ...}`). - private func currentUserId() throws -> String { - // The id comes from the credential the connection authenticates with: the JWT when one - // is set (never the session, which could belong to a different user), else the session. - if let jwt = client.config["jwt"], !jwt.isEmpty { - if let userId = userIdFromJwt(jwt) { - return userId - } - } else if case let signedIn = session(), !signedIn.isEmpty, let userId = userIdFromSession(signedIn) { - return userId - } - throw AppwriteError(message: "subscribe() without a topic needs a signed-in user: sign in with this client, or set a JWT or session on it") - } - - private func open() async throws -> MQTTClient { - // A fresh connect clears any prior deliberate-close flag. - sync.sync { closing = false } - let properties: MQTTProperties - do { - properties = try connectProperties() - } catch { - try report(error) - throw error - } - - // An empty identifier makes the broker derive a stable id server-side (keyed on the - // credential/project) and key its offline-replay cursor on it; Client.setPushClientId(id) - // overrides with an explicit id. Resolved once per instance (see resolvedClientId) so a - // reconnect rebuild reuses the same id and resumes the same session. - let id = resolvedClientId - - var tlsConfiguration: MQTTClient.TLSConfigurationType? - if tls && tlsInsecure { - #if canImport(Network) - tlsConfiguration = .ts(TSTLSConfiguration(certificateVerification: .none)) - #endif - } - - let configuration = MQTTClient.Configuration( - version: .v5_0, - keepAliveInterval: .seconds(Int64(Push.keepAliveSeconds)), - useSSL: tls, - tlsConfiguration: tlsConfiguration - ) - - let mqtt = MQTTClient( - host: host, - port: port, - identifier: id, - eventLoopGroupProvider: .createNew, - configuration: configuration - ) - - // One listener fans every delivery out to the matching local callbacks. - mqtt.addPublishListener(named: "appwrite-push") { [weak self] (result: Result) in - switch result { - case .success(let publish): - self?.dispatch(publish) - case .failure(let error): - self?.surface(Push.describe(error)) - } - } - - // Surface the connection lifecycle to the caller's onClose hook, and recover from an - // unexpected drop (a deliberate close() is skipped via the `closing` flag). - mqtt.addCloseListener(named: "appwrite-push") { [weak self, weak mqtt] result in - if let self, let mqtt, self.sync.sync(execute: { self.retired.remove(ObjectIdentifier(mqtt)) != nil }) { - return - } - if let self, let mqtt, self.sync.sync(execute: { self.closedClients.remove(ObjectIdentifier(mqtt)) != nil }) { - self.onCloseCb?() - return - } - if case .failure(let error) = result { - self?.surface(Push.describe(error)) - } else if let self, !self.sync.sync(execute: { self.closing }) { - // A close nobody asked for, e.g. a DISCONNECT from the broker. MQTTNIO closes - // cleanly then and does not expose the broker's reason string, so report the - // drop itself rather than letting it pass silently. - self.surface(AppwriteError(message: "Connection closed by the broker")) - } - self?.onCloseCb?() - self?.handleUnexpectedClose() - } - - do { - // Clean start is always off, so the broker keeps this client's session and can - // redeliver missed messages to QoS-1 subscriptions on reconnect. - let ack = try await mqtt.v5.connect(cleanStart: false, properties: properties) - if ack.reason != .success { - try? mqtt.syncShutdownGracefully() - throw AppwriteError(message: Push.reasonString(ack.properties) ?? "MQTT authentication failed (CONNACK reason \(ack.reason))") - } - } catch let error as AppwriteError { - try report(error) - throw error - } catch { - // Best-effort cleanup of a client that never connected; the connect error below is - // the one worth reporting. - try? mqtt.syncShutdownGracefully() - let described = AppwriteError(message: Push.brokerMessage(error) ?? error.localizedDescription) - try report(described) - throw described - } - - onOpenCb?() - return mqtt - } - - // Called from the close listener. Starts one reconnect loop for an unexpected drop, unless - // this was a deliberate close(), there are no subscriptions, or a loop is already running. - private func handleUnexpectedClose() { - let client = sync.sync { () -> MQTTClient? in - if closing || reconnecting || subscriptions.isEmpty { - return nil - } - reconnecting = true - return mqtt - } - guard let client else { return } - Task { - await reconnectLoop(client) - sync.sync { self.reconnecting = false } - } - } - - // Reconnect the same client with exponential backoff (capped at 30s) and resubscribe every - // active filter, so an existing subscription resumes delivery without an app-level subscribe. - private func reconnectLoop(_ client: MQTTClient) async { - var delaySeconds: UInt64 = 1 - while true { - // Stop if closed, drained, or the client was replaced by a fresh connect. - if sync.sync(execute: { closing || subscriptions.isEmpty || mqtt !== client }) { - return - } - try? await Task.sleep(nanoseconds: delaySeconds * 1_000_000_000) - if sync.sync(execute: { closing || subscriptions.isEmpty || mqtt !== client }) { - return - } - do { - // Only (re)connect when the client is actually down. If a prior iteration - // connected but then failed to resubscribe, the client is still active, so - // re-connecting it would be a no-op that never restores routing — retry the - // subscribe instead. - if !client.isActive() { - let properties = try connectProperties() - let ack = try await client.v5.connect(cleanStart: false, properties: properties) - if ack.reason != .success { - surface(AppwriteError(message: Push.reasonString(ack.properties) ?? "MQTT authentication failed (CONNACK reason \(ack.reason))")) - delaySeconds = min(delaySeconds * 2, 30) - continue - } - } - let infos = sync.sync { () -> [MQTTSubscribeInfoV5] in - Set(subscriptions.values.map { $0.filter }).map { - MQTTSubscribeInfoV5(topicFilter: $0, qos: effectiveQos($0)) - } - } - // Let a resubscription failure fall through to the retry loop rather than - // reporting a recovery that left the handles without broker routing. - if !infos.isEmpty { - try await brokerSubscribe(client, infos) - } - onOpenCb?() - return - } catch { - // Report each failed attempt, then keep retrying until closed or drained. - surface(Push.describe(error)) - } - delaySeconds = min(delaySeconds * 2, 30) - } - } - - // For a call path that throws to its caller, which does `try report(error); throw error`: - // the error reaches onError when one is registered and the caller still gets it; with no - // callback it is thrown to the caller exactly once. - private func report(_ error: Swift.Error) throws { - guard let callback = onErrorCb else { - throw error - } - callback(error) - } - - // `report` for errors outside any call (listeners on the event loop, fire-and-forget tasks, - // notification callbacks, close()). These are never thrown, so they cannot crash the app: - // they reach onError, and with none registered they are logged to stderr. - private func surface(_ error: Swift.Error) { - guard let callback = onErrorCb else { - FileHandle.standardError.write(Data("Appwrite Push: \(error)\n".utf8)) - return - } - callback(error) - } - - // Run a fire-and-forget broker call (an unsubscribe or re-SUBSCRIBE nobody awaits) and - // report its failure. Failures after a deliberate close() are its own teardown, not errors. - private func inBackground(_ operation: @escaping () async throws -> Void) { - Task { [weak self] in - do { - try await operation() - } catch { - guard let self, !self.sync.sync(execute: { self.closing }) else { return } - self.surface(Push.describe(error)) - } - } - } - - // SUBSCRIBE, throwing when the broker refused a filter (SUBACK reason code 0x80 or above): - // subscribe() then rolls back, reports and throws; background callers report it. - private func brokerSubscribe(_ client: MQTTClient, _ infos: [MQTTSubscribeInfoV5]) async throws { - let suback = try await client.v5.subscribe(to: infos) - if let (info, reason) = zip(infos, suback.reasons).first(where: { $0.1.rawValue >= 0x80 }) { - throw AppwriteError(message: "Subscribe to \"\(info.topicFilter)\" refused by the broker (SUBACK reason \(reason))") - } - } - - // UNSUBSCRIBE, throwing when the broker refused a filter (UNSUBACK reason code 0x80 or above). - private func brokerUnsubscribe(_ client: MQTTClient, _ filters: [String]) async throws { - let unsuback = try await client.v5.unsubscribe(from: filters) - if let (filter, reason) = zip(filters, unsuback.reasons).first(where: { $0.1.rawValue >= 0x80 }) { - throw AppwriteError(message: "Unsubscribe from \"\(filter)\" refused by the broker (UNSUBACK reason \(reason))") - } - } - - // The error onError sees (and a failed call throws) for a library error: a broker error - // gets a readable message (see `brokerMessage`), anything else passes through unchanged. - private static func describe(_ error: Swift.Error) -> Swift.Error { - if let message = brokerMessage(error) { - return AppwriteError(message: message) - } - return error - } - - // The broker explains a refusal or disconnect with the MQTT 5 Reason String property. - private static func reasonString(_ properties: MQTTProperties) -> String? { - for case .reasonString(let value) in properties where !value.isEmpty { - return value - } - return nil - } - - // A readable message for a broker-originated MQTTNIO error, or nil for any other error. - // A server DISCONNECT carries its packet (and so its Reason String). A refused CONNACK - // only reaches us as its reason code: MQTTNIO drops the CONNACK properties when it - // rejects the connection, so its Reason String is not available here. - private static func brokerMessage(_ error: Swift.Error) -> String? { - switch error { - case MQTTError.serverDisconnection(let ack): - return reasonString(ack.properties) ?? "MQTT connection closed by the broker (DISCONNECT reason \(ack.reason))" - case MQTTError.reasonError(let reason): - return "MQTT connection refused (CONNACK reason \(reason))" - default: - return nil - } - } - - private func dispatch(_ publish: MQTTPublishInfo) { - let pushMessage = PushMessage( - topic: publish.topicName, - payload: [UInt8](publish.payload.readableBytesView), - qos: Int(publish.qos.rawValue) - ) - // Notification is per-subscription: only subs that opted in post one, each title once, as - // their callbacks return. A title the server sent replaces theirs, so it is posted once. - let matched = sync.sync { - subscriptions.values.filter { matches(filter: $0.filter, topic: publish.topicName) } - } - let notification = PushNotificationContent(message: pushMessage) - var postedTitles = Set() - for entry in matched { - entry.callback(pushMessage) - let title = notification.title ?? entry.title ?? pushMessage.topic - if entry.background && postedTitles.insert(title).inserted { - notify(pushMessage, title: title, notification: notification) - } - } - } - - private func notify(_ message: PushMessage, title: String, notification: PushNotificationContent) { - #if canImport(UserNotifications) - let content = UNMutableNotificationContent() - content.title = title - content.body = notification.body ?? (notification.present ? "" : message.data) - content.sound = .default - content.userInfo = ["topic": message.topic, "payload": message.data] - guard let image = notification.image.flatMap(URL.init(string:)) else { - post(content) - return - } - Push.downloadAttachment(image) { [weak self] attachment in - if let attachment { - content.attachments = [attachment] - } - self?.post(content) - } - #endif - } - - #if canImport(UserNotifications) - /// The file extension a notification attachment needs for each image type it supports, by MIME type: the - /// attachment's type comes from the file's extension. - private static let imageExtensions = [ - "image/jpeg": "jpg", - "image/jpg": "jpg", - "image/png": "png", - "image/gif": "gif", - "image/heic": "heic", - ] - - private func post(_ content: UNNotificationContent) { - let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil) - UNUserNotificationCenter.current().add(request) { [weak self] error in - if let error { - self?.surface(error) - } - } - } - - /// Download a notification image into a file a notification can attach, or nil when it cannot be fetched or is - /// not an image type notifications show. - private static func downloadAttachment(_ url: URL, completion: @escaping (UNNotificationAttachment?) -> Void) { - URLSession.shared.downloadTask(with: URLRequest(url: url, timeoutInterval: 10)) { location, response, _ in - guard let location, let fileExtension = attachmentExtension(url, mimeType: response?.mimeType) else { - completion(nil) - return - } - let file = FileManager.default.temporaryDirectory - .appendingPathComponent(UUID().uuidString) - .appendingPathExtension(fileExtension) - do { - try FileManager.default.moveItem(at: location, to: file) - completion(try UNNotificationAttachment(identifier: "image", url: file)) - } catch { - completion(nil) - } - }.resume() - } - - /// The extension for an image attachment: from its MIME type, else (an image served without an image MIME - /// type) from the URL when that names a supported image type. The attachment then validates the file. - private static func attachmentExtension(_ url: URL, mimeType: String?) -> String? { - if let fileExtension = imageExtensions[mimeType?.lowercased() ?? ""] { - return fileExtension - } - let urlExtension = url.pathExtension.lowercased() - return Set(imageExtensions.values).union(["jpeg"]).contains(urlExtension) ? urlExtension : nil - } - #endif - -} - -/// What a message's `notification` block asks a background notification to show: nils when the -/// payload has none or is not JSON. -struct PushNotificationContent { - let present: Bool - let title: String? - let body: String? - let image: String? - - init(message: PushMessage) { - let json = (try? JSONSerialization.jsonObject(with: Data(message.payload))) as? [String: Any] - let notification = json?["notification"] as? [String: Any] - present = notification != nil - func field(_ name: String) -> String? { - guard let value = notification?[name] as? String, !value.isEmpty else { return nil } - return value - } - title = field("title") - body = field("body") - image = field("image") - } -} - -/// The `userId` claim of a JWT's payload segment (base64url JSON), or nil when absent. -private func userIdFromJwt(_ jwt: String) -> String? { - let parts = jwt.split(separator: ".", omittingEmptySubsequences: false) - guard parts.count >= 2 else { return nil } - var payload = parts[1].replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") - payload += String(repeating: "=", count: (4 - payload.count % 4) % 4) - return jsonString(base64: payload, key: "userId") -} - -/// The `id` in a session secret (standard base64 of `{"id": ..., "secret": ...}`), or nil. -private func userIdFromSession(_ session: String) -> String? { - jsonString(base64: session, key: "id") -} - -private func jsonString(base64: String, key: String) -> String? { - guard let data = Data(base64Encoded: base64), - let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], - let value = object[key] as? String, !value.isEmpty - else { - return nil - } - return value -} - -/// MQTT topic-filter match with `+` (single level) and `#` (multi level). -private func matches(filter: String, topic: String) -> Bool { - let filterParts = filter.split(separator: "/", omittingEmptySubsequences: false) - let topicParts = topic.split(separator: "/", omittingEmptySubsequences: false) - for (index, part) in filterParts.enumerated() { - if part == "#" { - return true - } - if index >= topicParts.count { - return false - } - if part != "+" && part != topicParts[index] { - return false - } - } - return filterParts.count == topicParts.count -} - -private struct SupersededError: Swift.Error {} diff --git a/Sources/Appwrite/Services/Teams.swift b/Sources/Appwrite/Services/Teams.swift index 50cf929..9e6033a 100644 --- a/Sources/Appwrite/Services/Teams.swift +++ b/Sources/Appwrite/Services/Teams.swift @@ -602,6 +602,7 @@ open class Teams: Service { /// - phone: String (optional) /// - url: String (optional) /// - name: String (optional) + /// - membershipId: String (optional) /// - Throws: Exception if the request fails /// - Returns: AppwriteModels.Membership /// @@ -612,7 +613,8 @@ open class Teams: Service { userId: String? = nil, phone: String? = nil, url: String? = nil, - name: String? = nil + name: String? = nil, + membershipId: String? = nil ) async throws -> AppwriteModels.Membership { if teamId.isEmpty { throw AppwriteError(message: "Missing required parameter: \"teamId\"") @@ -628,6 +630,7 @@ open class Teams: Service { "roles": roles, "url": url, "name": name, + "membershipId": membershipId, ] let apiHeaders: [String: String] = [ diff --git a/Sources/Appwrite/Topic.swift b/Sources/Appwrite/Topic.swift deleted file mode 100644 index 3543d25..0000000 --- a/Sources/Appwrite/Topic.swift +++ /dev/null @@ -1,126 +0,0 @@ -import Foundation - -/// Thrown by `Topic.path(_:)` when a level is invalid. -public struct TopicError: Swift.Error, LocalizedError, CustomStringConvertible { - /// What is wrong with the levels. - public let message: String - - init(_ message: String) { - self.message = message - } - - public var description: String { - return message - } - - public var errorDescription: String? { - return message - } -} - -/// Validate the levels passed to `path(_:)`: a non-empty list of non-empty strings, none holding -/// the level separator `/` or the wildcards `+` and `#` (use `any()` and `all()` for those). -private func levelsOf(_ levels: [String]) throws -> [String] { - if levels.isEmpty { - throw TopicError("path() needs at least one level") - } - for (index, level) in levels.enumerated() { - if level.isEmpty { - throw TopicError("empty level at index \(index)") - } - if level.contains("/") { - let parts = - level - .components(separatedBy: "/") - .map { "'\($0)'" } - .joined(separator: ", ") - throw TopicError("\"\(level)\" contains \"/\", split it: path([\(parts)])") - } - if level == "+" { - throw TopicError("\"+\" is reserved, use any()") - } - if level.contains("+") { - throw TopicError("\"\(level)\" contains \"+\", use any() for wildcards") - } - if level == "#" { - throw TopicError("\"#\" is reserved, use all()") - } - if level.contains("#") { - throw TopicError("\"\(level)\" contains \"#\", use all() for wildcards") - } - } - return levels -} - -/// Helper to build MQTT topics for `Push`, level by level. -/// -/// try Topic.path(["user", userId, "notification"]) // "user/123/notification" -/// try Topic.path(["user"]).any().path(["notification"]) // "user/+/notification" -/// try Topic.path(["org"]).any().path(["logs"]).all() // "org/+/logs/#" -/// -/// `any()` matches exactly one level and `all()` everything below, at any depth (including the -/// parent itself). `all()` ends the topic, so it returns a `ResolvedTopic`. -public final class Topic: CustomStringConvertible, Sendable { - private let levels: [String] - - private init(_ levels: [String]) { - self.levels = levels - } - - /// Start a topic with the given levels, e.g. `try Topic.path(["user", userId])`. - public static func path(_ levels: [String]) throws -> Topic { - return Topic(try levelsOf(levels)) - } - - /// Start a topic with a single-level wildcard (`+`). - public static func any() -> Topic { - return Topic(["+"]) - } - - /// The multi-level wildcard alone (`#`): matches every topic. - public static func all() -> ResolvedTopic { - return ResolvedTopic(["#"]) - } - - /// Append the given levels. - public func path(_ levels: [String]) throws -> Topic { - return Topic(self.levels + (try levelsOf(levels))) - } - - /// Append a single-level wildcard (`+`): matches exactly one level. - public func any() -> Topic { - return Topic(levels + ["+"]) - } - - /// Append the multi-level wildcard (`#`) and end the topic. - public func all() -> ResolvedTopic { - return ResolvedTopic(levels + ["#"]) - } - - /// The topic string, levels joined with `/`. - public func toString() -> String { - return levels.joined(separator: "/") - } - - public var description: String { - return toString() - } -} - -/// A topic ended by `all()`: nothing can be appended after the `#` wildcard. -public final class ResolvedTopic: CustomStringConvertible, Sendable { - private let levels: [String] - - fileprivate init(_ levels: [String]) { - self.levels = levels - } - - /// The topic string, levels joined with `/`. - public func toString() -> String { - return levels.joined(separator: "/") - } - - public var description: String { - return toString() - } -} diff --git a/Sources/AppwriteModels/Account.swift b/Sources/AppwriteModels/Account.swift index 07773be..9616d34 100644 --- a/Sources/AppwriteModels/Account.swift +++ b/Sources/AppwriteModels/Account.swift @@ -135,28 +135,28 @@ open class Account: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.name = try container.decode(String.self, forKey: .name) - self.registration = try container.decode(String.self, forKey: .registration) - self.status = try container.decode(Bool.self, forKey: .status) - self.labels = try container.decode([String].self, forKey: .labels) - self.passwordUpdate = try container.decode(String.self, forKey: .passwordUpdate) - self.email = try container.decode(String.self, forKey: .email) - self.phone = try container.decode(String.self, forKey: .phone) - self.emailVerification = try container.decode(Bool.self, forKey: .emailVerification) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" + self.registration = try container.contains(.registration) ? container.decode(String.self, forKey: .registration) : "" + self.status = try container.contains(.status) ? container.decode(Bool.self, forKey: .status) : true + self.labels = try container.contains(.labels) ? container.decode([String].self, forKey: .labels) : [] + self.passwordUpdate = try container.contains(.passwordUpdate) ? container.decode(String.self, forKey: .passwordUpdate) : "" + self.email = try container.contains(.email) ? container.decode(String.self, forKey: .email) : "" + self.phone = try container.contains(.phone) ? container.decode(String.self, forKey: .phone) : "" + self.emailVerification = try container.contains(.emailVerification) ? container.decode(Bool.self, forKey: .emailVerification) : false self.emailCanonical = try container.decodeIfPresent(String.self, forKey: .emailCanonical) self.emailIsFree = try container.decodeIfPresent(Bool.self, forKey: .emailIsFree) self.emailIsDisposable = try container.decodeIfPresent(Bool.self, forKey: .emailIsDisposable) self.emailIsCorporate = try container.decodeIfPresent(Bool.self, forKey: .emailIsCorporate) self.emailIsCanonical = try container.decodeIfPresent(Bool.self, forKey: .emailIsCanonical) self.passwordPwned = try container.decodeIfPresent(Bool.self, forKey: .passwordPwned) - self.phoneVerification = try container.decode(Bool.self, forKey: .phoneVerification) - self.mfa = try container.decode(Bool.self, forKey: .mfa) + self.phoneVerification = try container.contains(.phoneVerification) ? container.decode(Bool.self, forKey: .phoneVerification) : false + self.mfa = try container.contains(.mfa) ? container.decode(Bool.self, forKey: .mfa) : false self.prefs = try container.decode(Preferences.self, forKey: .prefs) - self.targets = try container.decode([Target].self, forKey: .targets) - self.accessedAt = try container.decode(String.self, forKey: .accessedAt) + self.targets = try container.contains(.targets) ? container.decode([Target].self, forKey: .targets) : [] + self.accessedAt = try container.contains(.accessedAt) ? container.decode(String.self, forKey: .accessedAt) : "" self.impersonator = try container.decodeIfPresent(Bool.self, forKey: .impersonator) self.impersonatorUserId = try container.decodeIfPresent(String.self, forKey: .impersonatorUserId) } @@ -220,6 +220,25 @@ open class Account: Codable { } public static func from(map: [String: Any]) -> Account { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "name": "", + "registration": "", + "status": true, + "labels": [Any](), + "passwordUpdate": "", + "email": "", + "phone": "", + "emailVerification": false, + "phoneVerification": false, + "mfa": false, + "targets": [Any](), + "accessedAt": "", + ] + let map = defaults.merging(map) { _, new in new } + return Account( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/AlgoArgon2.swift b/Sources/AppwriteModels/AlgoArgon2.swift index 9eae6a5..e2bf066 100644 --- a/Sources/AppwriteModels/AlgoArgon2.swift +++ b/Sources/AppwriteModels/AlgoArgon2.swift @@ -35,10 +35,10 @@ open class AlgoArgon2: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.type = try container.decode(String.self, forKey: .type) - self.memoryCost = try container.decode(Int.self, forKey: .memoryCost) - self.timeCost = try container.decode(Int.self, forKey: .timeCost) - self.threads = try container.decode(Int.self, forKey: .threads) + self.type = try container.contains(.type) ? container.decode(String.self, forKey: .type) : "argon2" + self.memoryCost = try container.contains(.memoryCost) ? container.decode(Int.self, forKey: .memoryCost) : 0 + self.timeCost = try container.contains(.timeCost) ? container.decode(Int.self, forKey: .timeCost) : 0 + self.threads = try container.contains(.threads) ? container.decode(Int.self, forKey: .threads) : 0 } public func encode(to encoder: Encoder) throws { @@ -60,6 +60,14 @@ open class AlgoArgon2: Codable { } public static func from(map: [String: Any]) -> AlgoArgon2 { + let defaults: [String: Any] = [ + "type": "argon2", + "memoryCost": 0, + "timeCost": 0, + "threads": 0, + ] + let map = defaults.merging(map) { _, new in new } + return AlgoArgon2( type: map["type"] as! String, memoryCost: map["memoryCost"] as! Int, diff --git a/Sources/AppwriteModels/AlgoBcrypt.swift b/Sources/AppwriteModels/AlgoBcrypt.swift index 484860e..2393190 100644 --- a/Sources/AppwriteModels/AlgoBcrypt.swift +++ b/Sources/AppwriteModels/AlgoBcrypt.swift @@ -20,7 +20,7 @@ open class AlgoBcrypt: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.type = try container.decode(String.self, forKey: .type) + self.type = try container.contains(.type) ? container.decode(String.self, forKey: .type) : "bcrypt" } public func encode(to encoder: Encoder) throws { @@ -36,6 +36,9 @@ open class AlgoBcrypt: Codable { } public static func from(map: [String: Any]) -> AlgoBcrypt { + let defaults: [String: Any] = ["type": "bcrypt"] + let map = defaults.merging(map) { _, new in new } + return AlgoBcrypt( type: map["type"] as! String ) diff --git a/Sources/AppwriteModels/AlgoMd5.swift b/Sources/AppwriteModels/AlgoMd5.swift index d7e2613..20ba9cb 100644 --- a/Sources/AppwriteModels/AlgoMd5.swift +++ b/Sources/AppwriteModels/AlgoMd5.swift @@ -20,7 +20,7 @@ open class AlgoMd5: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.type = try container.decode(String.self, forKey: .type) + self.type = try container.contains(.type) ? container.decode(String.self, forKey: .type) : "md5" } public func encode(to encoder: Encoder) throws { @@ -36,6 +36,9 @@ open class AlgoMd5: Codable { } public static func from(map: [String: Any]) -> AlgoMd5 { + let defaults: [String: Any] = ["type": "md5"] + let map = defaults.merging(map) { _, new in new } + return AlgoMd5( type: map["type"] as! String ) diff --git a/Sources/AppwriteModels/AlgoPhpass.swift b/Sources/AppwriteModels/AlgoPhpass.swift index 90b31ce..0c2de32 100644 --- a/Sources/AppwriteModels/AlgoPhpass.swift +++ b/Sources/AppwriteModels/AlgoPhpass.swift @@ -20,7 +20,7 @@ open class AlgoPhpass: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.type = try container.decode(String.self, forKey: .type) + self.type = try container.contains(.type) ? container.decode(String.self, forKey: .type) : "phpass" } public func encode(to encoder: Encoder) throws { @@ -36,6 +36,9 @@ open class AlgoPhpass: Codable { } public static func from(map: [String: Any]) -> AlgoPhpass { + let defaults: [String: Any] = ["type": "phpass"] + let map = defaults.merging(map) { _, new in new } + return AlgoPhpass( type: map["type"] as! String ) diff --git a/Sources/AppwriteModels/AlgoScrypt.swift b/Sources/AppwriteModels/AlgoScrypt.swift index c3323f3..8f86d21 100644 --- a/Sources/AppwriteModels/AlgoScrypt.swift +++ b/Sources/AppwriteModels/AlgoScrypt.swift @@ -40,11 +40,11 @@ open class AlgoScrypt: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.type = try container.decode(String.self, forKey: .type) - self.costCpu = try container.decode(Int.self, forKey: .costCpu) - self.costMemory = try container.decode(Int.self, forKey: .costMemory) - self.costParallel = try container.decode(Int.self, forKey: .costParallel) - self.length = try container.decode(Int.self, forKey: .length) + self.type = try container.contains(.type) ? container.decode(String.self, forKey: .type) : "scrypt" + self.costCpu = try container.contains(.costCpu) ? container.decode(Int.self, forKey: .costCpu) : 8 + self.costMemory = try container.contains(.costMemory) ? container.decode(Int.self, forKey: .costMemory) : 14 + self.costParallel = try container.contains(.costParallel) ? container.decode(Int.self, forKey: .costParallel) : 1 + self.length = try container.contains(.length) ? container.decode(Int.self, forKey: .length) : 64 } public func encode(to encoder: Encoder) throws { @@ -68,6 +68,15 @@ open class AlgoScrypt: Codable { } public static func from(map: [String: Any]) -> AlgoScrypt { + let defaults: [String: Any] = [ + "type": "scrypt", + "costCpu": 8, + "costMemory": 14, + "costParallel": 1, + "length": 64, + ] + let map = defaults.merging(map) { _, new in new } + return AlgoScrypt( type: map["type"] as! String, costCpu: map["costCpu"] as! Int, diff --git a/Sources/AppwriteModels/AlgoScryptModified.swift b/Sources/AppwriteModels/AlgoScryptModified.swift index 71fb8b6..fda1626 100644 --- a/Sources/AppwriteModels/AlgoScryptModified.swift +++ b/Sources/AppwriteModels/AlgoScryptModified.swift @@ -35,10 +35,10 @@ open class AlgoScryptModified: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.type = try container.decode(String.self, forKey: .type) - self.salt = try container.decode(String.self, forKey: .salt) - self.saltSeparator = try container.decode(String.self, forKey: .saltSeparator) - self.signerKey = try container.decode(String.self, forKey: .signerKey) + self.type = try container.contains(.type) ? container.decode(String.self, forKey: .type) : "scryptMod" + self.salt = try container.contains(.salt) ? container.decode(String.self, forKey: .salt) : "" + self.saltSeparator = try container.contains(.saltSeparator) ? container.decode(String.self, forKey: .saltSeparator) : "" + self.signerKey = try container.contains(.signerKey) ? container.decode(String.self, forKey: .signerKey) : "" } public func encode(to encoder: Encoder) throws { @@ -60,6 +60,14 @@ open class AlgoScryptModified: Codable { } public static func from(map: [String: Any]) -> AlgoScryptModified { + let defaults: [String: Any] = [ + "type": "scryptMod", + "salt": "", + "saltSeparator": "", + "signerKey": "", + ] + let map = defaults.merging(map) { _, new in new } + return AlgoScryptModified( type: map["type"] as! String, salt: map["salt"] as! String, diff --git a/Sources/AppwriteModels/AlgoSha.swift b/Sources/AppwriteModels/AlgoSha.swift index 54b4831..a7aafc9 100644 --- a/Sources/AppwriteModels/AlgoSha.swift +++ b/Sources/AppwriteModels/AlgoSha.swift @@ -20,7 +20,7 @@ open class AlgoSha: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.type = try container.decode(String.self, forKey: .type) + self.type = try container.contains(.type) ? container.decode(String.self, forKey: .type) : "sha" } public func encode(to encoder: Encoder) throws { @@ -36,6 +36,9 @@ open class AlgoSha: Codable { } public static func from(map: [String: Any]) -> AlgoSha { + let defaults: [String: Any] = ["type": "sha"] + let map = defaults.merging(map) { _, new in new } + return AlgoSha( type: map["type"] as! String ) diff --git a/Sources/AppwriteModels/App.swift b/Sources/AppwriteModels/App.swift index 706ae75..4abcc78 100644 --- a/Sources/AppwriteModels/App.swift +++ b/Sources/AppwriteModels/App.swift @@ -145,32 +145,32 @@ open class App: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.name = try container.decode(String.self, forKey: .name) - self.description = try container.decode(String.self, forKey: .description) - self.clientUri = try container.decode(String.self, forKey: .clientUri) - self.logoUri = try container.decode(String.self, forKey: .logoUri) - self.privacyPolicyUrl = try container.decode(String.self, forKey: .privacyPolicyUrl) - self.termsUrl = try container.decode(String.self, forKey: .termsUrl) - self.contacts = try container.decode([String].self, forKey: .contacts) - self.tagline = try container.decode(String.self, forKey: .tagline) - self.tags = try container.decode([String].self, forKey: .tags) - self.labels = try container.decode([String].self, forKey: .labels) - self.images = try container.decode([String].self, forKey: .images) - self.supportUrl = try container.decode(String.self, forKey: .supportUrl) - self.dataDeletionUrl = try container.decode(String.self, forKey: .dataDeletionUrl) - self.redirectUris = try container.decode([String].self, forKey: .redirectUris) - self.postLogoutRedirectUris = try container.decode([String].self, forKey: .postLogoutRedirectUris) - self.enabled = try container.decode(Bool.self, forKey: .enabled) - self.type = try container.decode(String.self, forKey: .type) - self.deviceFlow = try container.decode(Bool.self, forKey: .deviceFlow) - self.teamId = try container.decode(String.self, forKey: .teamId) - self.userId = try container.decode(String.self, forKey: .userId) - self.installationScopes = try container.decode([String].self, forKey: .installationScopes) - self.installationRedirectUrl = try container.decode(String.self, forKey: .installationRedirectUrl) - self.secrets = try container.decode([AppSecret].self, forKey: .secrets) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" + self.description = try container.contains(.description) ? container.decode(String.self, forKey: .description) : "" + self.clientUri = try container.contains(.clientUri) ? container.decode(String.self, forKey: .clientUri) : "" + self.logoUri = try container.contains(.logoUri) ? container.decode(String.self, forKey: .logoUri) : "" + self.privacyPolicyUrl = try container.contains(.privacyPolicyUrl) ? container.decode(String.self, forKey: .privacyPolicyUrl) : "" + self.termsUrl = try container.contains(.termsUrl) ? container.decode(String.self, forKey: .termsUrl) : "" + self.contacts = try container.contains(.contacts) ? container.decode([String].self, forKey: .contacts) : [] + self.tagline = try container.contains(.tagline) ? container.decode(String.self, forKey: .tagline) : "" + self.tags = try container.contains(.tags) ? container.decode([String].self, forKey: .tags) : [] + self.labels = try container.contains(.labels) ? container.decode([String].self, forKey: .labels) : [] + self.images = try container.contains(.images) ? container.decode([String].self, forKey: .images) : [] + self.supportUrl = try container.contains(.supportUrl) ? container.decode(String.self, forKey: .supportUrl) : "" + self.dataDeletionUrl = try container.contains(.dataDeletionUrl) ? container.decode(String.self, forKey: .dataDeletionUrl) : "" + self.redirectUris = try container.contains(.redirectUris) ? container.decode([String].self, forKey: .redirectUris) : [] + self.postLogoutRedirectUris = try container.contains(.postLogoutRedirectUris) ? container.decode([String].self, forKey: .postLogoutRedirectUris) : [] + self.enabled = try container.contains(.enabled) ? container.decode(Bool.self, forKey: .enabled) : true + self.type = try container.contains(.type) ? container.decode(String.self, forKey: .type) : "confidential" + self.deviceFlow = try container.contains(.deviceFlow) ? container.decode(Bool.self, forKey: .deviceFlow) : false + self.teamId = try container.contains(.teamId) ? container.decode(String.self, forKey: .teamId) : "" + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" + self.installationScopes = try container.contains(.installationScopes) ? container.decode([String].self, forKey: .installationScopes) : [] + self.installationRedirectUrl = try container.contains(.installationRedirectUrl) ? container.decode(String.self, forKey: .installationRedirectUrl) : "" + self.secrets = try container.contains(.secrets) ? container.decode([AppSecret].self, forKey: .secrets) : [] } public func encode(to encoder: Encoder) throws { @@ -236,6 +236,36 @@ open class App: Codable { } public static func from(map: [String: Any]) -> App { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "name": "", + "description": "", + "clientUri": "", + "logoUri": "", + "privacyPolicyUrl": "", + "termsUrl": "", + "contacts": [Any](), + "tagline": "", + "tags": [Any](), + "labels": [Any](), + "images": [Any](), + "supportUrl": "", + "dataDeletionUrl": "", + "redirectUris": [Any](), + "postLogoutRedirectUris": [Any](), + "enabled": true, + "type": "confidential", + "deviceFlow": false, + "teamId": "", + "userId": "", + "installationScopes": [Any](), + "installationRedirectUrl": "", + "secrets": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return App( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/AppInstallation.swift b/Sources/AppwriteModels/AppInstallation.swift index 140feb1..af5b15d 100644 --- a/Sources/AppwriteModels/AppInstallation.swift +++ b/Sources/AppwriteModels/AppInstallation.swift @@ -65,15 +65,15 @@ open class AppInstallation: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.appId = try container.decode(String.self, forKey: .appId) - self.teamId = try container.decode(String.self, forKey: .teamId) - self.scopes = try container.decode([String].self, forKey: .scopes) - self.authorizationDetails = try container.decode([AnyCodable].self, forKey: .authorizationDetails) - self.createdById = try container.decode(String.self, forKey: .createdById) - self.createdByName = try container.decode(String.self, forKey: .createdByName) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.appId = try container.contains(.appId) ? container.decode(String.self, forKey: .appId) : "" + self.teamId = try container.contains(.teamId) ? container.decode(String.self, forKey: .teamId) : "" + self.scopes = try container.contains(.scopes) ? container.decode([String].self, forKey: .scopes) : [] + self.authorizationDetails = try container.contains(.authorizationDetails) ? container.decode([AnyCodable].self, forKey: .authorizationDetails) : [] + self.createdById = try container.contains(.createdById) ? container.decode(String.self, forKey: .createdById) : "" + self.createdByName = try container.contains(.createdByName) ? container.decode(String.self, forKey: .createdByName) : "" self.lastAccessedAt = try container.decodeIfPresent(String.self, forKey: .lastAccessedAt) } @@ -108,6 +108,19 @@ open class AppInstallation: Codable { } public static func from(map: [String: Any]) -> AppInstallation { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "appId": "", + "teamId": "", + "scopes": [Any](), + "authorizationDetails": [Any](), + "createdById": "", + "createdByName": "", + ] + let map = defaults.merging(map) { _, new in new } + return AppInstallation( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/AppInstallationList.swift b/Sources/AppwriteModels/AppInstallationList.swift index 63e9835..4c15a61 100644 --- a/Sources/AppwriteModels/AppInstallationList.swift +++ b/Sources/AppwriteModels/AppInstallationList.swift @@ -25,8 +25,8 @@ open class AppInstallationList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.installations = try container.decode([AppInstallation].self, forKey: .installations) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.installations = try container.contains(.installations) ? container.decode([AppInstallation].self, forKey: .installations) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class AppInstallationList: Codable { } public static func from(map: [String: Any]) -> AppInstallationList { + let defaults: [String: Any] = [ + "total": 0, + "installations": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return AppInstallationList( total: map["total"] as! Int, installations: (map["installations"] as! [[String: Any]]).map { AppInstallation.from(map: $0) } diff --git a/Sources/AppwriteModels/AppKey.swift b/Sources/AppwriteModels/AppKey.swift index e8937fc..a43ab5c 100644 --- a/Sources/AppwriteModels/AppKey.swift +++ b/Sources/AppwriteModels/AppKey.swift @@ -60,14 +60,14 @@ open class AppKey: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.appId = try container.decode(String.self, forKey: .appId) - self.secret = try container.decode(String.self, forKey: .secret) - self.hint = try container.decode(String.self, forKey: .hint) - self.createdById = try container.decode(String.self, forKey: .createdById) - self.createdByName = try container.decode(String.self, forKey: .createdByName) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.appId = try container.contains(.appId) ? container.decode(String.self, forKey: .appId) : "" + self.secret = try container.contains(.secret) ? container.decode(String.self, forKey: .secret) : "" + self.hint = try container.contains(.hint) ? container.decode(String.self, forKey: .hint) : "" + self.createdById = try container.contains(.createdById) ? container.decode(String.self, forKey: .createdById) : "" + self.createdByName = try container.contains(.createdByName) ? container.decode(String.self, forKey: .createdByName) : "" self.lastAccessedAt = try container.decodeIfPresent(String.self, forKey: .lastAccessedAt) } @@ -100,6 +100,18 @@ open class AppKey: Codable { } public static func from(map: [String: Any]) -> AppKey { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "appId": "", + "secret": "", + "hint": "", + "createdById": "", + "createdByName": "", + ] + let map = defaults.merging(map) { _, new in new } + return AppKey( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/AppKeyList.swift b/Sources/AppwriteModels/AppKeyList.swift index 65b6523..7bdd335 100644 --- a/Sources/AppwriteModels/AppKeyList.swift +++ b/Sources/AppwriteModels/AppKeyList.swift @@ -25,8 +25,8 @@ open class AppKeyList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.keys = try container.decode([AppKey].self, forKey: .keys) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.keys = try container.contains(.keys) ? container.decode([AppKey].self, forKey: .keys) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class AppKeyList: Codable { } public static func from(map: [String: Any]) -> AppKeyList { + let defaults: [String: Any] = [ + "total": 0, + "keys": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return AppKeyList( total: map["total"] as! Int, keys: (map["keys"] as! [[String: Any]]).map { AppKey.from(map: $0) } diff --git a/Sources/AppwriteModels/AppScope.swift b/Sources/AppwriteModels/AppScope.swift index 4edfb89..6919f6e 100644 --- a/Sources/AppwriteModels/AppScope.swift +++ b/Sources/AppwriteModels/AppScope.swift @@ -40,11 +40,11 @@ open class AppScope: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.value = try container.decode(String.self, forKey: .value) - self.description = try container.decode(String.self, forKey: .description) - self.type = try container.decode(String.self, forKey: .type) - self.category = try container.decode(String.self, forKey: .category) - self.deprecated = try container.decode(Bool.self, forKey: .deprecated) + self.value = try container.contains(.value) ? container.decode(String.self, forKey: .value) : "" + self.description = try container.contains(.description) ? container.decode(String.self, forKey: .description) : "" + self.type = try container.contains(.type) ? container.decode(String.self, forKey: .type) : "" + self.category = try container.contains(.category) ? container.decode(String.self, forKey: .category) : "" + self.deprecated = try container.contains(.deprecated) ? container.decode(Bool.self, forKey: .deprecated) : false } public func encode(to encoder: Encoder) throws { @@ -68,6 +68,15 @@ open class AppScope: Codable { } public static func from(map: [String: Any]) -> AppScope { + let defaults: [String: Any] = [ + "value": "", + "description": "", + "type": "", + "category": "", + "deprecated": false, + ] + let map = defaults.merging(map) { _, new in new } + return AppScope( value: map["value"] as! String, description: map["description"] as! String, diff --git a/Sources/AppwriteModels/AppScopeList.swift b/Sources/AppwriteModels/AppScopeList.swift index 1d76a56..0ff365c 100644 --- a/Sources/AppwriteModels/AppScopeList.swift +++ b/Sources/AppwriteModels/AppScopeList.swift @@ -25,8 +25,8 @@ open class AppScopeList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.scopes = try container.decode([AppScope].self, forKey: .scopes) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.scopes = try container.contains(.scopes) ? container.decode([AppScope].self, forKey: .scopes) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class AppScopeList: Codable { } public static func from(map: [String: Any]) -> AppScopeList { + let defaults: [String: Any] = [ + "total": 0, + "scopes": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return AppScopeList( total: map["total"] as! Int, scopes: (map["scopes"] as! [[String: Any]]).map { AppScope.from(map: $0) } diff --git a/Sources/AppwriteModels/AppSecret.swift b/Sources/AppwriteModels/AppSecret.swift index cd6ccae..181dc0b 100644 --- a/Sources/AppwriteModels/AppSecret.swift +++ b/Sources/AppwriteModels/AppSecret.swift @@ -60,14 +60,14 @@ open class AppSecret: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.appId = try container.decode(String.self, forKey: .appId) - self.secret = try container.decode(String.self, forKey: .secret) - self.hint = try container.decode(String.self, forKey: .hint) - self.createdById = try container.decode(String.self, forKey: .createdById) - self.createdByName = try container.decode(String.self, forKey: .createdByName) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.appId = try container.contains(.appId) ? container.decode(String.self, forKey: .appId) : "" + self.secret = try container.contains(.secret) ? container.decode(String.self, forKey: .secret) : "" + self.hint = try container.contains(.hint) ? container.decode(String.self, forKey: .hint) : "" + self.createdById = try container.contains(.createdById) ? container.decode(String.self, forKey: .createdById) : "" + self.createdByName = try container.contains(.createdByName) ? container.decode(String.self, forKey: .createdByName) : "" self.lastAccessedAt = try container.decodeIfPresent(String.self, forKey: .lastAccessedAt) } @@ -100,6 +100,18 @@ open class AppSecret: Codable { } public static func from(map: [String: Any]) -> AppSecret { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "appId": "", + "secret": "", + "hint": "", + "createdById": "", + "createdByName": "", + ] + let map = defaults.merging(map) { _, new in new } + return AppSecret( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/AppSecretList.swift b/Sources/AppwriteModels/AppSecretList.swift index c266941..3b09b57 100644 --- a/Sources/AppwriteModels/AppSecretList.swift +++ b/Sources/AppwriteModels/AppSecretList.swift @@ -25,8 +25,8 @@ open class AppSecretList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.secrets = try container.decode([AppSecret].self, forKey: .secrets) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.secrets = try container.contains(.secrets) ? container.decode([AppSecret].self, forKey: .secrets) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class AppSecretList: Codable { } public static func from(map: [String: Any]) -> AppSecretList { + let defaults: [String: Any] = [ + "total": 0, + "secrets": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return AppSecretList( total: map["total"] as! Int, secrets: (map["secrets"] as! [[String: Any]]).map { AppSecret.from(map: $0) } diff --git a/Sources/AppwriteModels/AppSecretPlaintext.swift b/Sources/AppwriteModels/AppSecretPlaintext.swift index 5d98b54..06aa620 100644 --- a/Sources/AppwriteModels/AppSecretPlaintext.swift +++ b/Sources/AppwriteModels/AppSecretPlaintext.swift @@ -60,14 +60,14 @@ open class AppSecretPlaintext: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.appId = try container.decode(String.self, forKey: .appId) - self.secret = try container.decode(String.self, forKey: .secret) - self.hint = try container.decode(String.self, forKey: .hint) - self.createdById = try container.decode(String.self, forKey: .createdById) - self.createdByName = try container.decode(String.self, forKey: .createdByName) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.appId = try container.contains(.appId) ? container.decode(String.self, forKey: .appId) : "" + self.secret = try container.contains(.secret) ? container.decode(String.self, forKey: .secret) : "" + self.hint = try container.contains(.hint) ? container.decode(String.self, forKey: .hint) : "" + self.createdById = try container.contains(.createdById) ? container.decode(String.self, forKey: .createdById) : "" + self.createdByName = try container.contains(.createdByName) ? container.decode(String.self, forKey: .createdByName) : "" self.lastAccessedAt = try container.decodeIfPresent(String.self, forKey: .lastAccessedAt) } @@ -100,6 +100,18 @@ open class AppSecretPlaintext: Codable { } public static func from(map: [String: Any]) -> AppSecretPlaintext { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "appId": "", + "secret": "", + "hint": "", + "createdById": "", + "createdByName": "", + ] + let map = defaults.merging(map) { _, new in new } + return AppSecretPlaintext( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/AppsList.swift b/Sources/AppwriteModels/AppsList.swift index 963168c..4110cd7 100644 --- a/Sources/AppwriteModels/AppsList.swift +++ b/Sources/AppwriteModels/AppsList.swift @@ -25,8 +25,8 @@ open class AppsList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.apps = try container.decode([App].self, forKey: .apps) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.apps = try container.contains(.apps) ? container.decode([App].self, forKey: .apps) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class AppsList: Codable { } public static func from(map: [String: Any]) -> AppsList { + let defaults: [String: Any] = [ + "total": 0, + "apps": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return AppsList( total: map["total"] as! Int, apps: (map["apps"] as! [[String: Any]]).map { App.from(map: $0) } diff --git a/Sources/AppwriteModels/Continent.swift b/Sources/AppwriteModels/Continent.swift index d0434ad..66a6eb2 100644 --- a/Sources/AppwriteModels/Continent.swift +++ b/Sources/AppwriteModels/Continent.swift @@ -25,8 +25,8 @@ open class Continent: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.name = try container.decode(String.self, forKey: .name) - self.code = try container.decode(String.self, forKey: .code) + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" + self.code = try container.contains(.code) ? container.decode(String.self, forKey: .code) : "" } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class Continent: Codable { } public static func from(map: [String: Any]) -> Continent { + let defaults: [String: Any] = [ + "name": "", + "code": "", + ] + let map = defaults.merging(map) { _, new in new } + return Continent( name: map["name"] as! String, code: map["code"] as! String diff --git a/Sources/AppwriteModels/ContinentList.swift b/Sources/AppwriteModels/ContinentList.swift index 3738f48..d9d962a 100644 --- a/Sources/AppwriteModels/ContinentList.swift +++ b/Sources/AppwriteModels/ContinentList.swift @@ -25,8 +25,8 @@ open class ContinentList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.continents = try container.decode([Continent].self, forKey: .continents) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.continents = try container.contains(.continents) ? container.decode([Continent].self, forKey: .continents) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class ContinentList: Codable { } public static func from(map: [String: Any]) -> ContinentList { + let defaults: [String: Any] = [ + "total": 0, + "continents": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return ContinentList( total: map["total"] as! Int, continents: (map["continents"] as! [[String: Any]]).map { Continent.from(map: $0) } diff --git a/Sources/AppwriteModels/Country.swift b/Sources/AppwriteModels/Country.swift index 90daca1..26bfbf0 100644 --- a/Sources/AppwriteModels/Country.swift +++ b/Sources/AppwriteModels/Country.swift @@ -25,8 +25,8 @@ open class Country: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.name = try container.decode(String.self, forKey: .name) - self.code = try container.decode(String.self, forKey: .code) + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" + self.code = try container.contains(.code) ? container.decode(String.self, forKey: .code) : "" } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class Country: Codable { } public static func from(map: [String: Any]) -> Country { + let defaults: [String: Any] = [ + "name": "", + "code": "", + ] + let map = defaults.merging(map) { _, new in new } + return Country( name: map["name"] as! String, code: map["code"] as! String diff --git a/Sources/AppwriteModels/CountryList.swift b/Sources/AppwriteModels/CountryList.swift index 252fa68..7f37298 100644 --- a/Sources/AppwriteModels/CountryList.swift +++ b/Sources/AppwriteModels/CountryList.swift @@ -25,8 +25,8 @@ open class CountryList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.countries = try container.decode([Country].self, forKey: .countries) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.countries = try container.contains(.countries) ? container.decode([Country].self, forKey: .countries) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class CountryList: Codable { } public static func from(map: [String: Any]) -> CountryList { + let defaults: [String: Any] = [ + "total": 0, + "countries": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return CountryList( total: map["total"] as! Int, countries: (map["countries"] as! [[String: Any]]).map { Country.from(map: $0) } diff --git a/Sources/AppwriteModels/Currency.swift b/Sources/AppwriteModels/Currency.swift index ebfe800..b4a0acf 100644 --- a/Sources/AppwriteModels/Currency.swift +++ b/Sources/AppwriteModels/Currency.swift @@ -50,13 +50,13 @@ open class Currency: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.symbol = try container.decode(String.self, forKey: .symbol) - self.name = try container.decode(String.self, forKey: .name) - self.symbolNative = try container.decode(String.self, forKey: .symbolNative) - self.decimalDigits = try container.decode(Int.self, forKey: .decimalDigits) - self.rounding = try container.decode(Double.self, forKey: .rounding) - self.code = try container.decode(String.self, forKey: .code) - self.namePlural = try container.decode(String.self, forKey: .namePlural) + self.symbol = try container.contains(.symbol) ? container.decode(String.self, forKey: .symbol) : "" + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" + self.symbolNative = try container.contains(.symbolNative) ? container.decode(String.self, forKey: .symbolNative) : "" + self.decimalDigits = try container.contains(.decimalDigits) ? container.decode(Int.self, forKey: .decimalDigits) : 0 + self.rounding = try container.contains(.rounding) ? container.decode(Double.self, forKey: .rounding) : 0 + self.code = try container.contains(.code) ? container.decode(String.self, forKey: .code) : "" + self.namePlural = try container.contains(.namePlural) ? container.decode(String.self, forKey: .namePlural) : "" } public func encode(to encoder: Encoder) throws { @@ -84,6 +84,17 @@ open class Currency: Codable { } public static func from(map: [String: Any]) -> Currency { + let defaults: [String: Any] = [ + "symbol": "", + "name": "", + "symbolNative": "", + "decimalDigits": 0, + "rounding": 0.0, + "code": "", + "namePlural": "", + ] + let map = defaults.merging(map) { _, new in new } + return Currency( symbol: map["symbol"] as! String, name: map["name"] as! String, diff --git a/Sources/AppwriteModels/CurrencyList.swift b/Sources/AppwriteModels/CurrencyList.swift index 64b7841..ff816b5 100644 --- a/Sources/AppwriteModels/CurrencyList.swift +++ b/Sources/AppwriteModels/CurrencyList.swift @@ -25,8 +25,8 @@ open class CurrencyList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.currencies = try container.decode([Currency].self, forKey: .currencies) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.currencies = try container.contains(.currencies) ? container.decode([Currency].self, forKey: .currencies) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class CurrencyList: Codable { } public static func from(map: [String: Any]) -> CurrencyList { + let defaults: [String: Any] = [ + "total": 0, + "currencies": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return CurrencyList( total: map["total"] as! Int, currencies: (map["currencies"] as! [[String: Any]]).map { Currency.from(map: $0) } diff --git a/Sources/AppwriteModels/Document.swift b/Sources/AppwriteModels/Document.swift index d551bd1..8bf53ed 100644 --- a/Sources/AppwriteModels/Document.swift +++ b/Sources/AppwriteModels/Document.swift @@ -55,13 +55,13 @@ open class Document: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.sequence = try container.decode(String.self, forKey: .sequence) - self.collectionId = try container.decode(String.self, forKey: .collectionId) - self.databaseId = try container.decode(String.self, forKey: .databaseId) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.permissions = try container.decode([String].self, forKey: .permissions) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.sequence = try container.contains(.sequence) ? container.decode(String.self, forKey: .sequence) : "" + self.collectionId = try container.contains(.collectionId) ? container.decode(String.self, forKey: .collectionId) : "" + self.databaseId = try container.contains(.databaseId) ? container.decode(String.self, forKey: .databaseId) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.permissions = try container.contains(.permissions) ? container.decode([String].self, forKey: .permissions) : [] self.data = try container.decode(T.self, forKey: .data) } @@ -92,6 +92,17 @@ open class Document: Codable { } public static func from(map: [String: Any]) -> Document { + let defaults: [String: Any] = [ + "$id": "", + "$sequence": "", + "$collectionId": "", + "$databaseId": "", + "$createdAt": "", + "$updatedAt": "", + "$permissions": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return Document( id: map["$id"] as? String ?? "", sequence: map["$sequence"] as? String ?? "", diff --git a/Sources/AppwriteModels/DocumentList.swift b/Sources/AppwriteModels/DocumentList.swift index ea3f589..b7ff1ce 100644 --- a/Sources/AppwriteModels/DocumentList.swift +++ b/Sources/AppwriteModels/DocumentList.swift @@ -25,8 +25,8 @@ open class DocumentList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.documents = try container.decode([Document].self, forKey: .documents) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.documents = try container.contains(.documents) ? container.decode([Document].self, forKey: .documents) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class DocumentList: Codable { } public static func from(map: [String: Any]) -> DocumentList { + let defaults: [String: Any] = [ + "total": 0, + "documents": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return DocumentList( total: map["total"] as! Int, documents: (map["documents"] as! [[String: Any]]).map { Document.from(map: $0) } diff --git a/Sources/AppwriteModels/Execution.swift b/Sources/AppwriteModels/Execution.swift index 1eefd1f..60d75ec 100644 --- a/Sources/AppwriteModels/Execution.swift +++ b/Sources/AppwriteModels/Execution.swift @@ -111,24 +111,24 @@ open class Execution: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.permissions = try container.decode([String].self, forKey: .permissions) - self.resourceId = try container.decode(String.self, forKey: .resourceId) - self.resourceType = AppwriteEnums.ExecutionResourceType(rawValue: try container.decode(String.self, forKey: .resourceType))! - self.deploymentId = try container.decode(String.self, forKey: .deploymentId) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.permissions = try container.contains(.permissions) ? container.decode([String].self, forKey: .permissions) : [] + self.resourceId = try container.contains(.resourceId) ? container.decode(String.self, forKey: .resourceId) : "" + self.resourceType = AppwriteEnums.ExecutionResourceType(rawValue: try container.contains(.resourceType) ? container.decode(String.self, forKey: .resourceType) : "functions")! + self.deploymentId = try container.contains(.deploymentId) ? container.decode(String.self, forKey: .deploymentId) : "" self.trigger = AppwriteEnums.ExecutionTrigger(rawValue: try container.decode(String.self, forKey: .trigger))! self.status = AppwriteEnums.ExecutionStatus(rawValue: try container.decode(String.self, forKey: .status))! - self.requestMethod = try container.decode(String.self, forKey: .requestMethod) - self.requestPath = try container.decode(String.self, forKey: .requestPath) - self.requestHeaders = try container.decode([Headers].self, forKey: .requestHeaders) - self.responseStatusCode = try container.decode(Int.self, forKey: .responseStatusCode) - self.responseBody = try container.decode(String.self, forKey: .responseBody) - self.responseHeaders = try container.decode([Headers].self, forKey: .responseHeaders) - self.logs = try container.decode(String.self, forKey: .logs) - self.errors = try container.decode(String.self, forKey: .errors) - self.duration = try container.decode(Double.self, forKey: .duration) + self.requestMethod = try container.contains(.requestMethod) ? container.decode(String.self, forKey: .requestMethod) : "" + self.requestPath = try container.contains(.requestPath) ? container.decode(String.self, forKey: .requestPath) : "" + self.requestHeaders = try container.contains(.requestHeaders) ? container.decode([Headers].self, forKey: .requestHeaders) : [] + self.responseStatusCode = try container.contains(.responseStatusCode) ? container.decode(Int.self, forKey: .responseStatusCode) : 0 + self.responseBody = try container.contains(.responseBody) ? container.decode(String.self, forKey: .responseBody) : "" + self.responseHeaders = try container.contains(.responseHeaders) ? container.decode([Headers].self, forKey: .responseHeaders) : [] + self.logs = try container.contains(.logs) ? container.decode(String.self, forKey: .logs) : "" + self.errors = try container.contains(.errors) ? container.decode(String.self, forKey: .errors) : "" + self.duration = try container.contains(.duration) ? container.decode(Double.self, forKey: .duration) : 0 self.scheduledAt = try container.decodeIfPresent(String.self, forKey: .scheduledAt) } @@ -181,6 +181,26 @@ open class Execution: Codable { } public static func from(map: [String: Any]) -> Execution { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "$permissions": [Any](), + "resourceId": "", + "resourceType": "functions", + "deploymentId": "", + "requestMethod": "", + "requestPath": "", + "requestHeaders": [Any](), + "responseStatusCode": 0, + "responseBody": "", + "responseHeaders": [Any](), + "logs": "", + "errors": "", + "duration": 0.0, + ] + let map = defaults.merging(map) { _, new in new } + return Execution( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/ExecutionList.swift b/Sources/AppwriteModels/ExecutionList.swift index e26b285..fe09b2c 100644 --- a/Sources/AppwriteModels/ExecutionList.swift +++ b/Sources/AppwriteModels/ExecutionList.swift @@ -25,8 +25,8 @@ open class ExecutionList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.executions = try container.decode([Execution].self, forKey: .executions) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.executions = try container.contains(.executions) ? container.decode([Execution].self, forKey: .executions) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class ExecutionList: Codable { } public static func from(map: [String: Any]) -> ExecutionList { + let defaults: [String: Any] = [ + "total": 0, + "executions": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return ExecutionList( total: map["total"] as! Int, executions: (map["executions"] as! [[String: Any]]).map { Execution.from(map: $0) } diff --git a/Sources/AppwriteModels/File.swift b/Sources/AppwriteModels/File.swift index e97e48a..eb2ccb4 100644 --- a/Sources/AppwriteModels/File.swift +++ b/Sources/AppwriteModels/File.swift @@ -95,22 +95,22 @@ open class File: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.bucketId = try container.decode(String.self, forKey: .bucketId) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.permissions = try container.decode([String].self, forKey: .permissions) - self.name = try container.decode(String.self, forKey: .name) - self.folder = try container.decode(String.self, forKey: .folder) - self.key = try container.decode(String.self, forKey: .key) - self.signature = try container.decode(String.self, forKey: .signature) - self.mimeType = try container.decode(String.self, forKey: .mimeType) - self.sizeOriginal = try container.decode(Int.self, forKey: .sizeOriginal) - self.sizeActual = try container.decode(Int.self, forKey: .sizeActual) - self.chunksTotal = try container.decode(Int.self, forKey: .chunksTotal) - self.chunksUploaded = try container.decode(Int.self, forKey: .chunksUploaded) - self.encryption = try container.decode(Bool.self, forKey: .encryption) - self.compression = try container.decode(String.self, forKey: .compression) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.bucketId = try container.contains(.bucketId) ? container.decode(String.self, forKey: .bucketId) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.permissions = try container.contains(.permissions) ? container.decode([String].self, forKey: .permissions) : [] + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" + self.folder = try container.contains(.folder) ? container.decode(String.self, forKey: .folder) : "" + self.key = try container.contains(.key) ? container.decode(String.self, forKey: .key) : "" + self.signature = try container.contains(.signature) ? container.decode(String.self, forKey: .signature) : "" + self.mimeType = try container.contains(.mimeType) ? container.decode(String.self, forKey: .mimeType) : "" + self.sizeOriginal = try container.contains(.sizeOriginal) ? container.decode(Int.self, forKey: .sizeOriginal) : 0 + self.sizeActual = try container.contains(.sizeActual) ? container.decode(Int.self, forKey: .sizeActual) : 0 + self.chunksTotal = try container.contains(.chunksTotal) ? container.decode(Int.self, forKey: .chunksTotal) : 0 + self.chunksUploaded = try container.contains(.chunksUploaded) ? container.decode(Int.self, forKey: .chunksUploaded) : 0 + self.encryption = try container.contains(.encryption) ? container.decode(Bool.self, forKey: .encryption) : false + self.compression = try container.contains(.compression) ? container.decode(String.self, forKey: .compression) : "none" } public func encode(to encoder: Encoder) throws { @@ -156,6 +156,26 @@ open class File: Codable { } public static func from(map: [String: Any]) -> File { + let defaults: [String: Any] = [ + "$id": "", + "bucketId": "", + "$createdAt": "", + "$updatedAt": "", + "$permissions": [Any](), + "name": "", + "folder": "", + "key": "", + "signature": "", + "mimeType": "", + "sizeOriginal": 0, + "sizeActual": 0, + "chunksTotal": 0, + "chunksUploaded": 0, + "encryption": false, + "compression": "none", + ] + let map = defaults.merging(map) { _, new in new } + return File( id: map["$id"] as! String, bucketId: map["bucketId"] as! String, diff --git a/Sources/AppwriteModels/FileList.swift b/Sources/AppwriteModels/FileList.swift index 6565130..be40e32 100644 --- a/Sources/AppwriteModels/FileList.swift +++ b/Sources/AppwriteModels/FileList.swift @@ -25,8 +25,8 @@ open class FileList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.files = try container.decode([File].self, forKey: .files) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.files = try container.contains(.files) ? container.decode([File].self, forKey: .files) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class FileList: Codable { } public static func from(map: [String: Any]) -> FileList { + let defaults: [String: Any] = [ + "total": 0, + "files": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return FileList( total: map["total"] as! Int, files: (map["files"] as! [[String: Any]]).map { File.from(map: $0) } diff --git a/Sources/AppwriteModels/Headers.swift b/Sources/AppwriteModels/Headers.swift index a409e07..6660cd3 100644 --- a/Sources/AppwriteModels/Headers.swift +++ b/Sources/AppwriteModels/Headers.swift @@ -25,8 +25,8 @@ open class Headers: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.name = try container.decode(String.self, forKey: .name) - self.value = try container.decode(String.self, forKey: .value) + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" + self.value = try container.contains(.value) ? container.decode(String.self, forKey: .value) : "" } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class Headers: Codable { } public static func from(map: [String: Any]) -> Headers { + let defaults: [String: Any] = [ + "name": "", + "value": "", + ] + let map = defaults.merging(map) { _, new in new } + return Headers( name: map["name"] as! String, value: map["value"] as! String diff --git a/Sources/AppwriteModels/Identity.swift b/Sources/AppwriteModels/Identity.swift index 5c785c7..3c50c6a 100644 --- a/Sources/AppwriteModels/Identity.swift +++ b/Sources/AppwriteModels/Identity.swift @@ -70,17 +70,17 @@ open class Identity: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.userId = try container.decode(String.self, forKey: .userId) - self.provider = try container.decode(String.self, forKey: .provider) - self.providerUid = try container.decode(String.self, forKey: .providerUid) - self.providerEmail = try container.decode(String.self, forKey: .providerEmail) - self.providerAccessToken = try container.decode(String.self, forKey: .providerAccessToken) - self.providerAccessTokenExpiry = try container.decode(String.self, forKey: .providerAccessTokenExpiry) - self.providerRefreshToken = try container.decode(String.self, forKey: .providerRefreshToken) - self.providerIdToken = try container.decode(String.self, forKey: .providerIdToken) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" + self.provider = try container.contains(.provider) ? container.decode(String.self, forKey: .provider) : "" + self.providerUid = try container.contains(.providerUid) ? container.decode(String.self, forKey: .providerUid) : "" + self.providerEmail = try container.contains(.providerEmail) ? container.decode(String.self, forKey: .providerEmail) : "" + self.providerAccessToken = try container.contains(.providerAccessToken) ? container.decode(String.self, forKey: .providerAccessToken) : "" + self.providerAccessTokenExpiry = try container.contains(.providerAccessTokenExpiry) ? container.decode(String.self, forKey: .providerAccessTokenExpiry) : "" + self.providerRefreshToken = try container.contains(.providerRefreshToken) ? container.decode(String.self, forKey: .providerRefreshToken) : "" + self.providerIdToken = try container.contains(.providerIdToken) ? container.decode(String.self, forKey: .providerIdToken) : "" } public func encode(to encoder: Encoder) throws { @@ -116,6 +116,21 @@ open class Identity: Codable { } public static func from(map: [String: Any]) -> Identity { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "userId": "", + "provider": "", + "providerUid": "", + "providerEmail": "", + "providerAccessToken": "", + "providerAccessTokenExpiry": "", + "providerRefreshToken": "", + "providerIdToken": "", + ] + let map = defaults.merging(map) { _, new in new } + return Identity( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/IdentityList.swift b/Sources/AppwriteModels/IdentityList.swift index 2e3f874..01fd013 100644 --- a/Sources/AppwriteModels/IdentityList.swift +++ b/Sources/AppwriteModels/IdentityList.swift @@ -25,8 +25,8 @@ open class IdentityList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.identities = try container.decode([Identity].self, forKey: .identities) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.identities = try container.contains(.identities) ? container.decode([Identity].self, forKey: .identities) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class IdentityList: Codable { } public static func from(map: [String: Any]) -> IdentityList { + let defaults: [String: Any] = [ + "total": 0, + "identities": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return IdentityList( total: map["total"] as! Int, identities: (map["identities"] as! [[String: Any]]).map { Identity.from(map: $0) } diff --git a/Sources/AppwriteModels/Jwt.swift b/Sources/AppwriteModels/Jwt.swift index 78160e4..a45ca1f 100644 --- a/Sources/AppwriteModels/Jwt.swift +++ b/Sources/AppwriteModels/Jwt.swift @@ -20,7 +20,7 @@ open class Jwt: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.jwt = try container.decode(String.self, forKey: .jwt) + self.jwt = try container.contains(.jwt) ? container.decode(String.self, forKey: .jwt) : "" } public func encode(to encoder: Encoder) throws { @@ -36,6 +36,9 @@ open class Jwt: Codable { } public static func from(map: [String: Any]) -> Jwt { + let defaults: [String: Any] = ["jwt": ""] + let map = defaults.merging(map) { _, new in new } + return Jwt( jwt: map["jwt"] as! String ) diff --git a/Sources/AppwriteModels/Language.swift b/Sources/AppwriteModels/Language.swift index 9c9d0dc..8f4370f 100644 --- a/Sources/AppwriteModels/Language.swift +++ b/Sources/AppwriteModels/Language.swift @@ -30,9 +30,9 @@ open class Language: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.name = try container.decode(String.self, forKey: .name) - self.code = try container.decode(String.self, forKey: .code) - self.nativeName = try container.decode(String.self, forKey: .nativeName) + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" + self.code = try container.contains(.code) ? container.decode(String.self, forKey: .code) : "" + self.nativeName = try container.contains(.nativeName) ? container.decode(String.self, forKey: .nativeName) : "" } public func encode(to encoder: Encoder) throws { @@ -52,6 +52,13 @@ open class Language: Codable { } public static func from(map: [String: Any]) -> Language { + let defaults: [String: Any] = [ + "name": "", + "code": "", + "nativeName": "", + ] + let map = defaults.merging(map) { _, new in new } + return Language( name: map["name"] as! String, code: map["code"] as! String, diff --git a/Sources/AppwriteModels/LanguageList.swift b/Sources/AppwriteModels/LanguageList.swift index 861ee63..2a082bd 100644 --- a/Sources/AppwriteModels/LanguageList.swift +++ b/Sources/AppwriteModels/LanguageList.swift @@ -25,8 +25,8 @@ open class LanguageList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.languages = try container.decode([Language].self, forKey: .languages) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.languages = try container.contains(.languages) ? container.decode([Language].self, forKey: .languages) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class LanguageList: Codable { } public static func from(map: [String: Any]) -> LanguageList { + let defaults: [String: Any] = [ + "total": 0, + "languages": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return LanguageList( total: map["total"] as! Int, languages: (map["languages"] as! [[String: Any]]).map { Language.from(map: $0) } diff --git a/Sources/AppwriteModels/Locale.swift b/Sources/AppwriteModels/Locale.swift index cf26870..cf5a674 100644 --- a/Sources/AppwriteModels/Locale.swift +++ b/Sources/AppwriteModels/Locale.swift @@ -105,13 +105,13 @@ open class Locale: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.ip = try container.decode(String.self, forKey: .ip) - self.countryCode = try container.decode(String.self, forKey: .countryCode) - self.country = try container.decode(String.self, forKey: .country) - self.continentCode = try container.decode(String.self, forKey: .continentCode) - self.continent = try container.decode(String.self, forKey: .continent) - self.eu = try container.decode(Bool.self, forKey: .eu) - self.currency = try container.decode(String.self, forKey: .currency) + self.ip = try container.contains(.ip) ? container.decode(String.self, forKey: .ip) : "" + self.countryCode = try container.contains(.countryCode) ? container.decode(String.self, forKey: .countryCode) : "" + self.country = try container.contains(.country) ? container.decode(String.self, forKey: .country) : "" + self.continentCode = try container.contains(.continentCode) ? container.decode(String.self, forKey: .continentCode) : "" + self.continent = try container.contains(.continent) ? container.decode(String.self, forKey: .continent) : "" + self.eu = try container.contains(.eu) ? container.decode(Bool.self, forKey: .eu) : false + self.currency = try container.contains(.currency) ? container.decode(String.self, forKey: .currency) : "" self.city = try container.decodeIfPresent(String.self, forKey: .city) self.timeZone = try container.decodeIfPresent(String.self, forKey: .timeZone) self.postalCode = try container.decodeIfPresent(String.self, forKey: .postalCode) @@ -172,6 +172,17 @@ open class Locale: Codable { } public static func from(map: [String: Any]) -> Locale { + let defaults: [String: Any] = [ + "ip": "", + "countryCode": "", + "country": "", + "continentCode": "", + "continent": "", + "eu": false, + "currency": "", + ] + let map = defaults.merging(map) { _, new in new } + return Locale( ip: map["ip"] as! String, countryCode: map["countryCode"] as! String, diff --git a/Sources/AppwriteModels/LocaleCode.swift b/Sources/AppwriteModels/LocaleCode.swift index beaa5a1..8aaa369 100644 --- a/Sources/AppwriteModels/LocaleCode.swift +++ b/Sources/AppwriteModels/LocaleCode.swift @@ -25,8 +25,8 @@ open class LocaleCode: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.code = try container.decode(String.self, forKey: .code) - self.name = try container.decode(String.self, forKey: .name) + self.code = try container.contains(.code) ? container.decode(String.self, forKey: .code) : "" + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class LocaleCode: Codable { } public static func from(map: [String: Any]) -> LocaleCode { + let defaults: [String: Any] = [ + "code": "", + "name": "", + ] + let map = defaults.merging(map) { _, new in new } + return LocaleCode( code: map["code"] as! String, name: map["name"] as! String diff --git a/Sources/AppwriteModels/LocaleCodeList.swift b/Sources/AppwriteModels/LocaleCodeList.swift index 2556128..edd7e95 100644 --- a/Sources/AppwriteModels/LocaleCodeList.swift +++ b/Sources/AppwriteModels/LocaleCodeList.swift @@ -25,8 +25,8 @@ open class LocaleCodeList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.localeCodes = try container.decode([LocaleCode].self, forKey: .localeCodes) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.localeCodes = try container.contains(.localeCodes) ? container.decode([LocaleCode].self, forKey: .localeCodes) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class LocaleCodeList: Codable { } public static func from(map: [String: Any]) -> LocaleCodeList { + let defaults: [String: Any] = [ + "total": 0, + "localeCodes": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return LocaleCodeList( total: map["total"] as! Int, localeCodes: (map["localeCodes"] as! [[String: Any]]).map { LocaleCode.from(map: $0) } diff --git a/Sources/AppwriteModels/Membership.swift b/Sources/AppwriteModels/Membership.swift index 70db9cf..1dc530e 100644 --- a/Sources/AppwriteModels/Membership.swift +++ b/Sources/AppwriteModels/Membership.swift @@ -90,21 +90,21 @@ open class Membership: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.userId = try container.decode(String.self, forKey: .userId) - self.userName = try container.decode(String.self, forKey: .userName) - self.userEmail = try container.decode(String.self, forKey: .userEmail) - self.userPhone = try container.decode(String.self, forKey: .userPhone) - self.teamId = try container.decode(String.self, forKey: .teamId) - self.teamName = try container.decode(String.self, forKey: .teamName) - self.invited = try container.decode(String.self, forKey: .invited) - self.joined = try container.decode(String.self, forKey: .joined) - self.confirm = try container.decode(Bool.self, forKey: .confirm) - self.mfa = try container.decode(Bool.self, forKey: .mfa) - self.userAccessedAt = try container.decode(String.self, forKey: .userAccessedAt) - self.roles = try container.decode([String].self, forKey: .roles) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" + self.userName = try container.contains(.userName) ? container.decode(String.self, forKey: .userName) : "" + self.userEmail = try container.contains(.userEmail) ? container.decode(String.self, forKey: .userEmail) : "" + self.userPhone = try container.contains(.userPhone) ? container.decode(String.self, forKey: .userPhone) : "" + self.teamId = try container.contains(.teamId) ? container.decode(String.self, forKey: .teamId) : "" + self.teamName = try container.contains(.teamName) ? container.decode(String.self, forKey: .teamName) : "" + self.invited = try container.contains(.invited) ? container.decode(String.self, forKey: .invited) : "" + self.joined = try container.contains(.joined) ? container.decode(String.self, forKey: .joined) : "" + self.confirm = try container.contains(.confirm) ? container.decode(Bool.self, forKey: .confirm) : false + self.mfa = try container.contains(.mfa) ? container.decode(Bool.self, forKey: .mfa) : false + self.userAccessedAt = try container.contains(.userAccessedAt) ? container.decode(String.self, forKey: .userAccessedAt) : "" + self.roles = try container.contains(.roles) ? container.decode([String].self, forKey: .roles) : [] } public func encode(to encoder: Encoder) throws { @@ -148,6 +148,25 @@ open class Membership: Codable { } public static func from(map: [String: Any]) -> Membership { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "userId": "", + "userName": "", + "userEmail": "", + "userPhone": "", + "teamId": "", + "teamName": "", + "invited": "", + "joined": "", + "confirm": false, + "mfa": false, + "userAccessedAt": "", + "roles": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return Membership( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/MembershipList.swift b/Sources/AppwriteModels/MembershipList.swift index 8d738cd..5268328 100644 --- a/Sources/AppwriteModels/MembershipList.swift +++ b/Sources/AppwriteModels/MembershipList.swift @@ -25,8 +25,8 @@ open class MembershipList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.memberships = try container.decode([Membership].self, forKey: .memberships) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.memberships = try container.contains(.memberships) ? container.decode([Membership].self, forKey: .memberships) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class MembershipList: Codable { } public static func from(map: [String: Any]) -> MembershipList { + let defaults: [String: Any] = [ + "total": 0, + "memberships": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return MembershipList( total: map["total"] as! Int, memberships: (map["memberships"] as! [[String: Any]]).map { Membership.from(map: $0) } diff --git a/Sources/AppwriteModels/MfaChallenge.swift b/Sources/AppwriteModels/MfaChallenge.swift index de83aa6..db386c4 100644 --- a/Sources/AppwriteModels/MfaChallenge.swift +++ b/Sources/AppwriteModels/MfaChallenge.swift @@ -35,10 +35,10 @@ open class MfaChallenge: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.userId = try container.decode(String.self, forKey: .userId) - self.expire = try container.decode(String.self, forKey: .expire) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" + self.expire = try container.contains(.expire) ? container.decode(String.self, forKey: .expire) : "" } public func encode(to encoder: Encoder) throws { @@ -60,6 +60,14 @@ open class MfaChallenge: Codable { } public static func from(map: [String: Any]) -> MfaChallenge { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "userId": "", + "expire": "", + ] + let map = defaults.merging(map) { _, new in new } + return MfaChallenge( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/MfaFactors.swift b/Sources/AppwriteModels/MfaFactors.swift index 65a293b..18533a5 100644 --- a/Sources/AppwriteModels/MfaFactors.swift +++ b/Sources/AppwriteModels/MfaFactors.swift @@ -40,11 +40,11 @@ open class MfaFactors: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.totp = try container.decode(Bool.self, forKey: .totp) - self.phone = try container.decode(Bool.self, forKey: .phone) - self.email = try container.decode(Bool.self, forKey: .email) - self.recoveryCode = try container.decode(Bool.self, forKey: .recoveryCode) - self.custom = try container.decode(Bool.self, forKey: .custom) + self.totp = try container.contains(.totp) ? container.decode(Bool.self, forKey: .totp) : false + self.phone = try container.contains(.phone) ? container.decode(Bool.self, forKey: .phone) : false + self.email = try container.contains(.email) ? container.decode(Bool.self, forKey: .email) : false + self.recoveryCode = try container.contains(.recoveryCode) ? container.decode(Bool.self, forKey: .recoveryCode) : false + self.custom = try container.contains(.custom) ? container.decode(Bool.self, forKey: .custom) : false } public func encode(to encoder: Encoder) throws { @@ -68,6 +68,15 @@ open class MfaFactors: Codable { } public static func from(map: [String: Any]) -> MfaFactors { + let defaults: [String: Any] = [ + "totp": false, + "phone": false, + "email": false, + "recoveryCode": false, + "custom": false, + ] + let map = defaults.merging(map) { _, new in new } + return MfaFactors( totp: map["totp"] as! Bool, phone: map["phone"] as! Bool, diff --git a/Sources/AppwriteModels/MfaRecoveryCodes.swift b/Sources/AppwriteModels/MfaRecoveryCodes.swift index 43a5675..e8167aa 100644 --- a/Sources/AppwriteModels/MfaRecoveryCodes.swift +++ b/Sources/AppwriteModels/MfaRecoveryCodes.swift @@ -20,7 +20,7 @@ open class MfaRecoveryCodes: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.recoveryCodes = try container.decode([String].self, forKey: .recoveryCodes) + self.recoveryCodes = try container.contains(.recoveryCodes) ? container.decode([String].self, forKey: .recoveryCodes) : [] } public func encode(to encoder: Encoder) throws { @@ -36,6 +36,9 @@ open class MfaRecoveryCodes: Codable { } public static func from(map: [String: Any]) -> MfaRecoveryCodes { + let defaults: [String: Any] = ["recoveryCodes": [Any]()] + let map = defaults.merging(map) { _, new in new } + return MfaRecoveryCodes( recoveryCodes: map["recoveryCodes"] as! [String] ) diff --git a/Sources/AppwriteModels/MfaType.swift b/Sources/AppwriteModels/MfaType.swift index 68d3ae2..51e24de 100644 --- a/Sources/AppwriteModels/MfaType.swift +++ b/Sources/AppwriteModels/MfaType.swift @@ -25,8 +25,8 @@ open class MfaType: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.secret = try container.decode(String.self, forKey: .secret) - self.uri = try container.decode(String.self, forKey: .uri) + self.secret = try container.contains(.secret) ? container.decode(String.self, forKey: .secret) : "" + self.uri = try container.contains(.uri) ? container.decode(String.self, forKey: .uri) : "" } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class MfaType: Codable { } public static func from(map: [String: Any]) -> MfaType { + let defaults: [String: Any] = [ + "secret": "", + "uri": "", + ] + let map = defaults.merging(map) { _, new in new } + return MfaType( secret: map["secret"] as! String, uri: map["uri"] as! String diff --git a/Sources/AppwriteModels/Oauth2Approve.swift b/Sources/AppwriteModels/Oauth2Approve.swift index adf1c12..93b3dea 100644 --- a/Sources/AppwriteModels/Oauth2Approve.swift +++ b/Sources/AppwriteModels/Oauth2Approve.swift @@ -20,7 +20,7 @@ open class Oauth2Approve: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.redirectUrl = try container.decode(String.self, forKey: .redirectUrl) + self.redirectUrl = try container.contains(.redirectUrl) ? container.decode(String.self, forKey: .redirectUrl) : "" } public func encode(to encoder: Encoder) throws { @@ -36,6 +36,9 @@ open class Oauth2Approve: Codable { } public static func from(map: [String: Any]) -> Oauth2Approve { + let defaults: [String: Any] = ["redirectUrl": ""] + let map = defaults.merging(map) { _, new in new } + return Oauth2Approve( redirectUrl: map["redirectUrl"] as! String ) diff --git a/Sources/AppwriteModels/Oauth2Authorize.swift b/Sources/AppwriteModels/Oauth2Authorize.swift index e6b078f..8665701 100644 --- a/Sources/AppwriteModels/Oauth2Authorize.swift +++ b/Sources/AppwriteModels/Oauth2Authorize.swift @@ -25,8 +25,8 @@ open class Oauth2Authorize: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.grantId = try container.decode(String.self, forKey: .grantId) - self.redirectUrl = try container.decode(String.self, forKey: .redirectUrl) + self.grantId = try container.contains(.grantId) ? container.decode(String.self, forKey: .grantId) : "" + self.redirectUrl = try container.contains(.redirectUrl) ? container.decode(String.self, forKey: .redirectUrl) : "" } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class Oauth2Authorize: Codable { } public static func from(map: [String: Any]) -> Oauth2Authorize { + let defaults: [String: Any] = [ + "grantId": "", + "redirectUrl": "", + ] + let map = defaults.merging(map) { _, new in new } + return Oauth2Authorize( grantId: map["grantId"] as! String, redirectUrl: map["redirectUrl"] as! String diff --git a/Sources/AppwriteModels/Oauth2Consent.swift b/Sources/AppwriteModels/Oauth2Consent.swift index 79d97f9..452fd97 100644 --- a/Sources/AppwriteModels/Oauth2Consent.swift +++ b/Sources/AppwriteModels/Oauth2Consent.swift @@ -65,16 +65,16 @@ open class Oauth2Consent: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.userId = try container.decode(String.self, forKey: .userId) - self.appId = try container.decode(String.self, forKey: .appId) - self.cimdUrl = try container.decode(String.self, forKey: .cimdUrl) - self.scopes = try container.decode([String].self, forKey: .scopes) - self.resources = try container.decode([String].self, forKey: .resources) - self.authorizationDetails = try container.decode(String.self, forKey: .authorizationDetails) - self.expire = try container.decode(String.self, forKey: .expire) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" + self.appId = try container.contains(.appId) ? container.decode(String.self, forKey: .appId) : "" + self.cimdUrl = try container.contains(.cimdUrl) ? container.decode(String.self, forKey: .cimdUrl) : "" + self.scopes = try container.contains(.scopes) ? container.decode([String].self, forKey: .scopes) : [] + self.resources = try container.contains(.resources) ? container.decode([String].self, forKey: .resources) : [] + self.authorizationDetails = try container.contains(.authorizationDetails) ? container.decode(String.self, forKey: .authorizationDetails) : "[]" + self.expire = try container.contains(.expire) ? container.decode(String.self, forKey: .expire) : "" } public func encode(to encoder: Encoder) throws { @@ -108,6 +108,20 @@ open class Oauth2Consent: Codable { } public static func from(map: [String: Any]) -> Oauth2Consent { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "userId": "", + "appId": "", + "cimdUrl": "", + "scopes": [Any](), + "resources": [Any](), + "authorizationDetails": "[]", + "expire": "", + ] + let map = defaults.merging(map) { _, new in new } + return Oauth2Consent( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/Oauth2ConsentList.swift b/Sources/AppwriteModels/Oauth2ConsentList.swift index 03678d3..92c3eb8 100644 --- a/Sources/AppwriteModels/Oauth2ConsentList.swift +++ b/Sources/AppwriteModels/Oauth2ConsentList.swift @@ -25,8 +25,8 @@ open class Oauth2ConsentList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.consents = try container.decode([Oauth2Consent].self, forKey: .consents) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.consents = try container.contains(.consents) ? container.decode([Oauth2Consent].self, forKey: .consents) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class Oauth2ConsentList: Codable { } public static func from(map: [String: Any]) -> Oauth2ConsentList { + let defaults: [String: Any] = [ + "total": 0, + "consents": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return Oauth2ConsentList( total: map["total"] as! Int, consents: (map["consents"] as! [[String: Any]]).map { Oauth2Consent.from(map: $0) } diff --git a/Sources/AppwriteModels/Oauth2ConsentToken.swift b/Sources/AppwriteModels/Oauth2ConsentToken.swift index 04ab05c..d8aaa24 100644 --- a/Sources/AppwriteModels/Oauth2ConsentToken.swift +++ b/Sources/AppwriteModels/Oauth2ConsentToken.swift @@ -70,17 +70,17 @@ open class Oauth2ConsentToken: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.consentId = try container.decode(String.self, forKey: .consentId) - self.userId = try container.decode(String.self, forKey: .userId) - self.appId = try container.decode(String.self, forKey: .appId) - self.cimdUrl = try container.decode(String.self, forKey: .cimdUrl) - self.scopes = try container.decode([String].self, forKey: .scopes) - self.resources = try container.decode([String].self, forKey: .resources) - self.authorizationDetails = try container.decode(String.self, forKey: .authorizationDetails) - self.expire = try container.decode(String.self, forKey: .expire) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.consentId = try container.contains(.consentId) ? container.decode(String.self, forKey: .consentId) : "" + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" + self.appId = try container.contains(.appId) ? container.decode(String.self, forKey: .appId) : "" + self.cimdUrl = try container.contains(.cimdUrl) ? container.decode(String.self, forKey: .cimdUrl) : "" + self.scopes = try container.contains(.scopes) ? container.decode([String].self, forKey: .scopes) : [] + self.resources = try container.contains(.resources) ? container.decode([String].self, forKey: .resources) : [] + self.authorizationDetails = try container.contains(.authorizationDetails) ? container.decode(String.self, forKey: .authorizationDetails) : "[]" + self.expire = try container.contains(.expire) ? container.decode(String.self, forKey: .expire) : "" } public func encode(to encoder: Encoder) throws { @@ -116,6 +116,21 @@ open class Oauth2ConsentToken: Codable { } public static func from(map: [String: Any]) -> Oauth2ConsentToken { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "consentId": "", + "userId": "", + "appId": "", + "cimdUrl": "", + "scopes": [Any](), + "resources": [Any](), + "authorizationDetails": "[]", + "expire": "", + ] + let map = defaults.merging(map) { _, new in new } + return Oauth2ConsentToken( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/Oauth2ConsentTokenList.swift b/Sources/AppwriteModels/Oauth2ConsentTokenList.swift index 45a6dae..405dba2 100644 --- a/Sources/AppwriteModels/Oauth2ConsentTokenList.swift +++ b/Sources/AppwriteModels/Oauth2ConsentTokenList.swift @@ -25,8 +25,8 @@ open class Oauth2ConsentTokenList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.tokens = try container.decode([Oauth2ConsentToken].self, forKey: .tokens) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.tokens = try container.contains(.tokens) ? container.decode([Oauth2ConsentToken].self, forKey: .tokens) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class Oauth2ConsentTokenList: Codable { } public static func from(map: [String: Any]) -> Oauth2ConsentTokenList { + let defaults: [String: Any] = [ + "total": 0, + "tokens": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return Oauth2ConsentTokenList( total: map["total"] as! Int, tokens: (map["tokens"] as! [[String: Any]]).map { Oauth2ConsentToken.from(map: $0) } diff --git a/Sources/AppwriteModels/Oauth2DeviceAuthorization.swift b/Sources/AppwriteModels/Oauth2DeviceAuthorization.swift index 2e1c35e..1cca425 100644 --- a/Sources/AppwriteModels/Oauth2DeviceAuthorization.swift +++ b/Sources/AppwriteModels/Oauth2DeviceAuthorization.swift @@ -45,12 +45,12 @@ open class Oauth2DeviceAuthorization: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.device_code = try container.decode(String.self, forKey: .device_code) - self.user_code = try container.decode(String.self, forKey: .user_code) - self.verification_uri = try container.decode(String.self, forKey: .verification_uri) - self.verification_uri_complete = try container.decode(String.self, forKey: .verification_uri_complete) - self.expires_in = try container.decode(Int.self, forKey: .expires_in) - self.interval = try container.decode(Int.self, forKey: .interval) + self.device_code = try container.contains(.device_code) ? container.decode(String.self, forKey: .device_code) : "" + self.user_code = try container.contains(.user_code) ? container.decode(String.self, forKey: .user_code) : "" + self.verification_uri = try container.contains(.verification_uri) ? container.decode(String.self, forKey: .verification_uri) : "" + self.verification_uri_complete = try container.contains(.verification_uri_complete) ? container.decode(String.self, forKey: .verification_uri_complete) : "" + self.expires_in = try container.contains(.expires_in) ? container.decode(Int.self, forKey: .expires_in) : 0 + self.interval = try container.contains(.interval) ? container.decode(Int.self, forKey: .interval) : 0 } public func encode(to encoder: Encoder) throws { @@ -76,6 +76,16 @@ open class Oauth2DeviceAuthorization: Codable { } public static func from(map: [String: Any]) -> Oauth2DeviceAuthorization { + let defaults: [String: Any] = [ + "device_code": "", + "user_code": "", + "verification_uri": "", + "verification_uri_complete": "", + "expires_in": 0, + "interval": 0, + ] + let map = defaults.merging(map) { _, new in new } + return Oauth2DeviceAuthorization( device_code: map["device_code"] as! String, user_code: map["user_code"] as! String, diff --git a/Sources/AppwriteModels/Oauth2Grant.swift b/Sources/AppwriteModels/Oauth2Grant.swift index 85c61a3..cc52705 100644 --- a/Sources/AppwriteModels/Oauth2Grant.swift +++ b/Sources/AppwriteModels/Oauth2Grant.swift @@ -75,18 +75,18 @@ open class Oauth2Grant: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.userId = try container.decode(String.self, forKey: .userId) - self.appId = try container.decode(String.self, forKey: .appId) - self.scopes = try container.decode([String].self, forKey: .scopes) - self.resources = try container.decode([String].self, forKey: .resources) - self.authorizationDetails = try container.decode(String.self, forKey: .authorizationDetails) - self.prompt = try container.decode(String.self, forKey: .prompt) - self.redirectUri = try container.decode(String.self, forKey: .redirectUri) - self.authTime = try container.decode(Int.self, forKey: .authTime) - self.expire = try container.decode(String.self, forKey: .expire) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" + self.appId = try container.contains(.appId) ? container.decode(String.self, forKey: .appId) : "" + self.scopes = try container.contains(.scopes) ? container.decode([String].self, forKey: .scopes) : [] + self.resources = try container.contains(.resources) ? container.decode([String].self, forKey: .resources) : [] + self.authorizationDetails = try container.contains(.authorizationDetails) ? container.decode(String.self, forKey: .authorizationDetails) : "[]" + self.prompt = try container.contains(.prompt) ? container.decode(String.self, forKey: .prompt) : "" + self.redirectUri = try container.contains(.redirectUri) ? container.decode(String.self, forKey: .redirectUri) : "" + self.authTime = try container.contains(.authTime) ? container.decode(Int.self, forKey: .authTime) : 0 + self.expire = try container.contains(.expire) ? container.decode(String.self, forKey: .expire) : "" } public func encode(to encoder: Encoder) throws { @@ -124,6 +124,22 @@ open class Oauth2Grant: Codable { } public static func from(map: [String: Any]) -> Oauth2Grant { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "userId": "", + "appId": "", + "scopes": [Any](), + "resources": [Any](), + "authorizationDetails": "[]", + "prompt": "", + "redirectUri": "", + "authTime": 0, + "expire": "", + ] + let map = defaults.merging(map) { _, new in new } + return Oauth2Grant( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/Oauth2Organization.swift b/Sources/AppwriteModels/Oauth2Organization.swift index 16a575f..7a6570f 100644 --- a/Sources/AppwriteModels/Oauth2Organization.swift +++ b/Sources/AppwriteModels/Oauth2Organization.swift @@ -20,7 +20,7 @@ open class Oauth2Organization: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" } public func encode(to encoder: Encoder) throws { @@ -36,6 +36,9 @@ open class Oauth2Organization: Codable { } public static func from(map: [String: Any]) -> Oauth2Organization { + let defaults: [String: Any] = ["$id": ""] + let map = defaults.merging(map) { _, new in new } + return Oauth2Organization( id: map["$id"] as! String ) diff --git a/Sources/AppwriteModels/Oauth2OrganizationList.swift b/Sources/AppwriteModels/Oauth2OrganizationList.swift index 25fb45c..1a1498b 100644 --- a/Sources/AppwriteModels/Oauth2OrganizationList.swift +++ b/Sources/AppwriteModels/Oauth2OrganizationList.swift @@ -25,8 +25,8 @@ open class Oauth2OrganizationList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.organizations = try container.decode([Oauth2Organization].self, forKey: .organizations) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.organizations = try container.contains(.organizations) ? container.decode([Oauth2Organization].self, forKey: .organizations) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class Oauth2OrganizationList: Codable { } public static func from(map: [String: Any]) -> Oauth2OrganizationList { + let defaults: [String: Any] = [ + "total": 0, + "organizations": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return Oauth2OrganizationList( total: map["total"] as! Int, organizations: (map["organizations"] as! [[String: Any]]).map { Oauth2Organization.from(map: $0) } diff --git a/Sources/AppwriteModels/Oauth2PAR.swift b/Sources/AppwriteModels/Oauth2PAR.swift index f738a9f..c49149a 100644 --- a/Sources/AppwriteModels/Oauth2PAR.swift +++ b/Sources/AppwriteModels/Oauth2PAR.swift @@ -25,8 +25,8 @@ open class Oauth2PAR: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.request_uri = try container.decode(String.self, forKey: .request_uri) - self.expires_in = try container.decode(Int.self, forKey: .expires_in) + self.request_uri = try container.contains(.request_uri) ? container.decode(String.self, forKey: .request_uri) : "" + self.expires_in = try container.contains(.expires_in) ? container.decode(Int.self, forKey: .expires_in) : 0 } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class Oauth2PAR: Codable { } public static func from(map: [String: Any]) -> Oauth2PAR { + let defaults: [String: Any] = [ + "request_uri": "", + "expires_in": 0, + ] + let map = defaults.merging(map) { _, new in new } + return Oauth2PAR( request_uri: map["request_uri"] as! String, expires_in: map["expires_in"] as! Int diff --git a/Sources/AppwriteModels/Oauth2Project.swift b/Sources/AppwriteModels/Oauth2Project.swift index 7f34e4e..7c4a2a7 100644 --- a/Sources/AppwriteModels/Oauth2Project.swift +++ b/Sources/AppwriteModels/Oauth2Project.swift @@ -30,9 +30,9 @@ open class Oauth2Project: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.region = try container.decode(String.self, forKey: .region) - self.endpoint = try container.decode(String.self, forKey: .endpoint) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.region = try container.contains(.region) ? container.decode(String.self, forKey: .region) : "" + self.endpoint = try container.contains(.endpoint) ? container.decode(String.self, forKey: .endpoint) : "" } public func encode(to encoder: Encoder) throws { @@ -52,6 +52,13 @@ open class Oauth2Project: Codable { } public static func from(map: [String: Any]) -> Oauth2Project { + let defaults: [String: Any] = [ + "$id": "", + "region": "", + "endpoint": "", + ] + let map = defaults.merging(map) { _, new in new } + return Oauth2Project( id: map["$id"] as! String, region: map["region"] as! String, diff --git a/Sources/AppwriteModels/Oauth2ProjectList.swift b/Sources/AppwriteModels/Oauth2ProjectList.swift index 14064ae..a7b157e 100644 --- a/Sources/AppwriteModels/Oauth2ProjectList.swift +++ b/Sources/AppwriteModels/Oauth2ProjectList.swift @@ -25,8 +25,8 @@ open class Oauth2ProjectList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.projects = try container.decode([Oauth2Project].self, forKey: .projects) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.projects = try container.contains(.projects) ? container.decode([Oauth2Project].self, forKey: .projects) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class Oauth2ProjectList: Codable { } public static func from(map: [String: Any]) -> Oauth2ProjectList { + let defaults: [String: Any] = [ + "total": 0, + "projects": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return Oauth2ProjectList( total: map["total"] as! Int, projects: (map["projects"] as! [[String: Any]]).map { Oauth2Project.from(map: $0) } diff --git a/Sources/AppwriteModels/Oauth2Reject.swift b/Sources/AppwriteModels/Oauth2Reject.swift index 57b6901..8005053 100644 --- a/Sources/AppwriteModels/Oauth2Reject.swift +++ b/Sources/AppwriteModels/Oauth2Reject.swift @@ -20,7 +20,7 @@ open class Oauth2Reject: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.redirectUrl = try container.decode(String.self, forKey: .redirectUrl) + self.redirectUrl = try container.contains(.redirectUrl) ? container.decode(String.self, forKey: .redirectUrl) : "" } public func encode(to encoder: Encoder) throws { @@ -36,6 +36,9 @@ open class Oauth2Reject: Codable { } public static func from(map: [String: Any]) -> Oauth2Reject { + let defaults: [String: Any] = ["redirectUrl": ""] + let map = defaults.merging(map) { _, new in new } + return Oauth2Reject( redirectUrl: map["redirectUrl"] as! String ) diff --git a/Sources/AppwriteModels/Oauth2Token.swift b/Sources/AppwriteModels/Oauth2Token.swift index 994d5fa..1e4840a 100644 --- a/Sources/AppwriteModels/Oauth2Token.swift +++ b/Sources/AppwriteModels/Oauth2Token.swift @@ -50,11 +50,11 @@ open class Oauth2Token: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.access_token = try container.decode(String.self, forKey: .access_token) - self.token_type = try container.decode(String.self, forKey: .token_type) - self.expires_in = try container.decode(Int.self, forKey: .expires_in) - self.refresh_token = try container.decode(String.self, forKey: .refresh_token) - self.scope = try container.decode(String.self, forKey: .scope) + self.access_token = try container.contains(.access_token) ? container.decode(String.self, forKey: .access_token) : "" + self.token_type = try container.contains(.token_type) ? container.decode(String.self, forKey: .token_type) : "Bearer" + self.expires_in = try container.contains(.expires_in) ? container.decode(Int.self, forKey: .expires_in) : 0 + self.refresh_token = try container.contains(.refresh_token) ? container.decode(String.self, forKey: .refresh_token) : "" + self.scope = try container.contains(.scope) ? container.decode(String.self, forKey: .scope) : "" self.authorization_details = try container.decodeIfPresent(String.self, forKey: .authorization_details) self.id_token = try container.decodeIfPresent(String.self, forKey: .id_token) } @@ -84,6 +84,15 @@ open class Oauth2Token: Codable { } public static func from(map: [String: Any]) -> Oauth2Token { + let defaults: [String: Any] = [ + "access_token": "", + "token_type": "Bearer", + "expires_in": 0, + "refresh_token": "", + "scope": "", + ] + let map = defaults.merging(map) { _, new in new } + return Oauth2Token( access_token: map["access_token"] as! String, token_type: map["token_type"] as! String, diff --git a/Sources/AppwriteModels/Passkey.swift b/Sources/AppwriteModels/Passkey.swift new file mode 100644 index 0000000..3717fba --- /dev/null +++ b/Sources/AppwriteModels/Passkey.swift @@ -0,0 +1,88 @@ +import Foundation +import JSONCodable + +/// Passkey +open class Passkey: Codable { + + enum CodingKeys: String, CodingKey { + case id = "$id" + case createdAt = "$createdAt" + case updatedAt = "$updatedAt" + case name = "name" + case accessedAt = "accessedAt" + } + + /// Passkey ID. + public let id: String + /// Passkey creation date in ISO 8601 format. + public let createdAt: String + /// Passkey update date in ISO 8601 format. + public let updatedAt: String + /// Passkey name. + public let name: String + /// Most recent sign-in with this passkey in ISO 8601 format. Empty until the passkey is used to sign in. + public let accessedAt: String + + init( + id: String, + createdAt: String, + updatedAt: String, + name: String, + accessedAt: String + ) { + self.id = id + self.createdAt = createdAt + self.updatedAt = updatedAt + self.name = name + self.accessedAt = accessedAt + } + + public required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" + self.accessedAt = try container.contains(.accessedAt) ? container.decode(String.self, forKey: .accessedAt) : "" + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(id, forKey: .id) + try container.encode(createdAt, forKey: .createdAt) + try container.encode(updatedAt, forKey: .updatedAt) + try container.encode(name, forKey: .name) + try container.encode(accessedAt, forKey: .accessedAt) + } + + public func toMap() -> [String: Any] { + return [ + "$id": id as Any, + "$createdAt": createdAt as Any, + "$updatedAt": updatedAt as Any, + "name": name as Any, + "accessedAt": accessedAt as Any, + ] + } + + public static func from(map: [String: Any]) -> Passkey { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "name": "", + "accessedAt": "", + ] + let map = defaults.merging(map) { _, new in new } + + return Passkey( + id: map["$id"] as! String, + createdAt: map["$createdAt"] as! String, + updatedAt: map["$updatedAt"] as! String, + name: map["name"] as! String, + accessedAt: map["accessedAt"] as! String + ) + } +} diff --git a/Sources/AppwriteModels/PasskeyChallenge.swift b/Sources/AppwriteModels/PasskeyChallenge.swift new file mode 100644 index 0000000..e9f81c0 --- /dev/null +++ b/Sources/AppwriteModels/PasskeyChallenge.swift @@ -0,0 +1,88 @@ +import Foundation +import JSONCodable + +/// Passkey Challenge +open class PasskeyChallenge: Codable { + + enum CodingKeys: String, CodingKey { + case id = "$id" + case createdAt = "$createdAt" + case passkeyId = "passkeyId" + case expire = "expire" + case publicKey = "publicKey" + } + + /// Challenge ID. When signing in, pass it back with the credential to receive a token. + public let id: String + /// Challenge creation date in ISO 8601 format. + public let createdAt: String + /// ID of the passkey being registered. Empty for sign-in challenges. + public let passkeyId: String + /// Challenge expiration date in ISO 8601 format. + public let expire: String + /// WebAuthn options in JSON form. Pass them to `PublicKeyCredential.parseCreationOptionsFromJSON()` when registering, or `PublicKeyCredential.parseRequestOptionsFromJSON()` when signing in. + public let publicKey: [String: AnyCodable] + + init( + id: String, + createdAt: String, + passkeyId: String, + expire: String, + publicKey: [String: AnyCodable] + ) { + self.id = id + self.createdAt = createdAt + self.passkeyId = passkeyId + self.expire = expire + self.publicKey = publicKey + } + + public required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.passkeyId = try container.contains(.passkeyId) ? container.decode(String.self, forKey: .passkeyId) : "" + self.expire = try container.contains(.expire) ? container.decode(String.self, forKey: .expire) : "" + self.publicKey = try container.contains(.publicKey) ? container.decode([String: AnyCodable].self, forKey: .publicKey) : ([String: Any]()).mapValues { AnyCodable($0) } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(id, forKey: .id) + try container.encode(createdAt, forKey: .createdAt) + try container.encode(passkeyId, forKey: .passkeyId) + try container.encode(expire, forKey: .expire) + try container.encode(publicKey, forKey: .publicKey) + } + + public func toMap() -> [String: Any] { + return [ + "$id": id as Any, + "$createdAt": createdAt as Any, + "passkeyId": passkeyId as Any, + "expire": expire as Any, + "publicKey": publicKey as Any, + ] + } + + public static func from(map: [String: Any]) -> PasskeyChallenge { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "passkeyId": "", + "expire": "", + "publicKey": [String: Any](), + ] + let map = defaults.merging(map) { _, new in new } + + return PasskeyChallenge( + id: map["$id"] as! String, + createdAt: map["$createdAt"] as! String, + passkeyId: map["passkeyId"] as! String, + expire: map["expire"] as! String, + publicKey: (map["publicKey"] as! [String: Any]).mapValues { AnyCodable($0) } + ) + } +} diff --git a/Sources/AppwriteModels/PasskeyList.swift b/Sources/AppwriteModels/PasskeyList.swift new file mode 100644 index 0000000..7e6e04d --- /dev/null +++ b/Sources/AppwriteModels/PasskeyList.swift @@ -0,0 +1,58 @@ +import Foundation +import JSONCodable + +/// Passkeys List +open class PasskeyList: Codable { + + enum CodingKeys: String, CodingKey { + case total = "total" + case passkeys = "passkeys" + } + + /// Total number of passkeys that matched your query. + public let total: Int + /// List of passkeys. + public let passkeys: [Passkey] + + init( + total: Int, + passkeys: [Passkey] + ) { + self.total = total + self.passkeys = passkeys + } + + public required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.passkeys = try container.contains(.passkeys) ? container.decode([Passkey].self, forKey: .passkeys) : [] + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(total, forKey: .total) + try container.encode(passkeys, forKey: .passkeys) + } + + public func toMap() -> [String: Any] { + return [ + "total": total as Any, + "passkeys": passkeys.map { $0.toMap() } as Any, + ] + } + + public static func from(map: [String: Any]) -> PasskeyList { + let defaults: [String: Any] = [ + "total": 0, + "passkeys": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + + return PasskeyList( + total: map["total"] as! Int, + passkeys: (map["passkeys"] as! [[String: Any]]).map { Passkey.from(map: $0) } + ) + } +} diff --git a/Sources/AppwriteModels/Phone.swift b/Sources/AppwriteModels/Phone.swift index b765f5d..e6b2f6c 100644 --- a/Sources/AppwriteModels/Phone.swift +++ b/Sources/AppwriteModels/Phone.swift @@ -30,9 +30,9 @@ open class Phone: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.code = try container.decode(String.self, forKey: .code) - self.countryCode = try container.decode(String.self, forKey: .countryCode) - self.countryName = try container.decode(String.self, forKey: .countryName) + self.code = try container.contains(.code) ? container.decode(String.self, forKey: .code) : "" + self.countryCode = try container.contains(.countryCode) ? container.decode(String.self, forKey: .countryCode) : "" + self.countryName = try container.contains(.countryName) ? container.decode(String.self, forKey: .countryName) : "" } public func encode(to encoder: Encoder) throws { @@ -52,6 +52,13 @@ open class Phone: Codable { } public static func from(map: [String: Any]) -> Phone { + let defaults: [String: Any] = [ + "code": "", + "countryCode": "", + "countryName": "", + ] + let map = defaults.merging(map) { _, new in new } + return Phone( code: map["code"] as! String, countryCode: map["countryCode"] as! String, diff --git a/Sources/AppwriteModels/PhoneList.swift b/Sources/AppwriteModels/PhoneList.swift index b4da5d4..1fe1379 100644 --- a/Sources/AppwriteModels/PhoneList.swift +++ b/Sources/AppwriteModels/PhoneList.swift @@ -25,8 +25,8 @@ open class PhoneList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.phones = try container.decode([Phone].self, forKey: .phones) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.phones = try container.contains(.phones) ? container.decode([Phone].self, forKey: .phones) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class PhoneList: Codable { } public static func from(map: [String: Any]) -> PhoneList { + let defaults: [String: Any] = [ + "total": 0, + "phones": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return PhoneList( total: map["total"] as! Int, phones: (map["phones"] as! [[String: Any]]).map { Phone.from(map: $0) } diff --git a/Sources/AppwriteModels/Presence.swift b/Sources/AppwriteModels/Presence.swift index 1876a3e..27dc15f 100644 --- a/Sources/AppwriteModels/Presence.swift +++ b/Sources/AppwriteModels/Presence.swift @@ -60,13 +60,13 @@ open class Presence: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.permissions = try container.decode([String].self, forKey: .permissions) - self.userId = try container.decode(String.self, forKey: .userId) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.permissions = try container.contains(.permissions) ? container.decode([String].self, forKey: .permissions) : [] + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" self.status = try container.decodeIfPresent(String.self, forKey: .status) - self.source = try container.decode(String.self, forKey: .source) + self.source = try container.contains(.source) ? container.decode(String.self, forKey: .source) : "" self.expiresAt = try container.decodeIfPresent(String.self, forKey: .expiresAt) self.metadata = try container.decodeIfPresent([String: AnyCodable].self, forKey: .metadata) } @@ -100,6 +100,16 @@ open class Presence: Codable { } public static func from(map: [String: Any]) -> Presence { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "$permissions": [Any](), + "userId": "", + "source": "", + ] + let map = defaults.merging(map) { _, new in new } + return Presence( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/PresenceList.swift b/Sources/AppwriteModels/PresenceList.swift index 5b06a5e..1679a3c 100644 --- a/Sources/AppwriteModels/PresenceList.swift +++ b/Sources/AppwriteModels/PresenceList.swift @@ -25,8 +25,8 @@ open class PresenceList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.presences = try container.decode([Presence].self, forKey: .presences) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.presences = try container.contains(.presences) ? container.decode([Presence].self, forKey: .presences) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class PresenceList: Codable { } public static func from(map: [String: Any]) -> PresenceList { + let defaults: [String: Any] = [ + "total": 0, + "presences": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return PresenceList( total: map["total"] as! Int, presences: (map["presences"] as! [[String: Any]]).map { Presence.from(map: $0) } diff --git a/Sources/AppwriteModels/Row.swift b/Sources/AppwriteModels/Row.swift index 81e24e5..cb9875c 100644 --- a/Sources/AppwriteModels/Row.swift +++ b/Sources/AppwriteModels/Row.swift @@ -55,13 +55,13 @@ open class Row: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.sequence = try container.decode(String.self, forKey: .sequence) - self.tableId = try container.decode(String.self, forKey: .tableId) - self.databaseId = try container.decode(String.self, forKey: .databaseId) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.permissions = try container.decode([String].self, forKey: .permissions) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.sequence = try container.contains(.sequence) ? container.decode(String.self, forKey: .sequence) : "" + self.tableId = try container.contains(.tableId) ? container.decode(String.self, forKey: .tableId) : "" + self.databaseId = try container.contains(.databaseId) ? container.decode(String.self, forKey: .databaseId) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.permissions = try container.contains(.permissions) ? container.decode([String].self, forKey: .permissions) : [] self.data = try container.decode(T.self, forKey: .data) } @@ -92,6 +92,17 @@ open class Row: Codable { } public static func from(map: [String: Any]) -> Row { + let defaults: [String: Any] = [ + "$id": "", + "$sequence": "", + "$tableId": "", + "$databaseId": "", + "$createdAt": "", + "$updatedAt": "", + "$permissions": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return Row( id: map["$id"] as! String, sequence: map["$sequence"] as! String, diff --git a/Sources/AppwriteModels/RowList.swift b/Sources/AppwriteModels/RowList.swift index bfc96d3..268ff00 100644 --- a/Sources/AppwriteModels/RowList.swift +++ b/Sources/AppwriteModels/RowList.swift @@ -25,8 +25,8 @@ open class RowList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.rows = try container.decode([Row].self, forKey: .rows) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.rows = try container.contains(.rows) ? container.decode([Row].self, forKey: .rows) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class RowList: Codable { } public static func from(map: [String: Any]) -> RowList { + let defaults: [String: Any] = [ + "total": 0, + "rows": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return RowList( total: map["total"] as! Int, rows: (map["rows"] as! [[String: Any]]).map { Row.from(map: $0) } diff --git a/Sources/AppwriteModels/Session.swift b/Sources/AppwriteModels/Session.swift index 799901c..44b73d8 100644 --- a/Sources/AppwriteModels/Session.swift +++ b/Sources/AppwriteModels/Session.swift @@ -160,35 +160,35 @@ open class Session: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.userId = try container.decode(String.self, forKey: .userId) - self.expire = try container.decode(String.self, forKey: .expire) - self.provider = try container.decode(String.self, forKey: .provider) - self.providerUid = try container.decode(String.self, forKey: .providerUid) - self.providerAccessToken = try container.decode(String.self, forKey: .providerAccessToken) - self.providerAccessTokenExpiry = try container.decode(String.self, forKey: .providerAccessTokenExpiry) - self.providerRefreshToken = try container.decode(String.self, forKey: .providerRefreshToken) - self.ip = try container.decode(String.self, forKey: .ip) - self.osCode = try container.decode(String.self, forKey: .osCode) - self.osName = try container.decode(String.self, forKey: .osName) - self.osVersion = try container.decode(String.self, forKey: .osVersion) - self.clientType = try container.decode(String.self, forKey: .clientType) - self.clientCode = try container.decode(String.self, forKey: .clientCode) - self.clientName = try container.decode(String.self, forKey: .clientName) - self.clientVersion = try container.decode(String.self, forKey: .clientVersion) - self.clientEngine = try container.decode(String.self, forKey: .clientEngine) - self.clientEngineVersion = try container.decode(String.self, forKey: .clientEngineVersion) - self.deviceName = try container.decode(String.self, forKey: .deviceName) - self.deviceBrand = try container.decode(String.self, forKey: .deviceBrand) - self.deviceModel = try container.decode(String.self, forKey: .deviceModel) - self.countryCode = try container.decode(String.self, forKey: .countryCode) - self.countryName = try container.decode(String.self, forKey: .countryName) - self.current = try container.decode(Bool.self, forKey: .current) - self.factors = try container.decode([String].self, forKey: .factors) - self.secret = try container.decode(String.self, forKey: .secret) - self.mfaUpdatedAt = try container.decode(String.self, forKey: .mfaUpdatedAt) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" + self.expire = try container.contains(.expire) ? container.decode(String.self, forKey: .expire) : "" + self.provider = try container.contains(.provider) ? container.decode(String.self, forKey: .provider) : "" + self.providerUid = try container.contains(.providerUid) ? container.decode(String.self, forKey: .providerUid) : "" + self.providerAccessToken = try container.contains(.providerAccessToken) ? container.decode(String.self, forKey: .providerAccessToken) : "" + self.providerAccessTokenExpiry = try container.contains(.providerAccessTokenExpiry) ? container.decode(String.self, forKey: .providerAccessTokenExpiry) : "" + self.providerRefreshToken = try container.contains(.providerRefreshToken) ? container.decode(String.self, forKey: .providerRefreshToken) : "" + self.ip = try container.contains(.ip) ? container.decode(String.self, forKey: .ip) : "" + self.osCode = try container.contains(.osCode) ? container.decode(String.self, forKey: .osCode) : "" + self.osName = try container.contains(.osName) ? container.decode(String.self, forKey: .osName) : "" + self.osVersion = try container.contains(.osVersion) ? container.decode(String.self, forKey: .osVersion) : "" + self.clientType = try container.contains(.clientType) ? container.decode(String.self, forKey: .clientType) : "" + self.clientCode = try container.contains(.clientCode) ? container.decode(String.self, forKey: .clientCode) : "" + self.clientName = try container.contains(.clientName) ? container.decode(String.self, forKey: .clientName) : "" + self.clientVersion = try container.contains(.clientVersion) ? container.decode(String.self, forKey: .clientVersion) : "" + self.clientEngine = try container.contains(.clientEngine) ? container.decode(String.self, forKey: .clientEngine) : "" + self.clientEngineVersion = try container.contains(.clientEngineVersion) ? container.decode(String.self, forKey: .clientEngineVersion) : "" + self.deviceName = try container.contains(.deviceName) ? container.decode(String.self, forKey: .deviceName) : "" + self.deviceBrand = try container.contains(.deviceBrand) ? container.decode(String.self, forKey: .deviceBrand) : "" + self.deviceModel = try container.contains(.deviceModel) ? container.decode(String.self, forKey: .deviceModel) : "" + self.countryCode = try container.contains(.countryCode) ? container.decode(String.self, forKey: .countryCode) : "" + self.countryName = try container.contains(.countryName) ? container.decode(String.self, forKey: .countryName) : "" + self.current = try container.contains(.current) ? container.decode(Bool.self, forKey: .current) : false + self.factors = try container.contains(.factors) ? container.decode([String].self, forKey: .factors) : [] + self.secret = try container.contains(.secret) ? container.decode(String.self, forKey: .secret) : "" + self.mfaUpdatedAt = try container.contains(.mfaUpdatedAt) ? container.decode(String.self, forKey: .mfaUpdatedAt) : "" } public func encode(to encoder: Encoder) throws { @@ -260,6 +260,39 @@ open class Session: Codable { } public static func from(map: [String: Any]) -> Session { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "userId": "", + "expire": "", + "provider": "", + "providerUid": "", + "providerAccessToken": "", + "providerAccessTokenExpiry": "", + "providerRefreshToken": "", + "ip": "", + "osCode": "", + "osName": "", + "osVersion": "", + "clientType": "", + "clientCode": "", + "clientName": "", + "clientVersion": "", + "clientEngine": "", + "clientEngineVersion": "", + "deviceName": "", + "deviceBrand": "", + "deviceModel": "", + "countryCode": "", + "countryName": "", + "current": false, + "factors": [Any](), + "secret": "", + "mfaUpdatedAt": "", + ] + let map = defaults.merging(map) { _, new in new } + return Session( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/SessionList.swift b/Sources/AppwriteModels/SessionList.swift index ccc8c18..7a6a540 100644 --- a/Sources/AppwriteModels/SessionList.swift +++ b/Sources/AppwriteModels/SessionList.swift @@ -25,8 +25,8 @@ open class SessionList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.sessions = try container.decode([Session].self, forKey: .sessions) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.sessions = try container.contains(.sessions) ? container.decode([Session].self, forKey: .sessions) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class SessionList: Codable { } public static func from(map: [String: Any]) -> SessionList { + let defaults: [String: Any] = [ + "total": 0, + "sessions": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return SessionList( total: map["total"] as! Int, sessions: (map["sessions"] as! [[String: Any]]).map { Session.from(map: $0) } diff --git a/Sources/AppwriteModels/Subscriber.swift b/Sources/AppwriteModels/Subscriber.swift index 4aa2e11..3911801 100644 --- a/Sources/AppwriteModels/Subscriber.swift +++ b/Sources/AppwriteModels/Subscriber.swift @@ -60,15 +60,15 @@ open class Subscriber: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.targetId = try container.decode(String.self, forKey: .targetId) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.targetId = try container.contains(.targetId) ? container.decode(String.self, forKey: .targetId) : "" self.target = try container.decode(Target.self, forKey: .target) - self.userId = try container.decode(String.self, forKey: .userId) - self.userName = try container.decode(String.self, forKey: .userName) - self.topicId = try container.decode(String.self, forKey: .topicId) - self.providerType = try container.decode(String.self, forKey: .providerType) + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" + self.userName = try container.contains(.userName) ? container.decode(String.self, forKey: .userName) : "" + self.topicId = try container.contains(.topicId) ? container.decode(String.self, forKey: .topicId) : "" + self.providerType = try container.contains(.providerType) ? container.decode(String.self, forKey: .providerType) : "" } public func encode(to encoder: Encoder) throws { @@ -100,6 +100,18 @@ open class Subscriber: Codable { } public static func from(map: [String: Any]) -> Subscriber { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "targetId": "", + "userId": "", + "userName": "", + "topicId": "", + "providerType": "", + ] + let map = defaults.merging(map) { _, new in new } + return Subscriber( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/Target.swift b/Sources/AppwriteModels/Target.swift index c27d03b..d3c0565 100644 --- a/Sources/AppwriteModels/Target.swift +++ b/Sources/AppwriteModels/Target.swift @@ -60,15 +60,15 @@ open class Target: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.name = try container.decode(String.self, forKey: .name) - self.userId = try container.decode(String.self, forKey: .userId) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" self.providerId = try container.decodeIfPresent(String.self, forKey: .providerId) - self.providerType = try container.decode(String.self, forKey: .providerType) - self.identifier = try container.decode(String.self, forKey: .identifier) - self.expired = try container.decode(Bool.self, forKey: .expired) + self.providerType = try container.contains(.providerType) ? container.decode(String.self, forKey: .providerType) : "" + self.identifier = try container.contains(.identifier) ? container.decode(String.self, forKey: .identifier) : "" + self.expired = try container.contains(.expired) ? container.decode(Bool.self, forKey: .expired) : false } public func encode(to encoder: Encoder) throws { @@ -100,6 +100,18 @@ open class Target: Codable { } public static func from(map: [String: Any]) -> Target { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "name": "", + "userId": "", + "providerType": "", + "identifier": "", + "expired": false, + ] + let map = defaults.merging(map) { _, new in new } + return Target( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/Team.swift b/Sources/AppwriteModels/Team.swift index 8a054db..4a5bd15 100644 --- a/Sources/AppwriteModels/Team.swift +++ b/Sources/AppwriteModels/Team.swift @@ -45,11 +45,11 @@ open class Team: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.name = try container.decode(String.self, forKey: .name) - self.total = try container.decode(Int.self, forKey: .total) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 self.prefs = try container.decode(Preferences.self, forKey: .prefs) } @@ -76,6 +76,15 @@ open class Team: Codable { } public static func from(map: [String: Any]) -> Team { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "name": "", + "total": 0, + ] + let map = defaults.merging(map) { _, new in new } + return Team( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/TeamList.swift b/Sources/AppwriteModels/TeamList.swift index f50cf54..7c80061 100644 --- a/Sources/AppwriteModels/TeamList.swift +++ b/Sources/AppwriteModels/TeamList.swift @@ -25,8 +25,8 @@ open class TeamList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.teams = try container.decode([Team].self, forKey: .teams) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.teams = try container.contains(.teams) ? container.decode([Team].self, forKey: .teams) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class TeamList: Codable { } public static func from(map: [String: Any]) -> TeamList { + let defaults: [String: Any] = [ + "total": 0, + "teams": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return TeamList( total: map["total"] as! Int, teams: (map["teams"] as! [[String: Any]]).map { Team.from(map: $0) } diff --git a/Sources/AppwriteModels/Token.swift b/Sources/AppwriteModels/Token.swift index 18a92a9..9448b0c 100644 --- a/Sources/AppwriteModels/Token.swift +++ b/Sources/AppwriteModels/Token.swift @@ -45,12 +45,12 @@ open class Token: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.userId = try container.decode(String.self, forKey: .userId) - self.secret = try container.decode(String.self, forKey: .secret) - self.expire = try container.decode(String.self, forKey: .expire) - self.phrase = try container.decode(String.self, forKey: .phrase) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" + self.secret = try container.contains(.secret) ? container.decode(String.self, forKey: .secret) : "" + self.expire = try container.contains(.expire) ? container.decode(String.self, forKey: .expire) : "" + self.phrase = try container.contains(.phrase) ? container.decode(String.self, forKey: .phrase) : "" } public func encode(to encoder: Encoder) throws { @@ -76,6 +76,16 @@ open class Token: Codable { } public static func from(map: [String: Any]) -> Token { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "userId": "", + "secret": "", + "expire": "", + "phrase": "", + ] + let map = defaults.merging(map) { _, new in new } + return Token( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/TokenSecret.swift b/Sources/AppwriteModels/TokenSecret.swift new file mode 100644 index 0000000..bc6623a --- /dev/null +++ b/Sources/AppwriteModels/TokenSecret.swift @@ -0,0 +1,98 @@ +import Foundation +import JSONCodable + +/// Token Secret +open class TokenSecret: Codable { + + enum CodingKeys: String, CodingKey { + case id = "$id" + case createdAt = "$createdAt" + case userId = "userId" + case secret = "secret" + case expire = "expire" + case phrase = "phrase" + } + + /// Token ID. + public let id: String + /// Token creation date in ISO 8601 format. + public let createdAt: String + /// User ID. + public let userId: String + /// Token secret key. Exchange it for a session with the create session endpoint. + public let secret: String + /// Token expiration date in ISO 8601 format. + public let expire: String + /// Security phrase of a token. Empty if security phrase was not requested when creating a token. It includes randomly generated phrase which is also sent in the external resource such as email. + public let phrase: String + + init( + id: String, + createdAt: String, + userId: String, + secret: String, + expire: String, + phrase: String + ) { + self.id = id + self.createdAt = createdAt + self.userId = userId + self.secret = secret + self.expire = expire + self.phrase = phrase + } + + public required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.userId = try container.contains(.userId) ? container.decode(String.self, forKey: .userId) : "" + self.secret = try container.contains(.secret) ? container.decode(String.self, forKey: .secret) : "" + self.expire = try container.contains(.expire) ? container.decode(String.self, forKey: .expire) : "" + self.phrase = try container.contains(.phrase) ? container.decode(String.self, forKey: .phrase) : "" + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(id, forKey: .id) + try container.encode(createdAt, forKey: .createdAt) + try container.encode(userId, forKey: .userId) + try container.encode(secret, forKey: .secret) + try container.encode(expire, forKey: .expire) + try container.encode(phrase, forKey: .phrase) + } + + public func toMap() -> [String: Any] { + return [ + "$id": id as Any, + "$createdAt": createdAt as Any, + "userId": userId as Any, + "secret": secret as Any, + "expire": expire as Any, + "phrase": phrase as Any, + ] + } + + public static func from(map: [String: Any]) -> TokenSecret { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "userId": "", + "secret": "", + "expire": "", + "phrase": "", + ] + let map = defaults.merging(map) { _, new in new } + + return TokenSecret( + id: map["$id"] as! String, + createdAt: map["$createdAt"] as! String, + userId: map["userId"] as! String, + secret: map["secret"] as! String, + expire: map["expire"] as! String, + phrase: map["phrase"] as! String + ) + } +} diff --git a/Sources/AppwriteModels/Transaction.swift b/Sources/AppwriteModels/Transaction.swift index 4032caa..ce2b93c 100644 --- a/Sources/AppwriteModels/Transaction.swift +++ b/Sources/AppwriteModels/Transaction.swift @@ -45,12 +45,12 @@ open class Transaction: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.status = try container.decode(String.self, forKey: .status) - self.operations = try container.decode(Int.self, forKey: .operations) - self.expiresAt = try container.decode(String.self, forKey: .expiresAt) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.status = try container.contains(.status) ? container.decode(String.self, forKey: .status) : "pending" + self.operations = try container.contains(.operations) ? container.decode(Int.self, forKey: .operations) : 0 + self.expiresAt = try container.contains(.expiresAt) ? container.decode(String.self, forKey: .expiresAt) : "" } public func encode(to encoder: Encoder) throws { @@ -76,6 +76,16 @@ open class Transaction: Codable { } public static func from(map: [String: Any]) -> Transaction { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "status": "pending", + "operations": 0, + "expiresAt": "", + ] + let map = defaults.merging(map) { _, new in new } + return Transaction( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/Sources/AppwriteModels/TransactionList.swift b/Sources/AppwriteModels/TransactionList.swift index 657d19e..00dd74c 100644 --- a/Sources/AppwriteModels/TransactionList.swift +++ b/Sources/AppwriteModels/TransactionList.swift @@ -25,8 +25,8 @@ open class TransactionList: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.total = try container.decode(Int.self, forKey: .total) - self.transactions = try container.decode([Transaction].self, forKey: .transactions) + self.total = try container.contains(.total) ? container.decode(Int.self, forKey: .total) : 0 + self.transactions = try container.contains(.transactions) ? container.decode([Transaction].self, forKey: .transactions) : [] } public func encode(to encoder: Encoder) throws { @@ -44,6 +44,12 @@ open class TransactionList: Codable { } public static func from(map: [String: Any]) -> TransactionList { + let defaults: [String: Any] = [ + "total": 0, + "transactions": [Any](), + ] + let map = defaults.merging(map) { _, new in new } + return TransactionList( total: map["total"] as! Int, transactions: (map["transactions"] as! [[String: Any]]).map { Transaction.from(map: $0) } diff --git a/Sources/AppwriteModels/User.swift b/Sources/AppwriteModels/User.swift index 2d0f963..3232b3b 100644 --- a/Sources/AppwriteModels/User.swift +++ b/Sources/AppwriteModels/User.swift @@ -150,31 +150,31 @@ open class User: Codable { public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - self.id = try container.decode(String.self, forKey: .id) - self.createdAt = try container.decode(String.self, forKey: .createdAt) - self.updatedAt = try container.decode(String.self, forKey: .updatedAt) - self.name = try container.decode(String.self, forKey: .name) + self.id = try container.contains(.id) ? container.decode(String.self, forKey: .id) : "" + self.createdAt = try container.contains(.createdAt) ? container.decode(String.self, forKey: .createdAt) : "" + self.updatedAt = try container.contains(.updatedAt) ? container.decode(String.self, forKey: .updatedAt) : "" + self.name = try container.contains(.name) ? container.decode(String.self, forKey: .name) : "" self.password = try container.decodeIfPresent(String.self, forKey: .password) self.hash = try container.decodeIfPresent(String.self, forKey: .hash) self.hashOptions = try container.decodeIfPresent([String: AnyCodable].self, forKey: .hashOptions) - self.registration = try container.decode(String.self, forKey: .registration) - self.status = try container.decode(Bool.self, forKey: .status) - self.labels = try container.decode([String].self, forKey: .labels) - self.passwordUpdate = try container.decode(String.self, forKey: .passwordUpdate) - self.email = try container.decode(String.self, forKey: .email) - self.phone = try container.decode(String.self, forKey: .phone) - self.emailVerification = try container.decode(Bool.self, forKey: .emailVerification) + self.registration = try container.contains(.registration) ? container.decode(String.self, forKey: .registration) : "" + self.status = try container.contains(.status) ? container.decode(Bool.self, forKey: .status) : true + self.labels = try container.contains(.labels) ? container.decode([String].self, forKey: .labels) : [] + self.passwordUpdate = try container.contains(.passwordUpdate) ? container.decode(String.self, forKey: .passwordUpdate) : "" + self.email = try container.contains(.email) ? container.decode(String.self, forKey: .email) : "" + self.phone = try container.contains(.phone) ? container.decode(String.self, forKey: .phone) : "" + self.emailVerification = try container.contains(.emailVerification) ? container.decode(Bool.self, forKey: .emailVerification) : false self.emailCanonical = try container.decodeIfPresent(String.self, forKey: .emailCanonical) self.emailIsFree = try container.decodeIfPresent(Bool.self, forKey: .emailIsFree) self.emailIsDisposable = try container.decodeIfPresent(Bool.self, forKey: .emailIsDisposable) self.emailIsCorporate = try container.decodeIfPresent(Bool.self, forKey: .emailIsCorporate) self.emailIsCanonical = try container.decodeIfPresent(Bool.self, forKey: .emailIsCanonical) self.passwordPwned = try container.decodeIfPresent(Bool.self, forKey: .passwordPwned) - self.phoneVerification = try container.decode(Bool.self, forKey: .phoneVerification) - self.mfa = try container.decode(Bool.self, forKey: .mfa) + self.phoneVerification = try container.contains(.phoneVerification) ? container.decode(Bool.self, forKey: .phoneVerification) : false + self.mfa = try container.contains(.mfa) ? container.decode(Bool.self, forKey: .mfa) : false self.prefs = try container.decode(Preferences.self, forKey: .prefs) - self.targets = try container.decode([Target].self, forKey: .targets) - self.accessedAt = try container.decode(String.self, forKey: .accessedAt) + self.targets = try container.contains(.targets) ? container.decode([Target].self, forKey: .targets) : [] + self.accessedAt = try container.contains(.accessedAt) ? container.decode(String.self, forKey: .accessedAt) : "" self.impersonator = try container.decodeIfPresent(Bool.self, forKey: .impersonator) self.impersonatorUserId = try container.decodeIfPresent(String.self, forKey: .impersonatorUserId) } @@ -244,6 +244,25 @@ open class User: Codable { } public static func from(map: [String: Any]) -> User { + let defaults: [String: Any] = [ + "$id": "", + "$createdAt": "", + "$updatedAt": "", + "name": "", + "registration": "", + "status": true, + "labels": [Any](), + "passwordUpdate": "", + "email": "", + "phone": "", + "emailVerification": false, + "phoneVerification": false, + "mfa": false, + "targets": [Any](), + "accessedAt": "", + ] + let map = defaults.merging(map) { _, new in new } + return User( id: map["$id"] as! String, createdAt: map["$createdAt"] as! String, diff --git a/docs/examples/account/create-o-auth-2-session.md b/docs/examples/account/create-o-auth-2-session.md index 3552fda..89a8280 100644 --- a/docs/examples/account/create-o-auth-2-session.md +++ b/docs/examples/account/create-o-auth-2-session.md @@ -12,7 +12,8 @@ let success = try await account.createOAuth2Session( provider: .amazon, success: "https://example.com", // optional failure: "https://example.com", // optional - scopes: [] // optional + scopes: [], // optional + state: "" // optional ) ``` diff --git a/docs/examples/account/create-o-auth-2-token.md b/docs/examples/account/create-o-auth-2-token.md index 1a22fb3..d813b6c 100644 --- a/docs/examples/account/create-o-auth-2-token.md +++ b/docs/examples/account/create-o-auth-2-token.md @@ -12,7 +12,8 @@ let success = try await account.createOAuth2Token( provider: .amazon, success: "https://example.com", // optional failure: "https://example.com", // optional - scopes: [] // optional + scopes: [], // optional + state: "" // optional ) ``` diff --git a/docs/examples/account/create-passkey-token.md b/docs/examples/account/create-passkey-token.md new file mode 100644 index 0000000..09d939b --- /dev/null +++ b/docs/examples/account/create-passkey-token.md @@ -0,0 +1,12 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let passkeyChallenge = try await account.createPasskeyToken() + +``` diff --git a/docs/examples/account/create-passkey.md b/docs/examples/account/create-passkey.md new file mode 100644 index 0000000..91130b0 --- /dev/null +++ b/docs/examples/account/create-passkey.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let passkeyChallenge = try await account.createPasskey( + passkeyId: "", // optional + name: "" // optional +) + +``` diff --git a/docs/examples/account/delete-passkey.md b/docs/examples/account/delete-passkey.md new file mode 100644 index 0000000..2f13a7f --- /dev/null +++ b/docs/examples/account/delete-passkey.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let result = try await account.deletePasskey( + passkeyId: "" +) + +``` diff --git a/docs/examples/account/get-passkey.md b/docs/examples/account/get-passkey.md new file mode 100644 index 0000000..ad1f843 --- /dev/null +++ b/docs/examples/account/get-passkey.md @@ -0,0 +1,14 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let passkey = try await account.getPasskey( + passkeyId: "" +) + +``` diff --git a/docs/examples/account/list-passkeys.md b/docs/examples/account/list-passkeys.md new file mode 100644 index 0000000..561b21d --- /dev/null +++ b/docs/examples/account/list-passkeys.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let passkeyList = try await account.listPasskeys( + queries: [], // optional + total: false // optional +) + +``` diff --git a/docs/examples/account/update-passkey-token.md b/docs/examples/account/update-passkey-token.md new file mode 100644 index 0000000..7ff46e9 --- /dev/null +++ b/docs/examples/account/update-passkey-token.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let tokenSecret = try await account.updatePasskeyToken( + challengeId: "", + credential: [:] +) + +``` diff --git a/docs/examples/account/update-passkey-verification.md b/docs/examples/account/update-passkey-verification.md new file mode 100644 index 0000000..834917c --- /dev/null +++ b/docs/examples/account/update-passkey-verification.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let passkey = try await account.updatePasskeyVerification( + passkeyId: "", + credential: [:] +) + +``` diff --git a/docs/examples/account/update-passkey.md b/docs/examples/account/update-passkey.md new file mode 100644 index 0000000..feec15c --- /dev/null +++ b/docs/examples/account/update-passkey.md @@ -0,0 +1,15 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let account = Account(client) + +let passkey = try await account.updatePasskey( + passkeyId: "", + name: "" +) + +``` diff --git a/docs/examples/analytics/create-event.md b/docs/examples/analytics/create-event.md new file mode 100644 index 0000000..5b6173d --- /dev/null +++ b/docs/examples/analytics/create-event.md @@ -0,0 +1,26 @@ +```swift +import Appwrite + +let client = Client() + .setEndpoint("https://.cloud.appwrite.io/v1") // Your API Endpoint + .setProject("") // Your project ID + +let analytics = Analytics(client) + +let result = try await analytics.createEvent( + propertyId: "", + name: "", + url: "https://example.com", + domain: "", // optional + referrer: "", // optional + screenWidth: 0, // optional + sessionHash: "", // optional + scrollDepth: 0, // optional + engagementTime: 0, // optional + props: [], // optional + userId: "", // optional + ip: "", // optional + userAgent: "" // optional +) + +``` diff --git a/docs/examples/oauth2/approve.md b/docs/examples/oauth2/approve.md index 28fff41..b5cc9c7 100644 --- a/docs/examples/oauth2/approve.md +++ b/docs/examples/oauth2/approve.md @@ -8,8 +8,8 @@ let client = Client() let oauth2 = Oauth2(client) let oauth2Approve = try await oauth2.approve( - grant_id: "", - authorization_details: "", // optional + grantId: "", + authorizationDetails: "", // optional scope: "" // optional ) diff --git a/docs/examples/oauth2/authorize-post.md b/docs/examples/oauth2/authorize-post.md index f3eee38..a8c7248 100644 --- a/docs/examples/oauth2/authorize-post.md +++ b/docs/examples/oauth2/authorize-post.md @@ -8,20 +8,20 @@ let client = Client() let oauth2 = Oauth2(client) let oauth2Authorize = try await oauth2.authorizePost( - client_id: "", // optional - redirect_uri: "https://example.com", // optional - response_type: "", // optional + clientId: "", // optional + redirectUri: "https://example.com", // optional + responseType: "", // optional scope: "", // optional state: "", // optional nonce: "", // optional - code_challenge: "", // optional - code_challenge_method: "s256", // optional + codeChallenge: "", // optional + codeChallengeMethod: "s256", // optional prompt: "", // optional - max_age: 0, // optional - authorization_details: "", // optional - resource: "", // optional + maxAge: 0, // optional + authorizationDetails: "", // optional + resource: [], // optional audience: "", // optional - request_uri: "" // optional + requestUri: "" // optional ) ``` diff --git a/docs/examples/oauth2/authorize.md b/docs/examples/oauth2/authorize.md index fb751a9..6b1dfd0 100644 --- a/docs/examples/oauth2/authorize.md +++ b/docs/examples/oauth2/authorize.md @@ -8,20 +8,20 @@ let client = Client() let oauth2 = Oauth2(client) let oauth2Authorize = try await oauth2.authorize( - client_id: "", // optional - redirect_uri: "https://example.com", // optional - response_type: "", // optional + clientId: "", // optional + redirectUri: "https://example.com", // optional + responseType: "", // optional scope: "", // optional state: "", // optional nonce: "", // optional - code_challenge: "", // optional - code_challenge_method: "s256", // optional + codeChallenge: "", // optional + codeChallengeMethod: "s256", // optional prompt: "", // optional - max_age: 0, // optional - authorization_details: "", // optional - resource: "", // optional + maxAge: 0, // optional + authorizationDetails: "", // optional + resource: [], // optional audience: "", // optional - request_uri: "" // optional + requestUri: "" // optional ) ``` diff --git a/docs/examples/oauth2/create-device-authorization.md b/docs/examples/oauth2/create-device-authorization.md index d7beeb5..a84a257 100644 --- a/docs/examples/oauth2/create-device-authorization.md +++ b/docs/examples/oauth2/create-device-authorization.md @@ -8,10 +8,10 @@ let client = Client() let oauth2 = Oauth2(client) let oauth2DeviceAuthorization = try await oauth2.createDeviceAuthorization( - client_id: "", // optional + clientId: "", // optional scope: "", // optional - authorization_details: "", // optional - resource: "", // optional + authorizationDetails: "", // optional + resource: [], // optional audience: "" // optional ) diff --git a/docs/examples/oauth2/create-grant.md b/docs/examples/oauth2/create-grant.md index 0f0126c..8da1d42 100644 --- a/docs/examples/oauth2/create-grant.md +++ b/docs/examples/oauth2/create-grant.md @@ -8,7 +8,7 @@ let client = Client() let oauth2 = Oauth2(client) let oauth2Grant = try await oauth2.createGrant( - user_code: "" + userCode: "" ) ``` diff --git a/docs/examples/oauth2/create-par.md b/docs/examples/oauth2/create-par.md index 2aa8e30..ca293df 100644 --- a/docs/examples/oauth2/create-par.md +++ b/docs/examples/oauth2/create-par.md @@ -8,18 +8,18 @@ let client = Client() let oauth2 = Oauth2(client) let oauth2PAR = try await oauth2.createPAR( - client_id: "", - redirect_uri: "https://example.com", - response_type: "code", + clientId: "", + redirectUri: "https://example.com", + responseType: "code", scope: "", // optional state: "", // optional nonce: "", // optional - code_challenge: "", // optional - code_challenge_method: "s256", // optional + codeChallenge: "", // optional + codeChallengeMethod: "s256", // optional prompt: "", // optional - max_age: 0, // optional - authorization_details: "", // optional - resource: "", // optional + maxAge: 0, // optional + authorizationDetails: "", // optional + resource: [], // optional audience: "" // optional ) diff --git a/docs/examples/oauth2/create-token.md b/docs/examples/oauth2/create-token.md index d604aef..0b7b34c 100644 --- a/docs/examples/oauth2/create-token.md +++ b/docs/examples/oauth2/create-token.md @@ -8,15 +8,15 @@ let client = Client() let oauth2 = Oauth2(client) let oauth2Token = try await oauth2.createToken( - grant_type: "", + grantType: "", code: "", // optional - refresh_token: "", // optional - device_code: "", // optional - client_id: "", // optional - client_secret: "", // optional - code_verifier: "", // optional - redirect_uri: "https://example.com", // optional - resource: "", // optional + refreshToken: "", // optional + deviceCode: "", // optional + clientId: "", // optional + clientSecret: "", // optional + codeVerifier: "", // optional + redirectUri: "https://example.com", // optional + resource: [], // optional audience: "" // optional ) diff --git a/docs/examples/oauth2/get-grant.md b/docs/examples/oauth2/get-grant.md index c87e783..9fdef85 100644 --- a/docs/examples/oauth2/get-grant.md +++ b/docs/examples/oauth2/get-grant.md @@ -8,7 +8,7 @@ let client = Client() let oauth2 = Oauth2(client) let oauth2Grant = try await oauth2.getGrant( - grant_id: "" + grantId: "" ) ``` diff --git a/docs/examples/oauth2/logout-post.md b/docs/examples/oauth2/logout-post.md index 125c268..1c07068 100644 --- a/docs/examples/oauth2/logout-post.md +++ b/docs/examples/oauth2/logout-post.md @@ -8,12 +8,12 @@ let client = Client() let oauth2 = Oauth2(client) let result = try await oauth2.logoutPost( - id_token_hint: "", // optional - logout_hint: "", // optional - client_id: "", // optional - post_logout_redirect_uri: "https://example.com", // optional + idTokenHint: "", // optional + logoutHint: "", // optional + clientId: "", // optional + postLogoutRedirectUri: "https://example.com", // optional state: "", // optional - ui_locales: "" // optional + uiLocales: "" // optional ) ``` diff --git a/docs/examples/oauth2/logout.md b/docs/examples/oauth2/logout.md index 188d7e3..3e19969 100644 --- a/docs/examples/oauth2/logout.md +++ b/docs/examples/oauth2/logout.md @@ -8,12 +8,12 @@ let client = Client() let oauth2 = Oauth2(client) let result = try await oauth2.logout( - id_token_hint: "", // optional - logout_hint: "", // optional - client_id: "", // optional - post_logout_redirect_uri: "https://example.com", // optional + idTokenHint: "", // optional + logoutHint: "", // optional + clientId: "", // optional + postLogoutRedirectUri: "https://example.com", // optional state: "", // optional - ui_locales: "" // optional + uiLocales: "" // optional ) ``` diff --git a/docs/examples/oauth2/reject.md b/docs/examples/oauth2/reject.md index f37be58..e0463cf 100644 --- a/docs/examples/oauth2/reject.md +++ b/docs/examples/oauth2/reject.md @@ -8,7 +8,7 @@ let client = Client() let oauth2 = Oauth2(client) let oauth2Reject = try await oauth2.reject( - grant_id: "" + grantId: "" ) ``` diff --git a/docs/examples/oauth2/revoke.md b/docs/examples/oauth2/revoke.md index e9a89ff..1a366e4 100644 --- a/docs/examples/oauth2/revoke.md +++ b/docs/examples/oauth2/revoke.md @@ -9,9 +9,9 @@ let oauth2 = Oauth2(client) let result = try await oauth2.revoke( token: "", - token_type_hint: "access_token", // optional - client_id: "", // optional - client_secret: "" // optional + tokenTypeHint: "access_token", // optional + clientId: "", // optional + clientSecret: "" // optional ) ``` diff --git a/docs/examples/teams/create-membership.md b/docs/examples/teams/create-membership.md index dd089a0..faa7578 100644 --- a/docs/examples/teams/create-membership.md +++ b/docs/examples/teams/create-membership.md @@ -16,7 +16,8 @@ let membership = try await teams.createMembership( userId: "", // optional phone: "+12065550100", // optional url: "https://example.com", // optional - name: "" // optional + name: "", // optional + membershipId: "" // optional ) ```