diff --git a/README.md b/README.md index 542c5c3e..6b771d55 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ # Appwrite React Native SDK ![License](https://img.shields.io/github/license/appwrite/sdk-for-react-native.svg?style=flat-square) -![Version](https://img.shields.io/badge/api%20version-1.7.4-blue.svg?style=flat-square) +![Version](https://img.shields.io/badge/api%20version-1.8.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 is compatible with Appwrite server version 1.7.x. For older versions, please check [previous releases](https://github.com/appwrite/sdk-for-react-native/releases).** +**This SDK is compatible with Appwrite server version 1.8.x. For older versions, please check [previous releases](https://github.com/appwrite/sdk-for-react-native/releases).** Appwrite is an open-source backend as a service server that abstract and simplify 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 React Native 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) @@ -21,15 +21,16 @@ npx expo install react-native-appwrite react-native-url-polyfill ``` - ## Getting Started ### Add your Platform + If this is your first time using Appwrite, create an account and create your first project. Then, under **Add a platform**, add a **Android app** or a **Apple app**. You can skip optional steps. #### iOS steps + Add your app **name** and **Bundle ID**. You can find your **Bundle Identifier** in the **General** tab for your app's primary target in XCode. For Expo projects you can set or find it on **app.json** file at your project's root directory. #### Android steps @@ -47,6 +48,7 @@ import 'react-native-url-polyfill/auto' > `cd ios && pod install && cd ..` ### Init your SDK + Initialize your SDK with your Appwrite server API endpoint and project ID which can be found in your project settings page. ```js @@ -62,6 +64,7 @@ client ``` ### Make Your First Request + Once your SDK object is set, access any of the Appwrite services and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the [API References](https://appwrite.io/docs) section. ```js @@ -78,6 +81,7 @@ account.create(ID.unique(), 'me@example.com', 'password', 'Jane Doe') ``` ### Full Example + ```js import { Client, Account } from 'react-native-appwrite'; // Init your React Native SDK @@ -100,13 +104,90 @@ account.create(ID.unique(), 'me@example.com', 'password', 'Jane Doe') }); ``` +### Type Safety with Models + +The Appwrite React Native SDK provides type safety when working with database documents through generic methods. Methods like `listDocuments`, `getDocument`, and others accept a generic type parameter that allows you to specify your custom model type for full type safety. + +**TypeScript:** +```typescript +interface Book { + name: string; + author: string; + releaseYear?: string; + category?: string; + genre?: string[]; + isCheckedOut: boolean; +} + +const databases = new Databases(client); + +try { + const documents = await databases.listDocuments( + 'your-database-id', + 'your-collection-id' + ); + + documents.documents.forEach(book => { + console.log(`Book: ${book.name} by ${book.author}`); // Now you have full type safety + }); +} catch (error) { + console.error('Appwrite error:', error); +} +``` + +**JavaScript (with JSDoc for type hints):** +```javascript +/** + * @typedef {Object} Book + * @property {string} name + * @property {string} author + * @property {string} [releaseYear] + * @property {string} [category] + * @property {string[]} [genre] + * @property {boolean} isCheckedOut + */ + +const databases = new Databases(client); + +try { + /** @type {Models.DocumentList} */ + const documents = await databases.listDocuments( + 'your-database-id', + 'your-collection-id' + ); + + documents.documents.forEach(book => { + console.log(`Book: ${book.name} by ${book.author}`); // Type hints available in IDE + }); +} catch (error) { + console.error('Appwrite error:', error); +} +``` + +**Tip**: You can use the `appwrite types` command to automatically generate TypeScript interfaces based on your Appwrite database schema. Learn more about [type generation](https://appwrite.io/docs/products/databases/type-generation). + +### Error Handling + +The Appwrite React Native SDK raises an `AppwriteException` object with `message`, `code` and `response` properties. You can handle any errors by catching the exception and present the `message` to the user or handle it yourself based on the provided error information. Below is an example. + +```javascript +try { + const user = await account.create(ID.unique(), "email@example.com", "password", "Walter O'Brien"); + console.log('User created:', user); +} catch (error) { + console.error('Appwrite error:', error.message); +} +``` + ### Learn more + You can use the following resources to learn more and get help - 🚀 [Getting Started Tutorial](https://appwrite.io/docs/quick-starts/react-native) - 📜 [Appwrite Docs](https://appwrite.io/docs) - 💬 [Discord Community](https://appwrite.io/discord) - 🚂 [Appwrite React Native Playground](https://github.com/appwrite/playground-for-react-native) + ## Contribution This library is auto-generated by Appwrite custom [SDK Generator](https://github.com/appwrite/sdk-generator). To learn more about how you can help us improve this SDK, please check the [contribution guide](https://github.com/appwrite/sdk-generator/blob/master/CONTRIBUTING.md) before sending a pull-request. diff --git a/docs/examples/account/create-email-password-session.md b/docs/examples/account/create-email-password-session.md index 217d7873..47fb5573 100644 --- a/docs/examples/account/create-email-password-session.md +++ b/docs/examples/account/create-email-password-session.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.createEmailPasswordSession( - 'email@example.com', // email - 'password' // password -); +const result = await account.createEmailPasswordSession({ + email: 'email@example.com', + password: 'password' +}); console.log(result); diff --git a/docs/examples/account/create-email-token.md b/docs/examples/account/create-email-token.md index b9bdf3bb..aef74a8e 100644 --- a/docs/examples/account/create-email-token.md +++ b/docs/examples/account/create-email-token.md @@ -6,10 +6,10 @@ const client = new Client() const account = new Account(client); -const result = await account.createEmailToken( - '', // userId - 'email@example.com', // email - false // phrase (optional) -); +const result = await account.createEmailToken({ + userId: '', + email: 'email@example.com', + phrase: false // optional +}); console.log(result); diff --git a/docs/examples/account/create-j-w-t.md b/docs/examples/account/create-jwt.md similarity index 100% rename from docs/examples/account/create-j-w-t.md rename to docs/examples/account/create-jwt.md diff --git a/docs/examples/account/create-magic-u-r-l-token.md b/docs/examples/account/create-magic-url-token.md similarity index 59% rename from docs/examples/account/create-magic-u-r-l-token.md rename to docs/examples/account/create-magic-url-token.md index 413e347a..5c30ef53 100644 --- a/docs/examples/account/create-magic-u-r-l-token.md +++ b/docs/examples/account/create-magic-url-token.md @@ -6,11 +6,11 @@ const client = new Client() const account = new Account(client); -const result = await account.createMagicURLToken( - '', // userId - 'email@example.com', // email - 'https://example.com', // url (optional) - false // phrase (optional) -); +const result = await account.createMagicURLToken({ + userId: '', + email: 'email@example.com', + url: 'https://example.com', // optional + phrase: false // optional +}); console.log(result); diff --git a/docs/examples/account/create-mfa-authenticator.md b/docs/examples/account/create-mfa-authenticator.md index ec243490..d859850f 100644 --- a/docs/examples/account/create-mfa-authenticator.md +++ b/docs/examples/account/create-mfa-authenticator.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.createMfaAuthenticator( - AuthenticatorType.Totp // type -); +const result = await account.createMFAAuthenticator({ + type: AuthenticatorType.Totp +}); console.log(result); diff --git a/docs/examples/account/create-mfa-challenge.md b/docs/examples/account/create-mfa-challenge.md index 04de2586..c7e5f621 100644 --- a/docs/examples/account/create-mfa-challenge.md +++ b/docs/examples/account/create-mfa-challenge.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.createMfaChallenge( - AuthenticationFactor.Email // factor -); +const result = await account.createMFAChallenge({ + factor: AuthenticationFactor.Email +}); console.log(result); diff --git a/docs/examples/account/create-mfa-recovery-codes.md b/docs/examples/account/create-mfa-recovery-codes.md index f256be30..22d6a579 100644 --- a/docs/examples/account/create-mfa-recovery-codes.md +++ b/docs/examples/account/create-mfa-recovery-codes.md @@ -6,6 +6,6 @@ const client = new Client() const account = new Account(client); -const result = await account.createMfaRecoveryCodes(); +const result = await account.createMFARecoveryCodes(); console.log(result); diff --git a/docs/examples/account/create-o-auth2token.md b/docs/examples/account/create-o-auth-2-session.md similarity index 58% rename from docs/examples/account/create-o-auth2token.md rename to docs/examples/account/create-o-auth-2-session.md index cd4ee86a..4212803c 100644 --- a/docs/examples/account/create-o-auth2token.md +++ b/docs/examples/account/create-o-auth-2-session.md @@ -6,10 +6,10 @@ const client = new Client() const account = new Account(client); -account.createOAuth2Token( - OAuthProvider.Amazon, // provider - 'https://example.com', // success (optional) - 'https://example.com', // failure (optional) - [] // scopes (optional) -); +account.createOAuth2Session({ + provider: OAuthProvider.Amazon, + success: 'https://example.com', // optional + failure: 'https://example.com', // optional + scopes: [] // optional +}); diff --git a/docs/examples/account/create-o-auth2session.md b/docs/examples/account/create-o-auth-2-token.md similarity index 58% rename from docs/examples/account/create-o-auth2session.md rename to docs/examples/account/create-o-auth-2-token.md index 84bddb47..8989e489 100644 --- a/docs/examples/account/create-o-auth2session.md +++ b/docs/examples/account/create-o-auth-2-token.md @@ -6,10 +6,10 @@ const client = new Client() const account = new Account(client); -account.createOAuth2Session( - OAuthProvider.Amazon, // provider - 'https://example.com', // success (optional) - 'https://example.com', // failure (optional) - [] // scopes (optional) -); +account.createOAuth2Token({ + provider: OAuthProvider.Amazon, + success: 'https://example.com', // optional + failure: 'https://example.com', // optional + scopes: [] // optional +}); diff --git a/docs/examples/account/create-phone-token.md b/docs/examples/account/create-phone-token.md index d03e5ea4..68eaa38d 100644 --- a/docs/examples/account/create-phone-token.md +++ b/docs/examples/account/create-phone-token.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.createPhoneToken( - '', // userId - '+12065550100' // phone -); +const result = await account.createPhoneToken({ + userId: '', + phone: '+12065550100' +}); console.log(result); diff --git a/docs/examples/account/create-push-target.md b/docs/examples/account/create-push-target.md index 83211ab9..d3fae6fd 100644 --- a/docs/examples/account/create-push-target.md +++ b/docs/examples/account/create-push-target.md @@ -6,10 +6,10 @@ const client = new Client() const account = new Account(client); -const result = await account.createPushTarget( - '', // targetId - '', // identifier - '' // providerId (optional) -); +const result = await account.createPushTarget({ + targetId: '', + identifier: '', + providerId: '' // optional +}); console.log(result); diff --git a/docs/examples/account/create-recovery.md b/docs/examples/account/create-recovery.md index 802af82f..01c5c387 100644 --- a/docs/examples/account/create-recovery.md +++ b/docs/examples/account/create-recovery.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.createRecovery( - 'email@example.com', // email - 'https://example.com' // url -); +const result = await account.createRecovery({ + email: 'email@example.com', + url: 'https://example.com' +}); console.log(result); diff --git a/docs/examples/account/create-session.md b/docs/examples/account/create-session.md index bb3040ae..b6741518 100644 --- a/docs/examples/account/create-session.md +++ b/docs/examples/account/create-session.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.createSession( - '', // userId - '' // secret -); +const result = await account.createSession({ + userId: '', + secret: '' +}); console.log(result); diff --git a/docs/examples/account/create-verification.md b/docs/examples/account/create-verification.md index 5fdffcba..f4a210be 100644 --- a/docs/examples/account/create-verification.md +++ b/docs/examples/account/create-verification.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.createVerification( - 'https://example.com' // url -); +const result = await account.createVerification({ + url: 'https://example.com' +}); console.log(result); diff --git a/docs/examples/account/create.md b/docs/examples/account/create.md index eb3d04ac..2c6850a1 100644 --- a/docs/examples/account/create.md +++ b/docs/examples/account/create.md @@ -6,11 +6,11 @@ const client = new Client() const account = new Account(client); -const result = await account.create( - '', // userId - 'email@example.com', // email - '', // password - '' // name (optional) -); +const result = await account.create({ + userId: '', + email: 'email@example.com', + password: '', + name: '' // optional +}); console.log(result); diff --git a/docs/examples/account/delete-identity.md b/docs/examples/account/delete-identity.md index df492a52..0d9a9712 100644 --- a/docs/examples/account/delete-identity.md +++ b/docs/examples/account/delete-identity.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.deleteIdentity( - '' // identityId -); +const result = await account.deleteIdentity({ + identityId: '' +}); console.log(result); diff --git a/docs/examples/account/delete-mfa-authenticator.md b/docs/examples/account/delete-mfa-authenticator.md index 093ba4d5..90a6e347 100644 --- a/docs/examples/account/delete-mfa-authenticator.md +++ b/docs/examples/account/delete-mfa-authenticator.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.deleteMfaAuthenticator( - AuthenticatorType.Totp // type -); +const result = await account.deleteMFAAuthenticator({ + type: AuthenticatorType.Totp +}); console.log(result); diff --git a/docs/examples/account/delete-push-target.md b/docs/examples/account/delete-push-target.md index a926ede9..dff171b3 100644 --- a/docs/examples/account/delete-push-target.md +++ b/docs/examples/account/delete-push-target.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.deletePushTarget( - '' // targetId -); +const result = await account.deletePushTarget({ + targetId: '' +}); console.log(result); diff --git a/docs/examples/account/delete-session.md b/docs/examples/account/delete-session.md index 134a2caa..f1ce4a0a 100644 --- a/docs/examples/account/delete-session.md +++ b/docs/examples/account/delete-session.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.deleteSession( - '' // sessionId -); +const result = await account.deleteSession({ + sessionId: '' +}); console.log(result); diff --git a/docs/examples/account/get-mfa-recovery-codes.md b/docs/examples/account/get-mfa-recovery-codes.md index c660a17a..94896eb7 100644 --- a/docs/examples/account/get-mfa-recovery-codes.md +++ b/docs/examples/account/get-mfa-recovery-codes.md @@ -6,6 +6,6 @@ const client = new Client() const account = new Account(client); -const result = await account.getMfaRecoveryCodes(); +const result = await account.getMFARecoveryCodes(); console.log(result); diff --git a/docs/examples/account/get-session.md b/docs/examples/account/get-session.md index 1db05d5c..4c0fdfc0 100644 --- a/docs/examples/account/get-session.md +++ b/docs/examples/account/get-session.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.getSession( - '' // sessionId -); +const result = await account.getSession({ + sessionId: '' +}); console.log(result); diff --git a/docs/examples/account/list-identities.md b/docs/examples/account/list-identities.md index 239dbbf2..2a3bbae3 100644 --- a/docs/examples/account/list-identities.md +++ b/docs/examples/account/list-identities.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.listIdentities( - [] // queries (optional) -); +const result = await account.listIdentities({ + queries: [] // optional +}); console.log(result); diff --git a/docs/examples/account/list-logs.md b/docs/examples/account/list-logs.md index 9cf44145..4bb9f9fd 100644 --- a/docs/examples/account/list-logs.md +++ b/docs/examples/account/list-logs.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.listLogs( - [] // queries (optional) -); +const result = await account.listLogs({ + queries: [] // optional +}); console.log(result); diff --git a/docs/examples/account/list-mfa-factors.md b/docs/examples/account/list-mfa-factors.md index 51b76c90..98ba9397 100644 --- a/docs/examples/account/list-mfa-factors.md +++ b/docs/examples/account/list-mfa-factors.md @@ -6,6 +6,6 @@ const client = new Client() const account = new Account(client); -const result = await account.listMfaFactors(); +const result = await account.listMFAFactors(); console.log(result); diff --git a/docs/examples/account/update-email.md b/docs/examples/account/update-email.md index 4bbe0b03..325fa472 100644 --- a/docs/examples/account/update-email.md +++ b/docs/examples/account/update-email.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.updateEmail( - 'email@example.com', // email - 'password' // password -); +const result = await account.updateEmail({ + email: 'email@example.com', + password: 'password' +}); console.log(result); diff --git a/docs/examples/account/update-magic-u-r-l-session.md b/docs/examples/account/update-magic-url-session.md similarity index 72% rename from docs/examples/account/update-magic-u-r-l-session.md rename to docs/examples/account/update-magic-url-session.md index c5e6b613..4feaa59f 100644 --- a/docs/examples/account/update-magic-u-r-l-session.md +++ b/docs/examples/account/update-magic-url-session.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.updateMagicURLSession( - '', // userId - '' // secret -); +const result = await account.updateMagicURLSession({ + userId: '', + secret: '' +}); console.log(result); diff --git a/docs/examples/account/update-mfa-authenticator.md b/docs/examples/account/update-mfa-authenticator.md index 07a798e7..58f23295 100644 --- a/docs/examples/account/update-mfa-authenticator.md +++ b/docs/examples/account/update-mfa-authenticator.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.updateMfaAuthenticator( - AuthenticatorType.Totp, // type - '' // otp -); +const result = await account.updateMFAAuthenticator({ + type: AuthenticatorType.Totp, + otp: '' +}); console.log(result); diff --git a/docs/examples/account/update-mfa-challenge.md b/docs/examples/account/update-mfa-challenge.md index b93e0bf5..c2ce59f6 100644 --- a/docs/examples/account/update-mfa-challenge.md +++ b/docs/examples/account/update-mfa-challenge.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.updateMfaChallenge( - '', // challengeId - '' // otp -); +const result = await account.updateMFAChallenge({ + challengeId: '', + otp: '' +}); console.log(result); diff --git a/docs/examples/account/update-mfa-recovery-codes.md b/docs/examples/account/update-mfa-recovery-codes.md index 2ed9bb02..1f7b4f0d 100644 --- a/docs/examples/account/update-mfa-recovery-codes.md +++ b/docs/examples/account/update-mfa-recovery-codes.md @@ -6,6 +6,6 @@ const client = new Client() const account = new Account(client); -const result = await account.updateMfaRecoveryCodes(); +const result = await account.updateMFARecoveryCodes(); console.log(result); diff --git a/docs/examples/account/update-m-f-a.md b/docs/examples/account/update-mfa.md similarity index 82% rename from docs/examples/account/update-m-f-a.md rename to docs/examples/account/update-mfa.md index ebbfc0c8..26d26ffe 100644 --- a/docs/examples/account/update-m-f-a.md +++ b/docs/examples/account/update-mfa.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.updateMFA( - false // mfa -); +const result = await account.updateMFA({ + mfa: false +}); console.log(result); diff --git a/docs/examples/account/update-name.md b/docs/examples/account/update-name.md index adbbcab5..f58f26ba 100644 --- a/docs/examples/account/update-name.md +++ b/docs/examples/account/update-name.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.updateName( - '' // name -); +const result = await account.updateName({ + name: '' +}); console.log(result); diff --git a/docs/examples/account/update-password.md b/docs/examples/account/update-password.md index 3bde58e6..89f99d97 100644 --- a/docs/examples/account/update-password.md +++ b/docs/examples/account/update-password.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.updatePassword( - '', // password - 'password' // oldPassword (optional) -); +const result = await account.updatePassword({ + password: '', + oldPassword: 'password' // optional +}); console.log(result); diff --git a/docs/examples/account/update-phone-session.md b/docs/examples/account/update-phone-session.md index c9c82696..b3a3ffff 100644 --- a/docs/examples/account/update-phone-session.md +++ b/docs/examples/account/update-phone-session.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.updatePhoneSession( - '', // userId - '' // secret -); +const result = await account.updatePhoneSession({ + userId: '', + secret: '' +}); console.log(result); diff --git a/docs/examples/account/update-phone-verification.md b/docs/examples/account/update-phone-verification.md index 0ef7e53e..2f1be2f3 100644 --- a/docs/examples/account/update-phone-verification.md +++ b/docs/examples/account/update-phone-verification.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.updatePhoneVerification( - '', // userId - '' // secret -); +const result = await account.updatePhoneVerification({ + userId: '', + secret: '' +}); console.log(result); diff --git a/docs/examples/account/update-phone.md b/docs/examples/account/update-phone.md index bf8aae2a..4e123547 100644 --- a/docs/examples/account/update-phone.md +++ b/docs/examples/account/update-phone.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.updatePhone( - '+12065550100', // phone - 'password' // password -); +const result = await account.updatePhone({ + phone: '+12065550100', + password: 'password' +}); console.log(result); diff --git a/docs/examples/account/update-prefs.md b/docs/examples/account/update-prefs.md index 01d4fd68..43fa9fc7 100644 --- a/docs/examples/account/update-prefs.md +++ b/docs/examples/account/update-prefs.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.updatePrefs( - {} // prefs -); +const result = await account.updatePrefs({ + prefs: {} +}); console.log(result); diff --git a/docs/examples/account/update-push-target.md b/docs/examples/account/update-push-target.md index d88e22e0..c61f6561 100644 --- a/docs/examples/account/update-push-target.md +++ b/docs/examples/account/update-push-target.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.updatePushTarget( - '', // targetId - '' // identifier -); +const result = await account.updatePushTarget({ + targetId: '', + identifier: '' +}); console.log(result); diff --git a/docs/examples/account/update-recovery.md b/docs/examples/account/update-recovery.md index 9a5ef04f..9e0c4397 100644 --- a/docs/examples/account/update-recovery.md +++ b/docs/examples/account/update-recovery.md @@ -6,10 +6,10 @@ const client = new Client() const account = new Account(client); -const result = await account.updateRecovery( - '', // userId - '', // secret - '' // password -); +const result = await account.updateRecovery({ + userId: '', + secret: '', + password: '' +}); console.log(result); diff --git a/docs/examples/account/update-session.md b/docs/examples/account/update-session.md index 0c8a9e5d..948514d6 100644 --- a/docs/examples/account/update-session.md +++ b/docs/examples/account/update-session.md @@ -6,8 +6,8 @@ const client = new Client() const account = new Account(client); -const result = await account.updateSession( - '' // sessionId -); +const result = await account.updateSession({ + sessionId: '' +}); console.log(result); diff --git a/docs/examples/account/update-verification.md b/docs/examples/account/update-verification.md index c956d5fc..287a7fea 100644 --- a/docs/examples/account/update-verification.md +++ b/docs/examples/account/update-verification.md @@ -6,9 +6,9 @@ const client = new Client() const account = new Account(client); -const result = await account.updateVerification( - '', // userId - '' // secret -); +const result = await account.updateVerification({ + userId: '', + secret: '' +}); console.log(result); diff --git a/docs/examples/avatars/get-browser.md b/docs/examples/avatars/get-browser.md index 433cbe59..6506f2e7 100644 --- a/docs/examples/avatars/get-browser.md +++ b/docs/examples/avatars/get-browser.md @@ -6,11 +6,11 @@ const client = new Client() const avatars = new Avatars(client); -const result = avatars.getBrowser( - Browser.AvantBrowser, // code - 0, // width (optional) - 0, // height (optional) - -1 // quality (optional) -); +const result = avatars.getBrowser({ + code: Browser.AvantBrowser, + width: 0, // optional + height: 0, // optional + quality: -1 // optional +}); console.log(result); diff --git a/docs/examples/avatars/get-credit-card.md b/docs/examples/avatars/get-credit-card.md index bbd0007f..05d3a53b 100644 --- a/docs/examples/avatars/get-credit-card.md +++ b/docs/examples/avatars/get-credit-card.md @@ -6,11 +6,11 @@ const client = new Client() const avatars = new Avatars(client); -const result = avatars.getCreditCard( - CreditCard.AmericanExpress, // code - 0, // width (optional) - 0, // height (optional) - -1 // quality (optional) -); +const result = avatars.getCreditCard({ + code: CreditCard.AmericanExpress, + width: 0, // optional + height: 0, // optional + quality: -1 // optional +}); console.log(result); diff --git a/docs/examples/avatars/get-favicon.md b/docs/examples/avatars/get-favicon.md index ff48c76f..d3931e3e 100644 --- a/docs/examples/avatars/get-favicon.md +++ b/docs/examples/avatars/get-favicon.md @@ -6,8 +6,8 @@ const client = new Client() const avatars = new Avatars(client); -const result = avatars.getFavicon( - 'https://example.com' // url -); +const result = avatars.getFavicon({ + url: 'https://example.com' +}); console.log(result); diff --git a/docs/examples/avatars/get-flag.md b/docs/examples/avatars/get-flag.md index 4e6070d1..651771a0 100644 --- a/docs/examples/avatars/get-flag.md +++ b/docs/examples/avatars/get-flag.md @@ -6,11 +6,11 @@ const client = new Client() const avatars = new Avatars(client); -const result = avatars.getFlag( - Flag.Afghanistan, // code - 0, // width (optional) - 0, // height (optional) - -1 // quality (optional) -); +const result = avatars.getFlag({ + code: Flag.Afghanistan, + width: 0, // optional + height: 0, // optional + quality: -1 // optional +}); console.log(result); diff --git a/docs/examples/avatars/get-image.md b/docs/examples/avatars/get-image.md index 006155ef..e3b89c31 100644 --- a/docs/examples/avatars/get-image.md +++ b/docs/examples/avatars/get-image.md @@ -6,10 +6,10 @@ const client = new Client() const avatars = new Avatars(client); -const result = avatars.getImage( - 'https://example.com', // url - 0, // width (optional) - 0 // height (optional) -); +const result = avatars.getImage({ + url: 'https://example.com', + width: 0, // optional + height: 0 // optional +}); console.log(result); diff --git a/docs/examples/avatars/get-initials.md b/docs/examples/avatars/get-initials.md index a87a6434..3abc399a 100644 --- a/docs/examples/avatars/get-initials.md +++ b/docs/examples/avatars/get-initials.md @@ -6,11 +6,11 @@ const client = new Client() const avatars = new Avatars(client); -const result = avatars.getInitials( - '', // name (optional) - 0, // width (optional) - 0, // height (optional) - '' // background (optional) -); +const result = avatars.getInitials({ + name: '', // optional + width: 0, // optional + height: 0, // optional + background: '' // optional +}); console.log(result); diff --git a/docs/examples/avatars/get-q-r.md b/docs/examples/avatars/get-qr.md similarity index 66% rename from docs/examples/avatars/get-q-r.md rename to docs/examples/avatars/get-qr.md index 177759d9..3cbe72a9 100644 --- a/docs/examples/avatars/get-q-r.md +++ b/docs/examples/avatars/get-qr.md @@ -6,11 +6,11 @@ const client = new Client() const avatars = new Avatars(client); -const result = avatars.getQR( - '', // text - 1, // size (optional) - 0, // margin (optional) - false // download (optional) -); +const result = avatars.getQR({ + text: '', + size: 1, // optional + margin: 0, // optional + download: false // optional +}); console.log(result); diff --git a/docs/examples/databases/create-document.md b/docs/examples/databases/create-document.md index 1b28231e..d0d25bd8 100644 --- a/docs/examples/databases/create-document.md +++ b/docs/examples/databases/create-document.md @@ -6,12 +6,12 @@ const client = new Client() const databases = new Databases(client); -const result = await databases.createDocument( - '', // databaseId - '', // collectionId - '', // documentId - {}, // data - ["read("any")"] // permissions (optional) -); +const result = await databases.createDocument({ + databaseId: '', + collectionId: '', + documentId: '', + data: {}, + permissions: ["read("any")"] // optional +}); console.log(result); diff --git a/docs/examples/databases/decrement-document-attribute.md b/docs/examples/databases/decrement-document-attribute.md index 4c9c2d99..8eb4387c 100644 --- a/docs/examples/databases/decrement-document-attribute.md +++ b/docs/examples/databases/decrement-document-attribute.md @@ -6,13 +6,13 @@ const client = new Client() const databases = new Databases(client); -const result = await databases.decrementDocumentAttribute( - '', // databaseId - '', // collectionId - '', // documentId - '', // attribute - null, // value (optional) - null // min (optional) -); +const result = await databases.decrementDocumentAttribute({ + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + value: null, // optional + min: null // optional +}); console.log(result); diff --git a/docs/examples/databases/delete-document.md b/docs/examples/databases/delete-document.md index 9136107a..828cefdd 100644 --- a/docs/examples/databases/delete-document.md +++ b/docs/examples/databases/delete-document.md @@ -6,10 +6,10 @@ const client = new Client() const databases = new Databases(client); -const result = await databases.deleteDocument( - '', // databaseId - '', // collectionId - '' // documentId -); +const result = await databases.deleteDocument({ + databaseId: '', + collectionId: '', + documentId: '' +}); console.log(result); diff --git a/docs/examples/databases/get-document.md b/docs/examples/databases/get-document.md index 9993e2c9..7d28ee03 100644 --- a/docs/examples/databases/get-document.md +++ b/docs/examples/databases/get-document.md @@ -6,11 +6,11 @@ const client = new Client() const databases = new Databases(client); -const result = await databases.getDocument( - '', // databaseId - '', // collectionId - '', // documentId - [] // queries (optional) -); +const result = await databases.getDocument({ + databaseId: '', + collectionId: '', + documentId: '', + queries: [] // optional +}); console.log(result); diff --git a/docs/examples/databases/increment-document-attribute.md b/docs/examples/databases/increment-document-attribute.md index 3a9d9490..8cb3d816 100644 --- a/docs/examples/databases/increment-document-attribute.md +++ b/docs/examples/databases/increment-document-attribute.md @@ -6,13 +6,13 @@ const client = new Client() const databases = new Databases(client); -const result = await databases.incrementDocumentAttribute( - '', // databaseId - '', // collectionId - '', // documentId - '', // attribute - null, // value (optional) - null // max (optional) -); +const result = await databases.incrementDocumentAttribute({ + databaseId: '', + collectionId: '', + documentId: '', + attribute: '', + value: null, // optional + max: null // optional +}); console.log(result); diff --git a/docs/examples/databases/list-documents.md b/docs/examples/databases/list-documents.md index b2f377e5..8d210b08 100644 --- a/docs/examples/databases/list-documents.md +++ b/docs/examples/databases/list-documents.md @@ -6,10 +6,10 @@ const client = new Client() const databases = new Databases(client); -const result = await databases.listDocuments( - '', // databaseId - '', // collectionId - [] // queries (optional) -); +const result = await databases.listDocuments({ + databaseId: '', + collectionId: '', + queries: [] // optional +}); console.log(result); diff --git a/docs/examples/databases/update-document.md b/docs/examples/databases/update-document.md index 7676ee10..ce4a6f22 100644 --- a/docs/examples/databases/update-document.md +++ b/docs/examples/databases/update-document.md @@ -6,12 +6,12 @@ const client = new Client() const databases = new Databases(client); -const result = await databases.updateDocument( - '', // databaseId - '', // collectionId - '', // documentId - {}, // data (optional) - ["read("any")"] // permissions (optional) -); +const result = await databases.updateDocument({ + databaseId: '', + collectionId: '', + documentId: '', + data: {}, // optional + permissions: ["read("any")"] // optional +}); console.log(result); diff --git a/docs/examples/databases/upsert-document.md b/docs/examples/databases/upsert-document.md index ae423d12..a351ed7d 100644 --- a/docs/examples/databases/upsert-document.md +++ b/docs/examples/databases/upsert-document.md @@ -6,12 +6,12 @@ const client = new Client() const databases = new Databases(client); -const result = await databases.upsertDocument( - '', // databaseId - '', // collectionId - '', // documentId - {}, // data - ["read("any")"] // permissions (optional) -); +const result = await databases.upsertDocument({ + databaseId: '', + collectionId: '', + documentId: '', + data: {}, + permissions: ["read("any")"] // optional +}); console.log(result); diff --git a/docs/examples/functions/create-execution.md b/docs/examples/functions/create-execution.md index 72c71f77..b9e6682f 100644 --- a/docs/examples/functions/create-execution.md +++ b/docs/examples/functions/create-execution.md @@ -6,14 +6,14 @@ const client = new Client() const functions = new Functions(client); -const result = await functions.createExecution( - '', // functionId - '', // body (optional) - false, // async (optional) - '', // path (optional) - ExecutionMethod.GET, // method (optional) - {}, // headers (optional) - '' // scheduledAt (optional) -); +const result = await functions.createExecution({ + functionId: '', + body: '', // optional + async: false, // optional + path: '', // optional + method: ExecutionMethod.GET, // optional + headers: {}, // optional + scheduledAt: '' // optional +}); console.log(result); diff --git a/docs/examples/functions/get-execution.md b/docs/examples/functions/get-execution.md index 848747ea..2ef4e9f8 100644 --- a/docs/examples/functions/get-execution.md +++ b/docs/examples/functions/get-execution.md @@ -6,9 +6,9 @@ const client = new Client() const functions = new Functions(client); -const result = await functions.getExecution( - '', // functionId - '' // executionId -); +const result = await functions.getExecution({ + functionId: '', + executionId: '' +}); console.log(result); diff --git a/docs/examples/functions/list-executions.md b/docs/examples/functions/list-executions.md index 346f8c7e..7b046dde 100644 --- a/docs/examples/functions/list-executions.md +++ b/docs/examples/functions/list-executions.md @@ -6,9 +6,9 @@ const client = new Client() const functions = new Functions(client); -const result = await functions.listExecutions( - '', // functionId - [] // queries (optional) -); +const result = await functions.listExecutions({ + functionId: '', + queries: [] // optional +}); console.log(result); diff --git a/docs/examples/graphql/mutation.md b/docs/examples/graphql/mutation.md index 3292a5da..dbc27ff1 100644 --- a/docs/examples/graphql/mutation.md +++ b/docs/examples/graphql/mutation.md @@ -6,8 +6,8 @@ const client = new Client() const graphql = new Graphql(client); -const result = await graphql.mutation( - {} // query -); +const result = await graphql.mutation({ + query: {} +}); console.log(result); diff --git a/docs/examples/graphql/query.md b/docs/examples/graphql/query.md index a00c517a..560b7e5c 100644 --- a/docs/examples/graphql/query.md +++ b/docs/examples/graphql/query.md @@ -6,8 +6,8 @@ const client = new Client() const graphql = new Graphql(client); -const result = await graphql.query( - {} // query -); +const result = await graphql.query({ + query: {} +}); console.log(result); diff --git a/docs/examples/locale/list-countries-e-u.md b/docs/examples/locale/list-countries-eu.md similarity index 100% rename from docs/examples/locale/list-countries-e-u.md rename to docs/examples/locale/list-countries-eu.md diff --git a/docs/examples/messaging/create-subscriber.md b/docs/examples/messaging/create-subscriber.md index c950e90b..2057f1da 100644 --- a/docs/examples/messaging/create-subscriber.md +++ b/docs/examples/messaging/create-subscriber.md @@ -6,10 +6,10 @@ const client = new Client() const messaging = new Messaging(client); -const result = await messaging.createSubscriber( - '', // topicId - '', // subscriberId - '' // targetId -); +const result = await messaging.createSubscriber({ + topicId: '', + subscriberId: '', + targetId: '' +}); console.log(result); diff --git a/docs/examples/messaging/delete-subscriber.md b/docs/examples/messaging/delete-subscriber.md index 5004b59c..38545f62 100644 --- a/docs/examples/messaging/delete-subscriber.md +++ b/docs/examples/messaging/delete-subscriber.md @@ -6,9 +6,9 @@ const client = new Client() const messaging = new Messaging(client); -const result = await messaging.deleteSubscriber( - '', // topicId - '' // subscriberId -); +const result = await messaging.deleteSubscriber({ + topicId: '', + subscriberId: '' +}); console.log(result); diff --git a/docs/examples/storage/create-file.md b/docs/examples/storage/create-file.md index efbfd607..4a44d3ca 100644 --- a/docs/examples/storage/create-file.md +++ b/docs/examples/storage/create-file.md @@ -6,11 +6,11 @@ const client = new Client() const storage = new Storage(client); -const result = await storage.createFile( - '', // bucketId - '', // fileId - await pickSingle(), // file - ["read("any")"] // permissions (optional) -); +const result = await storage.createFile({ + bucketId: '', + fileId: '', + file: await pickSingle(), + permissions: ["read("any")"] // optional +}); console.log(result); diff --git a/docs/examples/storage/delete-file.md b/docs/examples/storage/delete-file.md index 1a436ac8..776ec7fa 100644 --- a/docs/examples/storage/delete-file.md +++ b/docs/examples/storage/delete-file.md @@ -6,9 +6,9 @@ const client = new Client() const storage = new Storage(client); -const result = await storage.deleteFile( - '', // bucketId - '' // fileId -); +const result = await storage.deleteFile({ + bucketId: '', + fileId: '' +}); console.log(result); diff --git a/docs/examples/storage/get-file-download.md b/docs/examples/storage/get-file-download.md index e21bad67..317141c8 100644 --- a/docs/examples/storage/get-file-download.md +++ b/docs/examples/storage/get-file-download.md @@ -6,10 +6,10 @@ const client = new Client() const storage = new Storage(client); -const result = storage.getFileDownload( - '', // bucketId - '', // fileId - '' // token (optional) -); +const result = storage.getFileDownload({ + bucketId: '', + fileId: '', + token: '' // optional +}); console.log(result); diff --git a/docs/examples/storage/get-file-preview.md b/docs/examples/storage/get-file-preview.md index 6f116c5d..94623fb0 100644 --- a/docs/examples/storage/get-file-preview.md +++ b/docs/examples/storage/get-file-preview.md @@ -6,21 +6,21 @@ const client = new Client() const storage = new Storage(client); -const result = storage.getFilePreview( - '', // bucketId - '', // fileId - 0, // width (optional) - 0, // height (optional) - ImageGravity.Center, // gravity (optional) - -1, // quality (optional) - 0, // borderWidth (optional) - '', // borderColor (optional) - 0, // borderRadius (optional) - 0, // opacity (optional) - -360, // rotation (optional) - '', // background (optional) - ImageFormat.Jpg, // output (optional) - '' // token (optional) -); +const result = storage.getFilePreview({ + bucketId: '', + fileId: '', + width: 0, // optional + height: 0, // optional + gravity: ImageGravity.Center, // optional + quality: -1, // optional + borderWidth: 0, // optional + borderColor: '', // optional + borderRadius: 0, // optional + opacity: 0, // optional + rotation: -360, // optional + background: '', // optional + output: ImageFormat.Jpg, // optional + token: '' // optional +}); console.log(result); diff --git a/docs/examples/storage/get-file-view.md b/docs/examples/storage/get-file-view.md index 9b229f6a..bacd1088 100644 --- a/docs/examples/storage/get-file-view.md +++ b/docs/examples/storage/get-file-view.md @@ -6,10 +6,10 @@ const client = new Client() const storage = new Storage(client); -const result = storage.getFileView( - '', // bucketId - '', // fileId - '' // token (optional) -); +const result = storage.getFileView({ + bucketId: '', + fileId: '', + token: '' // optional +}); console.log(result); diff --git a/docs/examples/storage/get-file.md b/docs/examples/storage/get-file.md index 6d358ada..f2841824 100644 --- a/docs/examples/storage/get-file.md +++ b/docs/examples/storage/get-file.md @@ -6,9 +6,9 @@ const client = new Client() const storage = new Storage(client); -const result = await storage.getFile( - '', // bucketId - '' // fileId -); +const result = await storage.getFile({ + bucketId: '', + fileId: '' +}); console.log(result); diff --git a/docs/examples/storage/list-files.md b/docs/examples/storage/list-files.md index 19099b12..4c6e159d 100644 --- a/docs/examples/storage/list-files.md +++ b/docs/examples/storage/list-files.md @@ -6,10 +6,10 @@ const client = new Client() const storage = new Storage(client); -const result = await storage.listFiles( - '', // bucketId - [], // queries (optional) - '' // search (optional) -); +const result = await storage.listFiles({ + bucketId: '', + queries: [], // optional + search: '' // optional +}); console.log(result); diff --git a/docs/examples/storage/update-file.md b/docs/examples/storage/update-file.md index d4ed68a3..2a8092f8 100644 --- a/docs/examples/storage/update-file.md +++ b/docs/examples/storage/update-file.md @@ -6,11 +6,11 @@ const client = new Client() const storage = new Storage(client); -const result = await storage.updateFile( - '', // bucketId - '', // fileId - '', // name (optional) - ["read("any")"] // permissions (optional) -); +const result = await storage.updateFile({ + bucketId: '', + fileId: '', + name: '', // optional + permissions: ["read("any")"] // optional +}); console.log(result); diff --git a/docs/examples/tablesdb/create-row.md b/docs/examples/tablesdb/create-row.md new file mode 100644 index 00000000..43018476 --- /dev/null +++ b/docs/examples/tablesdb/create-row.md @@ -0,0 +1,17 @@ +import { Client, TablesDB } from "react-native-appwrite"; + +const client = new Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +const tablesDB = new TablesDB(client); + +const result = await tablesDB.createRow({ + databaseId: '', + tableId: '', + rowId: '', + data: {}, + permissions: ["read("any")"] // optional +}); + +console.log(result); diff --git a/docs/examples/tablesdb/decrement-row-column.md b/docs/examples/tablesdb/decrement-row-column.md new file mode 100644 index 00000000..6b47c18c --- /dev/null +++ b/docs/examples/tablesdb/decrement-row-column.md @@ -0,0 +1,18 @@ +import { Client, TablesDB } from "react-native-appwrite"; + +const client = new Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +const tablesDB = new TablesDB(client); + +const result = await tablesDB.decrementRowColumn({ + databaseId: '', + tableId: '', + rowId: '', + column: '', + value: null, // optional + min: null // optional +}); + +console.log(result); diff --git a/docs/examples/tablesdb/delete-row.md b/docs/examples/tablesdb/delete-row.md new file mode 100644 index 00000000..624f1a19 --- /dev/null +++ b/docs/examples/tablesdb/delete-row.md @@ -0,0 +1,15 @@ +import { Client, TablesDB } from "react-native-appwrite"; + +const client = new Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +const tablesDB = new TablesDB(client); + +const result = await tablesDB.deleteRow({ + databaseId: '', + tableId: '', + rowId: '' +}); + +console.log(result); diff --git a/docs/examples/tablesdb/get-row.md b/docs/examples/tablesdb/get-row.md new file mode 100644 index 00000000..081db46f --- /dev/null +++ b/docs/examples/tablesdb/get-row.md @@ -0,0 +1,16 @@ +import { Client, TablesDB } from "react-native-appwrite"; + +const client = new Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +const tablesDB = new TablesDB(client); + +const result = await tablesDB.getRow({ + databaseId: '', + tableId: '', + rowId: '', + queries: [] // optional +}); + +console.log(result); diff --git a/docs/examples/tablesdb/increment-row-column.md b/docs/examples/tablesdb/increment-row-column.md new file mode 100644 index 00000000..62b7dd0c --- /dev/null +++ b/docs/examples/tablesdb/increment-row-column.md @@ -0,0 +1,18 @@ +import { Client, TablesDB } from "react-native-appwrite"; + +const client = new Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +const tablesDB = new TablesDB(client); + +const result = await tablesDB.incrementRowColumn({ + databaseId: '', + tableId: '', + rowId: '', + column: '', + value: null, // optional + max: null // optional +}); + +console.log(result); diff --git a/docs/examples/tablesdb/list-rows.md b/docs/examples/tablesdb/list-rows.md new file mode 100644 index 00000000..6148e97e --- /dev/null +++ b/docs/examples/tablesdb/list-rows.md @@ -0,0 +1,15 @@ +import { Client, TablesDB } from "react-native-appwrite"; + +const client = new Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +const tablesDB = new TablesDB(client); + +const result = await tablesDB.listRows({ + databaseId: '', + tableId: '', + queries: [] // optional +}); + +console.log(result); diff --git a/docs/examples/tablesdb/update-row.md b/docs/examples/tablesdb/update-row.md new file mode 100644 index 00000000..01ed6e6a --- /dev/null +++ b/docs/examples/tablesdb/update-row.md @@ -0,0 +1,17 @@ +import { Client, TablesDB } from "react-native-appwrite"; + +const client = new Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +const tablesDB = new TablesDB(client); + +const result = await tablesDB.updateRow({ + databaseId: '', + tableId: '', + rowId: '', + data: {}, // optional + permissions: ["read("any")"] // optional +}); + +console.log(result); diff --git a/docs/examples/tablesdb/upsert-row.md b/docs/examples/tablesdb/upsert-row.md new file mode 100644 index 00000000..72fad15a --- /dev/null +++ b/docs/examples/tablesdb/upsert-row.md @@ -0,0 +1,17 @@ +import { Client, TablesDB } from "react-native-appwrite"; + +const client = new Client() + .setEndpoint('https://.cloud.appwrite.io/v1') // Your API Endpoint + .setProject(''); // Your project ID + +const tablesDB = new TablesDB(client); + +const result = await tablesDB.upsertRow({ + databaseId: '', + tableId: '', + rowId: '', + data: {}, // optional + permissions: ["read("any")"] // optional +}); + +console.log(result); diff --git a/docs/examples/teams/create-membership.md b/docs/examples/teams/create-membership.md index 680fdb2a..e89d2ded 100644 --- a/docs/examples/teams/create-membership.md +++ b/docs/examples/teams/create-membership.md @@ -6,14 +6,14 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.createMembership( - '', // teamId - [], // roles - 'email@example.com', // email (optional) - '', // userId (optional) - '+12065550100', // phone (optional) - 'https://example.com', // url (optional) - '' // name (optional) -); +const result = await teams.createMembership({ + teamId: '', + roles: [], + email: 'email@example.com', // optional + userId: '', // optional + phone: '+12065550100', // optional + url: 'https://example.com', // optional + name: '' // optional +}); console.log(result); diff --git a/docs/examples/teams/create.md b/docs/examples/teams/create.md index 51aaee35..6c8dbbba 100644 --- a/docs/examples/teams/create.md +++ b/docs/examples/teams/create.md @@ -6,10 +6,10 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.create( - '', // teamId - '', // name - [] // roles (optional) -); +const result = await teams.create({ + teamId: '', + name: '', + roles: [] // optional +}); console.log(result); diff --git a/docs/examples/teams/delete-membership.md b/docs/examples/teams/delete-membership.md index 37bdc7f8..b881c5ac 100644 --- a/docs/examples/teams/delete-membership.md +++ b/docs/examples/teams/delete-membership.md @@ -6,9 +6,9 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.deleteMembership( - '', // teamId - '' // membershipId -); +const result = await teams.deleteMembership({ + teamId: '', + membershipId: '' +}); console.log(result); diff --git a/docs/examples/teams/delete.md b/docs/examples/teams/delete.md index fe67eaff..8c98139c 100644 --- a/docs/examples/teams/delete.md +++ b/docs/examples/teams/delete.md @@ -6,8 +6,8 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.delete( - '' // teamId -); +const result = await teams.delete({ + teamId: '' +}); console.log(result); diff --git a/docs/examples/teams/get-membership.md b/docs/examples/teams/get-membership.md index 2b253c8b..46cdc412 100644 --- a/docs/examples/teams/get-membership.md +++ b/docs/examples/teams/get-membership.md @@ -6,9 +6,9 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.getMembership( - '', // teamId - '' // membershipId -); +const result = await teams.getMembership({ + teamId: '', + membershipId: '' +}); console.log(result); diff --git a/docs/examples/teams/get-prefs.md b/docs/examples/teams/get-prefs.md index 943ed1a1..0e3b4894 100644 --- a/docs/examples/teams/get-prefs.md +++ b/docs/examples/teams/get-prefs.md @@ -6,8 +6,8 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.getPrefs( - '' // teamId -); +const result = await teams.getPrefs({ + teamId: '' +}); console.log(result); diff --git a/docs/examples/teams/get.md b/docs/examples/teams/get.md index 9267b57e..63053656 100644 --- a/docs/examples/teams/get.md +++ b/docs/examples/teams/get.md @@ -6,8 +6,8 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.get( - '' // teamId -); +const result = await teams.get({ + teamId: '' +}); console.log(result); diff --git a/docs/examples/teams/list-memberships.md b/docs/examples/teams/list-memberships.md index 4444bcd6..12f71549 100644 --- a/docs/examples/teams/list-memberships.md +++ b/docs/examples/teams/list-memberships.md @@ -6,10 +6,10 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.listMemberships( - '', // teamId - [], // queries (optional) - '' // search (optional) -); +const result = await teams.listMemberships({ + teamId: '', + queries: [], // optional + search: '' // optional +}); console.log(result); diff --git a/docs/examples/teams/list.md b/docs/examples/teams/list.md index 779538a7..f9ca4c40 100644 --- a/docs/examples/teams/list.md +++ b/docs/examples/teams/list.md @@ -6,9 +6,9 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.list( - [], // queries (optional) - '' // search (optional) -); +const result = await teams.list({ + queries: [], // optional + search: '' // optional +}); console.log(result); diff --git a/docs/examples/teams/update-membership-status.md b/docs/examples/teams/update-membership-status.md index c8edbf08..0aba8065 100644 --- a/docs/examples/teams/update-membership-status.md +++ b/docs/examples/teams/update-membership-status.md @@ -6,11 +6,11 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.updateMembershipStatus( - '', // teamId - '', // membershipId - '', // userId - '' // secret -); +const result = await teams.updateMembershipStatus({ + teamId: '', + membershipId: '', + userId: '', + secret: '' +}); console.log(result); diff --git a/docs/examples/teams/update-membership.md b/docs/examples/teams/update-membership.md index 347cbdd0..ada28634 100644 --- a/docs/examples/teams/update-membership.md +++ b/docs/examples/teams/update-membership.md @@ -6,10 +6,10 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.updateMembership( - '', // teamId - '', // membershipId - [] // roles -); +const result = await teams.updateMembership({ + teamId: '', + membershipId: '', + roles: [] +}); console.log(result); diff --git a/docs/examples/teams/update-name.md b/docs/examples/teams/update-name.md index 0ab4aa1c..251ff26a 100644 --- a/docs/examples/teams/update-name.md +++ b/docs/examples/teams/update-name.md @@ -6,9 +6,9 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.updateName( - '', // teamId - '' // name -); +const result = await teams.updateName({ + teamId: '', + name: '' +}); console.log(result); diff --git a/docs/examples/teams/update-prefs.md b/docs/examples/teams/update-prefs.md index fda16a05..49045021 100644 --- a/docs/examples/teams/update-prefs.md +++ b/docs/examples/teams/update-prefs.md @@ -6,9 +6,9 @@ const client = new Client() const teams = new Teams(client); -const result = await teams.updatePrefs( - '', // teamId - {} // prefs -); +const result = await teams.updatePrefs({ + teamId: '', + prefs: {} +}); console.log(result); diff --git a/package.json b/package.json index 92479c87..d362a5d1 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "react-native-appwrite", "homepage": "https://appwrite.io/support", "description": "Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API", - "version": "0.11.0", + "version": "0.12.0", "license": "BSD-3-Clause", "main": "dist/cjs/sdk.js", "exports": { diff --git a/src/client.ts b/src/client.ts index 22628773..e0f1ba1e 100644 --- a/src/client.ts +++ b/src/client.ts @@ -115,8 +115,8 @@ class Client { 'x-sdk-name': 'React Native', 'x-sdk-platform': 'client', 'x-sdk-language': 'reactnative', - 'x-sdk-version': '0.11.0', - 'X-Appwrite-Response-Format': '1.7.0', + 'x-sdk-version': '0.12.0', + 'X-Appwrite-Response-Format': '1.8.0', }; /** diff --git a/src/index.ts b/src/index.ts index bbc74cce..e8b51b8a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,6 +7,7 @@ export { Graphql } from './services/graphql'; export { Locale } from './services/locale'; export { Messaging } from './services/messaging'; export { Storage } from './services/storage'; +export { TablesDB } from './services/tables-db'; export { Teams } from './services/teams'; export type { Models, Payload, RealtimeResponseEvent, UploadProgress } from './client'; export type { QueryTypes, QueryTypesList } from './query'; diff --git a/src/models.ts b/src/models.ts index 4887e222..268baa97 100644 --- a/src/models.ts +++ b/src/models.ts @@ -2,12 +2,26 @@ export namespace Models { declare const __default: unique symbol; + /** + * Rows List + */ + export type RowList = { + /** + * Total number of rows that matched your query. + */ + total: number; + /** + * List of rows. + */ + rows: Row[]; + } + /** * Documents List */ export type DocumentList = { /** - * Total number of documents documents that matched your query. + * Total number of documents that matched your query. */ total: number; /** @@ -21,7 +35,7 @@ export namespace Models { */ export type SessionList = { /** - * Total number of sessions documents that matched your query. + * Total number of sessions that matched your query. */ total: number; /** @@ -35,7 +49,7 @@ export namespace Models { */ export type IdentityList = { /** - * Total number of identities documents that matched your query. + * Total number of identities that matched your query. */ total: number; /** @@ -49,7 +63,7 @@ export namespace Models { */ export type LogList = { /** - * Total number of logs documents that matched your query. + * Total number of logs that matched your query. */ total: number; /** @@ -63,7 +77,7 @@ export namespace Models { */ export type FileList = { /** - * Total number of files documents that matched your query. + * Total number of files that matched your query. */ total: number; /** @@ -77,7 +91,7 @@ export namespace Models { */ export type TeamList = { /** - * Total number of teams documents that matched your query. + * Total number of teams that matched your query. */ total: number; /** @@ -91,7 +105,7 @@ export namespace Models { */ export type MembershipList = { /** - * Total number of memberships documents that matched your query. + * Total number of memberships that matched your query. */ total: number; /** @@ -105,7 +119,7 @@ export namespace Models { */ export type ExecutionList = { /** - * Total number of executions documents that matched your query. + * Total number of executions that matched your query. */ total: number; /** @@ -119,7 +133,7 @@ export namespace Models { */ export type CountryList = { /** - * Total number of countries documents that matched your query. + * Total number of countries that matched your query. */ total: number; /** @@ -133,7 +147,7 @@ export namespace Models { */ export type ContinentList = { /** - * Total number of continents documents that matched your query. + * Total number of continents that matched your query. */ total: number; /** @@ -147,7 +161,7 @@ export namespace Models { */ export type LanguageList = { /** - * Total number of languages documents that matched your query. + * Total number of languages that matched your query. */ total: number; /** @@ -161,7 +175,7 @@ export namespace Models { */ export type CurrencyList = { /** - * Total number of currencies documents that matched your query. + * Total number of currencies that matched your query. */ total: number; /** @@ -175,7 +189,7 @@ export namespace Models { */ export type PhoneList = { /** - * Total number of phones documents that matched your query. + * Total number of phones that matched your query. */ total: number; /** @@ -189,7 +203,7 @@ export namespace Models { */ export type LocaleCodeList = { /** - * Total number of localeCodes documents that matched your query. + * Total number of localeCodes that matched your query. */ total: number; /** @@ -198,6 +212,45 @@ export namespace Models { localeCodes: LocaleCode[]; } + /** + * Row + */ + export type Row = { + /** + * Row ID. + */ + $id: string; + /** + * Row automatically incrementing ID. + */ + $sequence: number; + /** + * Table ID. + */ + $tableId: string; + /** + * Database ID. + */ + $databaseId: string; + /** + * Row creation date in ISO 8601 format. + */ + $createdAt: string; + /** + * Row update date in ISO 8601 format. + */ + $updatedAt: string; + /** + * Row permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + */ + $permissions: string[]; + } + + export type DefaultRow = Row & { + [key: string]: any; + [__default]: true; + }; + /** * Document */ @@ -237,12 +290,6 @@ export namespace Models { [__default]: true; }; - export type DataWithoutDocumentKeys = { - [K in string]: any; - } & { - [K in keyof Document]?: never; - }; - /** * Log */ @@ -536,12 +583,6 @@ export namespace Models { [__default]: true; }; - export type DataWithoutPreferencesKeys = { - [K in string]: any; - } & { - [K in keyof Preferences]?: never; - }; - /** * Session */ @@ -949,7 +990,7 @@ export namespace Models { */ $createdAt: string; /** - * Execution upate date in ISO 8601 format. + * Execution update date in ISO 8601 format. */ $updatedAt: string; /** @@ -960,6 +1001,10 @@ export namespace Models { * Function ID. */ functionId: string; + /** + * Function's deployment ID used to create the execution. + */ + deploymentId: string; /** * The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. */ diff --git a/src/query.ts b/src/query.ts index 229d6c85..09576a46 100644 --- a/src/query.ts +++ b/src/query.ts @@ -90,9 +90,104 @@ export class Query { static offset = (offset: number): string => new Query("offset", undefined, offset).toString(); + /** + * Filter resources where attribute contains the specified value. + * + * @param {string} attribute + * @param {string | string[]} value + * @returns {string} + */ static contains = (attribute: string, value: string | string[]): string => new Query("contains", attribute, value).toString(); + /** + * Filter resources where attribute does not contain the specified value. + * + * @param {string} attribute + * @param {string | string[]} value + * @returns {string} + */ + static notContains = (attribute: string, value: string | string[]): string => + new Query("notContains", attribute, value).toString(); + + /** + * Filter resources by searching attribute for value (inverse of search). + * A fulltext index on attribute is required for this query to work. + * + * @param {string} attribute + * @param {string} value + * @returns {string} + */ + static notSearch = (attribute: string, value: string): string => + new Query("notSearch", attribute, value).toString(); + + /** + * Filter resources where attribute is not between start and end (exclusive). + * + * @param {string} attribute + * @param {string | number} start + * @param {string | number} end + * @returns {string} + */ + static notBetween = (attribute: string, start: string | number, end: string | number): string => + new Query("notBetween", attribute, [start, end] as QueryTypesList).toString(); + + /** + * Filter resources where attribute does not start with value. + * + * @param {string} attribute + * @param {string} value + * @returns {string} + */ + static notStartsWith = (attribute: string, value: string): string => + new Query("notStartsWith", attribute, value).toString(); + + /** + * Filter resources where attribute does not end with value. + * + * @param {string} attribute + * @param {string} value + * @returns {string} + */ + static notEndsWith = (attribute: string, value: string): string => + new Query("notEndsWith", attribute, value).toString(); + + /** + * Filter resources where document was created before date. + * + * @param {string} value + * @returns {string} + */ + static createdBefore = (value: string): string => + new Query("createdBefore", undefined, value).toString(); + + /** + * Filter resources where document was created after date. + * + * @param {string} value + * @returns {string} + */ + static createdAfter = (value: string): string => + new Query("createdAfter", undefined, value).toString(); + + /** + * Filter resources where document was updated before date. + * + * @param {string} value + * @returns {string} + */ + static updatedBefore = (value: string): string => + new Query("updatedBefore", undefined, value).toString(); + + /** + * Filter resources where document was updated after date. + * + * @param {string} value + * @returns {string} + */ + static updatedAfter = (value: string): string => + new Query("updatedAfter", undefined, value).toString(); + static or = (queries: string[]) => new Query("or", undefined, queries.map((query) => JSON.parse(query))).toString(); diff --git a/src/services/account.ts b/src/services/account.ts index 713f7369..0fdb10be 100644 --- a/src/services/account.ts +++ b/src/services/account.ts @@ -32,22 +32,50 @@ export class Account extends Service { } /** - * Use this endpoint to allow a new user to register a new account in your - * project. After the user registration completes successfully, you can use - * the - * [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) - * route to start verifying the user email address. To allow the new user to - * login to their new account, you need to create a new [account - * session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). - * - * @param {string} userId - * @param {string} email - * @param {string} password - * @param {string} name + * Use this endpoint to allow a new user to register a new account in your project. After the user registration completes successfully, you can use the [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) route to start verifying the user email address. To allow the new user to login to their new account, you need to create a new [account session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + * + * @param {string} params.userId - User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {string} params.email - User email. + * @param {string} params.password - New user password. Must be between 8 and 256 chars. + * @param {string} params.name - User name. Max length: 128 chars. * @throws {AppwriteException} * @returns {Promise} */ - create(userId: string, email: string, password: string, name?: string): Promise> { + create(params: { userId: string, email: string, password: string, name?: string }): Promise>; + /** + * Use this endpoint to allow a new user to register a new account in your project. After the user registration completes successfully, you can use the [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification) route to start verifying the user email address. To allow the new user to login to their new account, you need to create a new [account session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession). + * + * @param {string} userId - User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {string} email - User email. + * @param {string} password - New user password. Must be between 8 and 256 chars. + * @param {string} name - User name. Max length: 128 chars. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + create(userId: string, email: string, password: string, name?: string): Promise>; + create( + paramsOrFirst: { userId: string, email: string, password: string, name?: string } | string, + ...rest: [(string)?, (string)?, (string)?] + ): Promise> { + let params: { userId: string, email: string, password: string, name?: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { userId: string, email: string, password: string, name?: string }; + } else { + params = { + userId: paramsOrFirst as string, + email: rest[0] as string, + password: rest[1] as string, + name: rest[2] as string + }; + } + + const userId = params.userId; + const email = params.email; + const password = params.password; + const name = params.name; + if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } @@ -86,21 +114,46 @@ export class Account extends Service { } /** - * Update currently logged in user account email address. After changing user - * address, the user confirmation status will get reset. A new confirmation - * email is not sent automatically however you can use the send confirmation - * email endpoint again to send the confirmation email. For security measures, - * user password is required to complete this request. - * This endpoint can also be used to convert an anonymous account to a normal - * one, by passing an email address and a new password. + * Update currently logged in user account email address. After changing user address, the user confirmation status will get reset. A new confirmation email is not sent automatically however you can use the send confirmation email endpoint again to send the confirmation email. For security measures, user password is required to complete this request. + * This endpoint can also be used to convert an anonymous account to a normal one, by passing an email address and a new password. * * - * @param {string} email - * @param {string} password + * @param {string} params.email - User email. + * @param {string} params.password - User password. Must be at least 8 chars. * @throws {AppwriteException} * @returns {Promise} */ - updateEmail(email: string, password: string): Promise> { + updateEmail(params: { email: string, password: string }): Promise>; + /** + * Update currently logged in user account email address. After changing user address, the user confirmation status will get reset. A new confirmation email is not sent automatically however you can use the send confirmation email endpoint again to send the confirmation email. For security measures, user password is required to complete this request. + * This endpoint can also be used to convert an anonymous account to a normal one, by passing an email address and a new password. + * + * + * @param {string} email - User email. + * @param {string} password - User password. Must be at least 8 chars. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateEmail(email: string, password: string): Promise>; + updateEmail( + paramsOrFirst: { email: string, password: string } | string, + ...rest: [(string)?] + ): Promise> { + let params: { email: string, password: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { email: string, password: string }; + } else { + params = { + email: paramsOrFirst as string, + password: rest[0] as string + }; + } + + const email = params.email; + const password = params.password; + if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } @@ -129,11 +182,35 @@ export class Account extends Service { /** * Get the list of identities for the currently logged in user. * - * @param {string[]} queries + * @param {string[]} params.queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, provider, providerUid, providerEmail, providerAccessTokenExpiry * @throws {AppwriteException} * @returns {Promise} */ - listIdentities(queries?: string[]): Promise { + listIdentities(params?: { queries?: string[] }): Promise; + /** + * Get the list of identities for the currently logged in user. + * + * @param {string[]} queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, provider, providerUid, providerEmail, providerAccessTokenExpiry + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + listIdentities(queries?: string[]): Promise; + listIdentities( + paramsOrFirst?: { queries?: string[] } | string[] + ): Promise { + let params: { queries?: string[] }; + + if (!paramsOrFirst || (paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { queries?: string[] }; + } else { + params = { + queries: paramsOrFirst as string[] + }; + } + + const queries = params.queries; + const apiPath = '/account/identities'; const payload: Payload = {}; @@ -149,11 +226,35 @@ export class Account extends Service { /** * Delete an identity by its unique ID. * - * @param {string} identityId + * @param {string} params.identityId - Identity ID. * @throws {AppwriteException} * @returns {Promise} */ - deleteIdentity(identityId: string): Promise<{}> { + deleteIdentity(params: { identityId: string }): Promise<{}>; + /** + * Delete an identity by its unique ID. + * + * @param {string} identityId - Identity ID. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + deleteIdentity(identityId: string): Promise<{}>; + deleteIdentity( + paramsOrFirst: { identityId: string } | string + ): Promise<{}> { + let params: { identityId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { identityId: string }; + } else { + params = { + identityId: paramsOrFirst as string + }; + } + + const identityId = params.identityId; + if (typeof identityId === 'undefined') { throw new AppwriteException('Missing required parameter: "identityId"'); } @@ -168,11 +269,7 @@ export class Account extends Service { } /** - * Use this endpoint to create a JSON Web Token. You can use the resulting JWT - * to authenticate on behalf of the current user when working with the - * Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - * from its creation and will be invalid if the user will logout in that time - * frame. + * Use this endpoint to create a JSON Web Token. You can use the resulting JWT to authenticate on behalf of the current user when working with the Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes from its creation and will be invalid if the user will logout in that time frame. * * @throws {AppwriteException} * @returns {Promise} @@ -188,14 +285,37 @@ export class Account extends Service { } /** - * Get the list of latest security activity logs for the currently logged in - * user. Each log returns user IP address, location and date and time of log. + * Get the list of latest security activity logs for the currently logged in user. Each log returns user IP address, location and date and time of log. * - * @param {string[]} queries + * @param {string[]} params.queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset * @throws {AppwriteException} * @returns {Promise} */ - listLogs(queries?: string[]): Promise { + listLogs(params?: { queries?: string[] }): Promise; + /** + * Get the list of latest security activity logs for the currently logged in user. Each log returns user IP address, location and date and time of log. + * + * @param {string[]} queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + listLogs(queries?: string[]): Promise; + listLogs( + paramsOrFirst?: { queries?: string[] } | string[] + ): Promise { + let params: { queries?: string[] }; + + if (!paramsOrFirst || (paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { queries?: string[] }; + } else { + params = { + queries: paramsOrFirst as string[] + }; + } + + const queries = params.queries; + const apiPath = '/account/logs'; const payload: Payload = {}; @@ -211,11 +331,35 @@ export class Account extends Service { /** * Enable or disable MFA on an account. * - * @param {boolean} mfa + * @param {boolean} params.mfa - Enable or disable MFA. * @throws {AppwriteException} * @returns {Promise} */ - updateMFA(mfa: boolean): Promise> { + updateMFA(params: { mfa: boolean }): Promise>; + /** + * Enable or disable MFA on an account. + * + * @param {boolean} mfa - Enable or disable MFA. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateMFA(mfa: boolean): Promise>; + updateMFA( + paramsOrFirst: { mfa: boolean } | boolean + ): Promise> { + let params: { mfa: boolean }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { mfa: boolean }; + } else { + params = { + mfa: paramsOrFirst as boolean + }; + } + + const mfa = params.mfa; + if (typeof mfa === 'undefined') { throw new AppwriteException('Missing required parameter: "mfa"'); } @@ -234,16 +378,38 @@ export class Account extends Service { } /** - * Add an authenticator app to be used as an MFA factor. Verify the - * authenticator using the [verify - * authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - * method. + * Add an authenticator app to be used as an MFA factor. Verify the authenticator using the [verify authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) method. * - * @param {AuthenticatorType} type + * @param {AuthenticatorType} params.type - Type of authenticator. Must be `totp` * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `Account.createMFAAuthenticator` instead. + */ + createMfaAuthenticator(params: { type: AuthenticatorType }): Promise; + /** + * Add an authenticator app to be used as an MFA factor. Verify the authenticator using the [verify authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) method. + * + * @param {AuthenticatorType} type - Type of authenticator. Must be `totp` + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. */ - createMfaAuthenticator(type: AuthenticatorType): Promise { + createMfaAuthenticator(type: AuthenticatorType): Promise; + createMfaAuthenticator( + paramsOrFirst: { type: AuthenticatorType } | AuthenticatorType + ): Promise { + let params: { type: AuthenticatorType }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'type' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { type: AuthenticatorType }; + } else { + params = { + type: paramsOrFirst as AuthenticatorType + }; + } + + const type = params.type; + if (typeof type === 'undefined') { throw new AppwriteException('Missing required parameter: "type"'); } @@ -258,16 +424,146 @@ export class Account extends Service { } /** - * Verify an authenticator app after adding it using the [add - * authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - * method. + * Add an authenticator app to be used as an MFA factor. Verify the authenticator using the [verify authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) method. * - * @param {AuthenticatorType} type - * @param {string} otp + * @param {AuthenticatorType} params.type - Type of authenticator. Must be `totp` * @throws {AppwriteException} * @returns {Promise} */ - updateMfaAuthenticator(type: AuthenticatorType, otp: string): Promise> { + createMFAAuthenticator(params: { type: AuthenticatorType }): Promise; + /** + * Add an authenticator app to be used as an MFA factor. Verify the authenticator using the [verify authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) method. + * + * @param {AuthenticatorType} type - Type of authenticator. Must be `totp` + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createMFAAuthenticator(type: AuthenticatorType): Promise; + createMFAAuthenticator( + paramsOrFirst: { type: AuthenticatorType } | AuthenticatorType + ): Promise { + let params: { type: AuthenticatorType }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'type' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { type: AuthenticatorType }; + } else { + params = { + type: paramsOrFirst as AuthenticatorType + }; + } + + const type = params.type; + + if (typeof type === 'undefined') { + throw new AppwriteException('Missing required parameter: "type"'); + } + + const apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type); + const payload: Payload = {}; + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('post', uri, { + 'content-type': 'application/json', + }, payload); + } + + /** + * Verify an authenticator app after adding it using the [add authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) method. + * + * @param {AuthenticatorType} params.type - Type of authenticator. + * @param {string} params.otp - Valid verification token. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `Account.updateMFAAuthenticator` instead. + */ + updateMfaAuthenticator(params: { type: AuthenticatorType, otp: string }): Promise>; + /** + * Verify an authenticator app after adding it using the [add authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) method. + * + * @param {AuthenticatorType} type - Type of authenticator. + * @param {string} otp - Valid verification token. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateMfaAuthenticator(type: AuthenticatorType, otp: string): Promise>; + updateMfaAuthenticator( + paramsOrFirst: { type: AuthenticatorType, otp: string } | AuthenticatorType, + ...rest: [(string)?] + ): Promise> { + let params: { type: AuthenticatorType, otp: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'type' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { type: AuthenticatorType, otp: string }; + } else { + params = { + type: paramsOrFirst as AuthenticatorType, + otp: rest[0] as string + }; + } + + const type = params.type; + const otp = params.otp; + + if (typeof type === 'undefined') { + throw new AppwriteException('Missing required parameter: "type"'); + } + + if (typeof otp === 'undefined') { + throw new AppwriteException('Missing required parameter: "otp"'); + } + + const apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type); + const payload: Payload = {}; + + if (typeof otp !== 'undefined') { + payload['otp'] = otp; + } + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('put', uri, { + 'content-type': 'application/json', + }, payload); + } + + /** + * Verify an authenticator app after adding it using the [add authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) method. + * + * @param {AuthenticatorType} params.type - Type of authenticator. + * @param {string} params.otp - Valid verification token. + * @throws {AppwriteException} + * @returns {Promise} + */ + updateMFAAuthenticator(params: { type: AuthenticatorType, otp: string }): Promise>; + /** + * Verify an authenticator app after adding it using the [add authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) method. + * + * @param {AuthenticatorType} type - Type of authenticator. + * @param {string} otp - Valid verification token. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateMFAAuthenticator(type: AuthenticatorType, otp: string): Promise>; + updateMFAAuthenticator( + paramsOrFirst: { type: AuthenticatorType, otp: string } | AuthenticatorType, + ...rest: [(string)?] + ): Promise> { + let params: { type: AuthenticatorType, otp: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'type' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { type: AuthenticatorType, otp: string }; + } else { + params = { + type: paramsOrFirst as AuthenticatorType, + otp: rest[0] as string + }; + } + + const type = params.type; + const otp = params.otp; + if (typeof type === 'undefined') { throw new AppwriteException('Missing required parameter: "type"'); } @@ -292,11 +588,81 @@ export class Account extends Service { /** * Delete an authenticator for a user by ID. * - * @param {AuthenticatorType} type + * @param {AuthenticatorType} params.type - Type of authenticator. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `Account.deleteMFAAuthenticator` instead. + */ + deleteMfaAuthenticator(params: { type: AuthenticatorType }): Promise<{}>; + /** + * Delete an authenticator for a user by ID. + * + * @param {AuthenticatorType} type - Type of authenticator. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + deleteMfaAuthenticator(type: AuthenticatorType): Promise<{}>; + deleteMfaAuthenticator( + paramsOrFirst: { type: AuthenticatorType } | AuthenticatorType + ): Promise<{}> { + let params: { type: AuthenticatorType }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'type' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { type: AuthenticatorType }; + } else { + params = { + type: paramsOrFirst as AuthenticatorType + }; + } + + const type = params.type; + + if (typeof type === 'undefined') { + throw new AppwriteException('Missing required parameter: "type"'); + } + + const apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type); + const payload: Payload = {}; + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('delete', uri, { + 'content-type': 'application/json', + }, payload); + } + + /** + * Delete an authenticator for a user by ID. + * + * @param {AuthenticatorType} params.type - Type of authenticator. * @throws {AppwriteException} * @returns {Promise} */ - deleteMfaAuthenticator(type: AuthenticatorType): Promise<{}> { + deleteMFAAuthenticator(params: { type: AuthenticatorType }): Promise<{}>; + /** + * Delete an authenticator for a user by ID. + * + * @param {AuthenticatorType} type - Type of authenticator. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + deleteMFAAuthenticator(type: AuthenticatorType): Promise<{}>; + deleteMFAAuthenticator( + paramsOrFirst: { type: AuthenticatorType } | AuthenticatorType + ): Promise<{}> { + let params: { type: AuthenticatorType }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'type' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { type: AuthenticatorType }; + } else { + params = { + type: paramsOrFirst as AuthenticatorType + }; + } + + const type = params.type; + if (typeof type === 'undefined') { throw new AppwriteException('Missing required parameter: "type"'); } @@ -311,15 +677,38 @@ export class Account extends Service { } /** - * Begin the process of MFA verification after sign-in. Finish the flow with - * [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - * method. + * Begin the process of MFA verification after sign-in. Finish the flow with [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) method. * - * @param {AuthenticationFactor} factor + * @param {AuthenticationFactor} params.factor - Factor used for verification. Must be one of following: `email`, `phone`, `totp`, `recoveryCode`. * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `Account.createMFAChallenge` instead. + */ + createMfaChallenge(params: { factor: AuthenticationFactor }): Promise; + /** + * Begin the process of MFA verification after sign-in. Finish the flow with [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) method. + * + * @param {AuthenticationFactor} factor - Factor used for verification. Must be one of following: `email`, `phone`, `totp`, `recoveryCode`. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. */ - createMfaChallenge(factor: AuthenticationFactor): Promise { + createMfaChallenge(factor: AuthenticationFactor): Promise; + createMfaChallenge( + paramsOrFirst: { factor: AuthenticationFactor } | AuthenticationFactor + ): Promise { + let params: { factor: AuthenticationFactor }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'factor' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { factor: AuthenticationFactor }; + } else { + params = { + factor: paramsOrFirst as AuthenticationFactor + }; + } + + const factor = params.factor; + if (typeof factor === 'undefined') { throw new AppwriteException('Missing required parameter: "factor"'); } @@ -338,18 +727,154 @@ export class Account extends Service { } /** - * Complete the MFA challenge by providing the one-time password. Finish the - * process of MFA verification by providing the one-time password. To begin - * the flow, use - * [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - * method. + * Begin the process of MFA verification after sign-in. Finish the flow with [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) method. * - * @param {string} challengeId - * @param {string} otp + * @param {AuthenticationFactor} params.factor - Factor used for verification. Must be one of following: `email`, `phone`, `totp`, `recoveryCode`. * @throws {AppwriteException} * @returns {Promise} */ - updateMfaChallenge(challengeId: string, otp: string): Promise { + createMFAChallenge(params: { factor: AuthenticationFactor }): Promise; + /** + * Begin the process of MFA verification after sign-in. Finish the flow with [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) method. + * + * @param {AuthenticationFactor} factor - Factor used for verification. Must be one of following: `email`, `phone`, `totp`, `recoveryCode`. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createMFAChallenge(factor: AuthenticationFactor): Promise; + createMFAChallenge( + paramsOrFirst: { factor: AuthenticationFactor } | AuthenticationFactor + ): Promise { + let params: { factor: AuthenticationFactor }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'factor' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { factor: AuthenticationFactor }; + } else { + params = { + factor: paramsOrFirst as AuthenticationFactor + }; + } + + const factor = params.factor; + + if (typeof factor === 'undefined') { + throw new AppwriteException('Missing required parameter: "factor"'); + } + + const apiPath = '/account/mfa/challenge'; + const payload: Payload = {}; + + if (typeof factor !== 'undefined') { + payload['factor'] = factor; + } + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('post', uri, { + 'content-type': 'application/json', + }, payload); + } + + /** + * Complete the MFA challenge by providing the one-time password. Finish the process of MFA verification by providing the one-time password. To begin the flow, use [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) method. + * + * @param {string} params.challengeId - ID of the challenge. + * @param {string} params.otp - Valid verification token. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `Account.updateMFAChallenge` instead. + */ + updateMfaChallenge(params: { challengeId: string, otp: string }): Promise; + /** + * Complete the MFA challenge by providing the one-time password. Finish the process of MFA verification by providing the one-time password. To begin the flow, use [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) method. + * + * @param {string} challengeId - ID of the challenge. + * @param {string} otp - Valid verification token. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateMfaChallenge(challengeId: string, otp: string): Promise; + updateMfaChallenge( + paramsOrFirst: { challengeId: string, otp: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { challengeId: string, otp: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { challengeId: string, otp: string }; + } else { + params = { + challengeId: paramsOrFirst as string, + otp: rest[0] as string + }; + } + + const challengeId = params.challengeId; + const otp = params.otp; + + if (typeof challengeId === 'undefined') { + throw new AppwriteException('Missing required parameter: "challengeId"'); + } + + if (typeof otp === 'undefined') { + throw new AppwriteException('Missing required parameter: "otp"'); + } + + const apiPath = '/account/mfa/challenge'; + const payload: Payload = {}; + + if (typeof challengeId !== 'undefined') { + payload['challengeId'] = challengeId; + } + + if (typeof otp !== 'undefined') { + payload['otp'] = otp; + } + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('put', uri, { + 'content-type': 'application/json', + }, payload); + } + + /** + * Complete the MFA challenge by providing the one-time password. Finish the process of MFA verification by providing the one-time password. To begin the flow, use [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) method. + * + * @param {string} params.challengeId - ID of the challenge. + * @param {string} params.otp - Valid verification token. + * @throws {AppwriteException} + * @returns {Promise} + */ + updateMFAChallenge(params: { challengeId: string, otp: string }): Promise; + /** + * Complete the MFA challenge by providing the one-time password. Finish the process of MFA verification by providing the one-time password. To begin the flow, use [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) method. + * + * @param {string} challengeId - ID of the challenge. + * @param {string} otp - Valid verification token. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateMFAChallenge(challengeId: string, otp: string): Promise; + updateMFAChallenge( + paramsOrFirst: { challengeId: string, otp: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { challengeId: string, otp: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { challengeId: string, otp: string }; + } else { + params = { + challengeId: paramsOrFirst as string, + otp: rest[0] as string + }; + } + + const challengeId = params.challengeId; + const otp = params.otp; + if (typeof challengeId === 'undefined') { throw new AppwriteException('Missing required parameter: "challengeId"'); } @@ -380,6 +905,7 @@ export class Account extends Service { * * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `Account.listMFAFactors` instead. */ listMfaFactors(): Promise { const apiPath = '/account/mfa/factors'; @@ -391,13 +917,26 @@ export class Account extends Service { } /** - * Get recovery codes that can be used as backup for MFA flow. Before getting - * codes, they must be generated using - * [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - * method. An OTP challenge is required to read recovery codes. + * List the factors available on the account to be used as a MFA challange. + * + * @throws {AppwriteException} + * @returns {Promise} + */ + listMFAFactors(): Promise { + const apiPath = '/account/mfa/factors'; + const payload: Payload = {}; + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('get', uri, { + }, payload); + } + + /** + * Get recovery codes that can be used as backup for MFA flow. Before getting codes, they must be generated using [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) method. An OTP challenge is required to read recovery codes. * * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `Account.getMFARecoveryCodes` instead. */ getMfaRecoveryCodes(): Promise { const apiPath = '/account/mfa/recovery-codes'; @@ -409,15 +948,27 @@ export class Account extends Service { } /** - * Generate recovery codes as backup for MFA flow. It's recommended to - * generate and show then immediately after user successfully adds their - * authehticator. Recovery codes can be used as a MFA verification type in - * [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - * method. + * Get recovery codes that can be used as backup for MFA flow. Before getting codes, they must be generated using [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) method. An OTP challenge is required to read recovery codes. * * @throws {AppwriteException} * @returns {Promise} */ + getMFARecoveryCodes(): Promise { + const apiPath = '/account/mfa/recovery-codes'; + const payload: Payload = {}; + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('get', uri, { + }, payload); + } + + /** + * Generate recovery codes as backup for MFA flow. It's recommended to generate and show then immediately after user successfully adds their authehticator. Recovery codes can be used as a MFA verification type in [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) method. + * + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `Account.createMFARecoveryCodes` instead. + */ createMfaRecoveryCodes(): Promise { const apiPath = '/account/mfa/recovery-codes'; const payload: Payload = {}; @@ -429,13 +980,27 @@ export class Account extends Service { } /** - * Regenerate recovery codes that can be used as backup for MFA flow. Before - * regenerating codes, they must be first generated using - * [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) - * method. An OTP challenge is required to regenreate recovery codes. + * Generate recovery codes as backup for MFA flow. It's recommended to generate and show then immediately after user successfully adds their authehticator. Recovery codes can be used as a MFA verification type in [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) method. + * + * @throws {AppwriteException} + * @returns {Promise} + */ + createMFARecoveryCodes(): Promise { + const apiPath = '/account/mfa/recovery-codes'; + const payload: Payload = {}; + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('post', uri, { + 'content-type': 'application/json', + }, payload); + } + + /** + * Regenerate recovery codes that can be used as backup for MFA flow. Before regenerating codes, they must be first generated using [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) method. An OTP challenge is required to regenreate recovery codes. * * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `Account.updateMFARecoveryCodes` instead. */ updateMfaRecoveryCodes(): Promise { const apiPath = '/account/mfa/recovery-codes'; @@ -447,14 +1012,54 @@ export class Account extends Service { }, payload); } + /** + * Regenerate recovery codes that can be used as backup for MFA flow. Before regenerating codes, they must be first generated using [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes) method. An OTP challenge is required to regenreate recovery codes. + * + * @throws {AppwriteException} + * @returns {Promise} + */ + updateMFARecoveryCodes(): Promise { + const apiPath = '/account/mfa/recovery-codes'; + const payload: Payload = {}; + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('patch', uri, { + 'content-type': 'application/json', + }, payload); + } + /** * Update currently logged in user account name. * - * @param {string} name + * @param {string} params.name - User name. Max length: 128 chars. * @throws {AppwriteException} * @returns {Promise} */ - updateName(name: string): Promise> { + updateName(params: { name: string }): Promise>; + /** + * Update currently logged in user account name. + * + * @param {string} name - User name. Max length: 128 chars. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateName(name: string): Promise>; + updateName( + paramsOrFirst: { name: string } | string + ): Promise> { + let params: { name: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { name: string }; + } else { + params = { + name: paramsOrFirst as string + }; + } + + const name = params.name; + if (typeof name === 'undefined') { throw new AppwriteException('Missing required parameter: "name"'); } @@ -473,16 +1078,42 @@ export class Account extends Service { } /** - * 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. + * 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. * - * @param {string} password - * @param {string} oldPassword + * @param {string} params.password - New user password. Must be at least 8 chars. + * @param {string} params.oldPassword - Current user password. Must be at least 8 chars. * @throws {AppwriteException} * @returns {Promise} */ - updatePassword(password: string, oldPassword?: string): Promise> { + updatePassword(params: { password: string, oldPassword?: string }): Promise>; + /** + * 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. + * + * @param {string} password - New user password. Must be at least 8 chars. + * @param {string} oldPassword - Current user password. Must be at least 8 chars. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updatePassword(password: string, oldPassword?: string): Promise>; + updatePassword( + paramsOrFirst: { password: string, oldPassword?: string } | string, + ...rest: [(string)?] + ): Promise> { + let params: { password: string, oldPassword?: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { password: string, oldPassword?: string }; + } else { + params = { + password: paramsOrFirst as string, + oldPassword: rest[0] as string + }; + } + + const password = params.password; + const oldPassword = params.oldPassword; + if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } @@ -505,18 +1136,42 @@ export class Account extends Service { } /** - * Update the currently logged in user's phone number. After updating the - * phone number, the phone verification status will be reset. A confirmation - * SMS is not sent automatically, however you can use the [POST - * /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) - * endpoint to send a confirmation SMS. + * Update the currently logged in user's phone number. After updating the phone number, the phone verification status will be reset. A confirmation SMS is not sent automatically, however you can use the [POST /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) endpoint to send a confirmation SMS. * - * @param {string} phone - * @param {string} password + * @param {string} params.phone - Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. + * @param {string} params.password - User password. Must be at least 8 chars. * @throws {AppwriteException} * @returns {Promise} */ - updatePhone(phone: string, password: string): Promise> { + updatePhone(params: { phone: string, password: string }): Promise>; + /** + * Update the currently logged in user's phone number. After updating the phone number, the phone verification status will be reset. A confirmation SMS is not sent automatically, however you can use the [POST /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification) endpoint to send a confirmation SMS. + * + * @param {string} phone - Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. + * @param {string} password - User password. Must be at least 8 chars. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updatePhone(phone: string, password: string): Promise>; + updatePhone( + paramsOrFirst: { phone: string, password: string } | string, + ...rest: [(string)?] + ): Promise> { + let params: { phone: string, password: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { phone: string, password: string }; + } else { + params = { + phone: paramsOrFirst as string, + password: rest[0] as string + }; + } + + const phone = params.phone; + const password = params.password; + if (typeof phone === 'undefined') { throw new AppwriteException('Missing required parameter: "phone"'); } @@ -558,15 +1213,37 @@ export class Account extends Service { } /** - * Update currently logged in user account preferences. The object you pass is - * stored as is, and replaces any previous value. The maximum allowed prefs - * size is 64kB and throws error if exceeded. + * Update currently logged in user account preferences. The object you pass is stored as is, and replaces any previous value. The maximum allowed prefs size is 64kB and throws error if exceeded. * - * @param {object} prefs + * @param {Partial} params.prefs - Prefs key-value JSON object. * @throws {AppwriteException} * @returns {Promise} */ - updatePrefs(prefs: object): Promise> { + updatePrefs(params: { prefs: Partial }): Promise>; + /** + * Update currently logged in user account preferences. The object you pass is stored as is, and replaces any previous value. The maximum allowed prefs size is 64kB and throws error if exceeded. + * + * @param {Partial} prefs - Prefs key-value JSON object. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updatePrefs(prefs: Partial): Promise>; + updatePrefs( + paramsOrFirst: { prefs: Partial } | Partial + ): Promise> { + let params: { prefs: Partial }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'prefs' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { prefs: Partial }; + } else { + params = { + prefs: paramsOrFirst as Partial + }; + } + + const prefs = params.prefs; + if (typeof prefs === 'undefined') { throw new AppwriteException('Missing required parameter: "prefs"'); } @@ -585,21 +1262,42 @@ export class Account extends Service { } /** - * Sends the user an email with a temporary secret key for password reset. - * When the user clicks the confirmation link he is redirected back to your - * app password reset URL with the secret key and email address values - * attached to the URL query string. Use the query string params to submit a - * request to the [PUT - * /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - * endpoint to complete the process. The verification link sent to the user's - * email address is valid for 1 hour. + * Sends the user an email with a temporary secret key for password reset. When the user clicks the confirmation link he is redirected back to your app password reset URL with the secret key and email address values attached to the URL query string. Use the query string params to submit a request to the [PUT /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) endpoint to complete the process. The verification link sent to the user's email address is valid for 1 hour. * - * @param {string} email - * @param {string} url + * @param {string} params.email - User email. + * @param {string} params.url - URL to redirect the user back to your app from the recovery email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. * @throws {AppwriteException} * @returns {Promise} */ - createRecovery(email: string, url: string): Promise { + createRecovery(params: { email: string, url: string }): Promise; + /** + * Sends the user an email with a temporary secret key for password reset. When the user clicks the confirmation link he is redirected back to your app password reset URL with the secret key and email address values attached to the URL query string. Use the query string params to submit a request to the [PUT /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) endpoint to complete the process. The verification link sent to the user's email address is valid for 1 hour. + * + * @param {string} email - User email. + * @param {string} url - URL to redirect the user back to your app from the recovery email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createRecovery(email: string, url: string): Promise; + createRecovery( + paramsOrFirst: { email: string, url: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { email: string, url: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { email: string, url: string }; + } else { + params = { + email: paramsOrFirst as string, + url: rest[0] as string + }; + } + + const email = params.email; + const url = params.url; + if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } @@ -626,24 +1324,50 @@ export class Account extends Service { } /** - * Use this endpoint to complete the user account password reset. Both the - * **userId** and **secret** arguments will be passed as query parameters to - * the redirect URL you have provided when sending your request to the [POST - * /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) - * endpoint. + * Use this endpoint to complete the user account password reset. Both the **userId** and **secret** arguments will be passed as query parameters to the redirect URL you have provided when sending your request to the [POST /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) endpoint. * - * Please note that in order to avoid a [Redirect - * Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - * the only valid redirect URLs are the ones from domains you have set when - * adding your platforms in the console interface. + * Please note that in order to avoid a [Redirect Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) the only valid redirect URLs are the ones from domains you have set when adding your platforms in the console interface. * - * @param {string} userId - * @param {string} secret - * @param {string} password + * @param {string} params.userId - User ID. + * @param {string} params.secret - Valid reset token. + * @param {string} params.password - New user password. Must be between 8 and 256 chars. * @throws {AppwriteException} * @returns {Promise} */ - updateRecovery(userId: string, secret: string, password: string): Promise { + updateRecovery(params: { userId: string, secret: string, password: string }): Promise; + /** + * Use this endpoint to complete the user account password reset. Both the **userId** and **secret** arguments will be passed as query parameters to the redirect URL you have provided when sending your request to the [POST /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery) endpoint. + * + * Please note that in order to avoid a [Redirect Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) the only valid redirect URLs are the ones from domains you have set when adding your platforms in the console interface. + * + * @param {string} userId - User ID. + * @param {string} secret - Valid reset token. + * @param {string} password - New user password. Must be between 8 and 256 chars. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateRecovery(userId: string, secret: string, password: string): Promise; + updateRecovery( + paramsOrFirst: { userId: string, secret: string, password: string } | string, + ...rest: [(string)?, (string)?] + ): Promise { + let params: { userId: string, secret: string, password: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { userId: string, secret: string, password: string }; + } else { + params = { + userId: paramsOrFirst as string, + secret: rest[0] as string, + password: rest[1] as string + }; + } + + const userId = params.userId; + const secret = params.secret; + const password = params.password; + if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } @@ -678,8 +1402,7 @@ export class Account extends Service { } /** - * Get the list of active sessions across different devices for the currently - * logged in user. + * Get the list of active sessions across different devices for the currently logged in user. * * @throws {AppwriteException} * @returns {Promise} @@ -694,8 +1417,7 @@ export class Account extends Service { } /** - * Delete all sessions from the user account and remove any sessions cookies - * from the end client. + * Delete all sessions from the user account and remove any sessions cookies from the end client. * * @throws {AppwriteException} * @returns {Promise} @@ -711,13 +1433,7 @@ export class Account extends Service { } /** - * Use this endpoint to allow a new user to register an anonymous account in - * your project. This route will also create a new session for the user. To - * allow the new user to convert an anonymous account to a normal account, you - * need to update its [email and - * password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - * or create an [OAuth2 - * session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + * Use this endpoint to allow a new user to register an anonymous account in your project. This route will also create a new session for the user. To allow the new user to convert an anonymous account to a normal account, you need to update its [email and password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) or create an [OAuth2 session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). * * @throws {AppwriteException} * @returns {Promise} @@ -733,19 +1449,46 @@ export class Account extends Service { } /** - * Allow the user to login into their account by providing a valid email and - * password combination. This route will create a new session for the user. + * Allow the user to login into their account by providing a valid email and password combination. This route will create a new session for the user. * - * A user is limited to 10 active sessions at a time by default. [Learn more - * about session - * limits](https://appwrite.io/docs/authentication-security#limits). + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). * - * @param {string} email - * @param {string} password + * @param {string} params.email - User email. + * @param {string} params.password - User password. Must be at least 8 chars. * @throws {AppwriteException} * @returns {Promise} */ - createEmailPasswordSession(email: string, password: string): Promise { + createEmailPasswordSession(params: { email: string, password: string }): Promise; + /** + * Allow the user to login into their account by providing a valid email and password combination. This route will create a new session for the user. + * + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). + * + * @param {string} email - User email. + * @param {string} password - User password. Must be at least 8 chars. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createEmailPasswordSession(email: string, password: string): Promise; + createEmailPasswordSession( + paramsOrFirst: { email: string, password: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { email: string, password: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { email: string, password: string }; + } else { + params = { + email: paramsOrFirst as string, + password: rest[0] as string + }; + } + + const email = params.email; + const password = params.password; + if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } @@ -772,16 +1515,43 @@ export class Account extends Service { } /** - * Use this endpoint to create a session from token. Provide the **userId** - * and **secret** parameters from the successful response of authentication - * flows initiated by token creation. For example, magic URL and phone login. + * Use this endpoint to create a session from token. Provide the **userId** and **secret** parameters from the successful response of authentication flows initiated by token creation. For example, magic URL and phone login. * - * @param {string} userId - * @param {string} secret + * @param {string} params.userId - User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {string} params.secret - Valid verification token. * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated. + */ + updateMagicURLSession(params: { userId: string, secret: string }): Promise; + /** + * Use this endpoint to create a session from token. Provide the **userId** and **secret** parameters from the successful response of authentication flows initiated by token creation. For example, magic URL and phone login. + * + * @param {string} userId - User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {string} secret - Valid verification token. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. */ - updateMagicURLSession(userId: string, secret: string): Promise { + updateMagicURLSession(userId: string, secret: string): Promise; + updateMagicURLSession( + paramsOrFirst: { userId: string, secret: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { userId: string, secret: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { userId: string, secret: string }; + } else { + params = { + userId: paramsOrFirst as string, + secret: rest[0] as string + }; + } + + const userId = params.userId; + const secret = params.secret; + if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } @@ -808,31 +1578,60 @@ export class Account extends Service { } /** - * Allow the user to login to their account using the OAuth2 provider of their - * choice. Each OAuth2 provider should be enabled from the Appwrite console - * first. Use the success and failure arguments to provide a redirect URL's - * back to your app when login is completed. + * Allow the user to login to their account using the OAuth2 provider of their choice. Each OAuth2 provider should be enabled from the Appwrite console first. Use the success and failure arguments to provide a redirect URL's back to your app when login is completed. * - * If there is already an active session, the new session will be attached to - * the logged-in account. If there are no active sessions, the server will - * attempt to look for a user with the same email address as the email - * received from the OAuth2 provider and attach the new session to the - * existing user. If no matching user is found - the server will create a new - * user. + * If there is already an active session, the new session will be attached to the logged-in account. If there are no active sessions, the server will attempt to look for a user with the same email address as the email received from the OAuth2 provider and attach the new session to the existing user. If no matching user is found - the server will create a new user. * - * A user is limited to 10 active sessions at a time by default. [Learn more - * about session - * limits](https://appwrite.io/docs/authentication-security#limits). + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). * * - * @param {OAuthProvider} provider - * @param {string} success - * @param {string} failure - * @param {string[]} scopes + * @param {OAuthProvider} params.provider - OAuth2 Provider. Currently, supported providers are: amazon, apple, auth0, authentik, autodesk, bitbucket, bitly, box, dailymotion, discord, disqus, dropbox, etsy, facebook, figma, github, gitlab, google, linkedin, microsoft, notion, oidc, okta, paypal, paypalSandbox, podio, salesforce, slack, spotify, stripe, tradeshift, tradeshiftBox, twitch, wordpress, yahoo, yammer, yandex, zoho, zoom. + * @param {string} params.success - URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param {string} params.failure - URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param {string[]} params.scopes - A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of 100 scopes are allowed, each 4096 characters long. * @throws {AppwriteException} * @returns {void|string} */ - createOAuth2Session(provider: OAuthProvider, success?: string, failure?: string, scopes?: string[]): void | URL { + createOAuth2Session(params: { provider: OAuthProvider, success?: string, failure?: string, scopes?: string[] }): void | URL; + /** + * Allow the user to login to their account using the OAuth2 provider of their choice. Each OAuth2 provider should be enabled from the Appwrite console first. Use the success and failure arguments to provide a redirect URL's back to your app when login is completed. + * + * If there is already an active session, the new session will be attached to the logged-in account. If there are no active sessions, the server will attempt to look for a user with the same email address as the email received from the OAuth2 provider and attach the new session to the existing user. If no matching user is found - the server will create a new user. + * + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). + * + * + * @param {OAuthProvider} provider - OAuth2 Provider. Currently, supported providers are: amazon, apple, auth0, authentik, autodesk, bitbucket, bitly, box, dailymotion, discord, disqus, dropbox, etsy, facebook, figma, github, gitlab, google, linkedin, microsoft, notion, oidc, okta, paypal, paypalSandbox, podio, salesforce, slack, spotify, stripe, tradeshift, tradeshiftBox, twitch, wordpress, yahoo, yammer, yandex, zoho, zoom. + * @param {string} success - URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param {string} failure - URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param {string[]} scopes - A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of 100 scopes are allowed, each 4096 characters long. + * @throws {AppwriteException} + * @returns {void | URL} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createOAuth2Session(provider: OAuthProvider, success?: string, failure?: string, scopes?: string[]): void | URL; + createOAuth2Session( + paramsOrFirst: { provider: OAuthProvider, success?: string, failure?: string, scopes?: string[] } | OAuthProvider, + ...rest: [(string)?, (string)?, (string[])?] + ): void | URL { + let params: { provider: OAuthProvider, success?: string, failure?: string, scopes?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'provider' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { provider: OAuthProvider, success?: string, failure?: string, scopes?: string[] }; + } else { + params = { + provider: paramsOrFirst as OAuthProvider, + success: rest[0] as string, + failure: rest[1] as string, + scopes: rest[2] as string[] + }; + } + + const provider = params.provider; + const success = params.success; + const failure = params.failure; + const scopes = params.scopes; + if (typeof provider === 'undefined') { throw new AppwriteException('Missing required parameter: "provider"'); } @@ -863,16 +1662,43 @@ export class Account extends Service { } /** - * Use this endpoint to create a session from token. Provide the **userId** - * and **secret** parameters from the successful response of authentication - * flows initiated by token creation. For example, magic URL and phone login. + * Use this endpoint to create a session from token. Provide the **userId** and **secret** parameters from the successful response of authentication flows initiated by token creation. For example, magic URL and phone login. * - * @param {string} userId - * @param {string} secret + * @param {string} params.userId - User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {string} params.secret - Valid verification token. * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated. + */ + updatePhoneSession(params: { userId: string, secret: string }): Promise; + /** + * Use this endpoint to create a session from token. Provide the **userId** and **secret** parameters from the successful response of authentication flows initiated by token creation. For example, magic URL and phone login. + * + * @param {string} userId - User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {string} secret - Valid verification token. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. */ - updatePhoneSession(userId: string, secret: string): Promise { + updatePhoneSession(userId: string, secret: string): Promise; + updatePhoneSession( + paramsOrFirst: { userId: string, secret: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { userId: string, secret: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { userId: string, secret: string }; + } else { + params = { + userId: paramsOrFirst as string, + secret: rest[0] as string + }; + } + + const userId = params.userId; + const secret = params.secret; + if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } @@ -899,16 +1725,42 @@ export class Account extends Service { } /** - * Use this endpoint to create a session from token. Provide the **userId** - * and **secret** parameters from the successful response of authentication - * flows initiated by token creation. For example, magic URL and phone login. + * Use this endpoint to create a session from token. Provide the **userId** and **secret** parameters from the successful response of authentication flows initiated by token creation. For example, magic URL and phone login. * - * @param {string} userId - * @param {string} secret + * @param {string} params.userId - User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {string} params.secret - Secret of a token generated by login methods. For example, the `createMagicURLToken` or `createPhoneToken` methods. * @throws {AppwriteException} * @returns {Promise} */ - createSession(userId: string, secret: string): Promise { + createSession(params: { userId: string, secret: string }): Promise; + /** + * Use this endpoint to create a session from token. Provide the **userId** and **secret** parameters from the successful response of authentication flows initiated by token creation. For example, magic URL and phone login. + * + * @param {string} userId - User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {string} secret - Secret of a token generated by login methods. For example, the `createMagicURLToken` or `createPhoneToken` methods. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createSession(userId: string, secret: string): Promise; + createSession( + paramsOrFirst: { userId: string, secret: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { userId: string, secret: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { userId: string, secret: string }; + } else { + params = { + userId: paramsOrFirst as string, + secret: rest[0] as string + }; + } + + const userId = params.userId; + const secret = params.secret; + if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } @@ -935,14 +1787,37 @@ export class Account extends Service { } /** - * Use this endpoint to get a logged in user's session using a Session ID. - * Inputting 'current' will return the current session being used. + * Use this endpoint to get a logged in user's session using a Session ID. Inputting 'current' will return the current session being used. * - * @param {string} sessionId + * @param {string} params.sessionId - Session ID. Use the string 'current' to get the current device session. * @throws {AppwriteException} * @returns {Promise} */ - getSession(sessionId: string): Promise { + getSession(params: { sessionId: string }): Promise; + /** + * Use this endpoint to get a logged in user's session using a Session ID. Inputting 'current' will return the current session being used. + * + * @param {string} sessionId - Session ID. Use the string 'current' to get the current device session. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getSession(sessionId: string): Promise; + getSession( + paramsOrFirst: { sessionId: string } | string + ): Promise { + let params: { sessionId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { sessionId: string }; + } else { + params = { + sessionId: paramsOrFirst as string + }; + } + + const sessionId = params.sessionId; + if (typeof sessionId === 'undefined') { throw new AppwriteException('Missing required parameter: "sessionId"'); } @@ -956,15 +1831,37 @@ export class Account extends Service { } /** - * Use this endpoint to extend a session's length. Extending a session is - * useful when session expiry is short. If the session was created using an - * OAuth provider, this endpoint refreshes the access token from the provider. + * Use this endpoint to extend a session's length. Extending a session is useful when session expiry is short. If the session was created using an OAuth provider, this endpoint refreshes the access token from the provider. * - * @param {string} sessionId + * @param {string} params.sessionId - Session ID. Use the string 'current' to update the current device session. * @throws {AppwriteException} * @returns {Promise} */ - updateSession(sessionId: string): Promise { + updateSession(params: { sessionId: string }): Promise; + /** + * Use this endpoint to extend a session's length. Extending a session is useful when session expiry is short. If the session was created using an OAuth provider, this endpoint refreshes the access token from the provider. + * + * @param {string} sessionId - Session ID. Use the string 'current' to update the current device session. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateSession(sessionId: string): Promise; + updateSession( + paramsOrFirst: { sessionId: string } | string + ): Promise { + let params: { sessionId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { sessionId: string }; + } else { + params = { + sessionId: paramsOrFirst as string + }; + } + + const sessionId = params.sessionId; + if (typeof sessionId === 'undefined') { throw new AppwriteException('Missing required parameter: "sessionId"'); } @@ -979,17 +1876,37 @@ export class Account extends Service { } /** - * Logout the user. Use 'current' as the session ID to logout on this device, - * use a session ID to logout on another device. If you're looking to logout - * the user on all devices, use [Delete - * Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - * instead. + * Logout the user. Use 'current' as the session ID to logout on this device, use a session ID to logout on another device. If you're looking to logout the user on all devices, use [Delete Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) instead. * - * @param {string} sessionId + * @param {string} params.sessionId - Session ID. Use the string 'current' to delete the current device session. * @throws {AppwriteException} * @returns {Promise} */ - deleteSession(sessionId: string): Promise<{}> { + deleteSession(params: { sessionId: string }): Promise<{}>; + /** + * Logout the user. Use 'current' as the session ID to logout on this device, use a session ID to logout on another device. If you're looking to logout the user on all devices, use [Delete Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) instead. + * + * @param {string} sessionId - Session ID. Use the string 'current' to delete the current device session. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + deleteSession(sessionId: string): Promise<{}>; + deleteSession( + paramsOrFirst: { sessionId: string } | string + ): Promise<{}> { + let params: { sessionId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { sessionId: string }; + } else { + params = { + sessionId: paramsOrFirst as string + }; + } + + const sessionId = params.sessionId; + if (typeof sessionId === 'undefined') { throw new AppwriteException('Missing required parameter: "sessionId"'); } @@ -1004,9 +1921,7 @@ export class Account extends Service { } /** - * Block the currently logged in user account. Behind the scene, the user - * record is not deleted but permanently blocked from any access. To - * completely delete a user, use the Users API instead. + * Block the currently logged in user account. Behind the scene, the user record is not deleted but permanently blocked from any access. To completely delete a user, use the Users API instead. * * @throws {AppwriteException} * @returns {Promise} @@ -1022,19 +1937,46 @@ export class Account extends Service { } /** - * Use this endpoint to register a device for push notifications. Provide a - * target ID (custom or generated using ID.unique()), a device identifier - * (usually a device token), and optionally specify which provider should send - * notifications to this target. The target is automatically linked to the - * current session and includes device information like brand and model. + * Use this endpoint to register a device for push notifications. Provide a target ID (custom or generated using ID.unique()), a device identifier (usually a device token), and optionally specify which provider should send notifications to this target. The target is automatically linked to the current session and includes device information like brand and model. * - * @param {string} targetId - * @param {string} identifier - * @param {string} providerId + * @param {string} params.targetId - Target ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {string} params.identifier - The target identifier (token, email, phone etc.) + * @param {string} params.providerId - Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used. * @throws {AppwriteException} * @returns {Promise} */ - createPushTarget(targetId: string, identifier: string, providerId?: string): Promise { + createPushTarget(params: { targetId: string, identifier: string, providerId?: string }): Promise; + /** + * Use this endpoint to register a device for push notifications. Provide a target ID (custom or generated using ID.unique()), a device identifier (usually a device token), and optionally specify which provider should send notifications to this target. The target is automatically linked to the current session and includes device information like brand and model. + * + * @param {string} targetId - Target ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {string} identifier - The target identifier (token, email, phone etc.) + * @param {string} providerId - Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createPushTarget(targetId: string, identifier: string, providerId?: string): Promise; + createPushTarget( + paramsOrFirst: { targetId: string, identifier: string, providerId?: string } | string, + ...rest: [(string)?, (string)?] + ): Promise { + let params: { targetId: string, identifier: string, providerId?: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { targetId: string, identifier: string, providerId?: string }; + } else { + params = { + targetId: paramsOrFirst as string, + identifier: rest[0] as string, + providerId: rest[1] as string + }; + } + + const targetId = params.targetId; + const identifier = params.identifier; + const providerId = params.providerId; + if (typeof targetId === 'undefined') { throw new AppwriteException('Missing required parameter: "targetId"'); } @@ -1065,18 +2007,42 @@ export class Account extends Service { } /** - * Update the currently logged in user's push notification target. You can - * modify the target's identifier (device token) and provider ID (token, - * email, phone etc.). The target must exist and belong to the current user. - * If you change the provider ID, notifications will be sent through the new - * messaging provider instead. + * Update the currently logged in user's push notification target. You can modify the target's identifier (device token) and provider ID (token, email, phone etc.). The target must exist and belong to the current user. If you change the provider ID, notifications will be sent through the new messaging provider instead. * - * @param {string} targetId - * @param {string} identifier + * @param {string} params.targetId - Target ID. + * @param {string} params.identifier - The target identifier (token, email, phone etc.) * @throws {AppwriteException} * @returns {Promise} */ - updatePushTarget(targetId: string, identifier: string): Promise { + updatePushTarget(params: { targetId: string, identifier: string }): Promise; + /** + * Update the currently logged in user's push notification target. You can modify the target's identifier (device token) and provider ID (token, email, phone etc.). The target must exist and belong to the current user. If you change the provider ID, notifications will be sent through the new messaging provider instead. + * + * @param {string} targetId - Target ID. + * @param {string} identifier - The target identifier (token, email, phone etc.) + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updatePushTarget(targetId: string, identifier: string): Promise; + updatePushTarget( + paramsOrFirst: { targetId: string, identifier: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { targetId: string, identifier: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { targetId: string, identifier: string }; + } else { + params = { + targetId: paramsOrFirst as string, + identifier: rest[0] as string + }; + } + + const targetId = params.targetId; + const identifier = params.identifier; + if (typeof targetId === 'undefined') { throw new AppwriteException('Missing required parameter: "targetId"'); } @@ -1099,15 +2065,37 @@ export class Account extends Service { } /** - * Delete a push notification target for the currently logged in user. After - * deletion, the device will no longer receive push notifications. The target - * must exist and belong to the current user. + * Delete a push notification target for the currently logged in user. After deletion, the device will no longer receive push notifications. The target must exist and belong to the current user. * - * @param {string} targetId + * @param {string} params.targetId - Target ID. * @throws {AppwriteException} * @returns {Promise} */ - deletePushTarget(targetId: string): Promise<{}> { + deletePushTarget(params: { targetId: string }): Promise<{}>; + /** + * Delete a push notification target for the currently logged in user. After deletion, the device will no longer receive push notifications. The target must exist and belong to the current user. + * + * @param {string} targetId - Target ID. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + deletePushTarget(targetId: string): Promise<{}>; + deletePushTarget( + paramsOrFirst: { targetId: string } | string + ): Promise<{}> { + let params: { targetId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { targetId: string }; + } else { + params = { + targetId: paramsOrFirst as string + }; + } + + const targetId = params.targetId; + if (typeof targetId === 'undefined') { throw new AppwriteException('Missing required parameter: "targetId"'); } @@ -1122,24 +2110,52 @@ export class Account extends Service { } /** - * Sends the user an email 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 - * /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - * endpoint to complete the login process. The secret sent to the user's email - * is valid for 15 minutes. + * Sends the user an email with a secret key for creating a session. If the email address has never been used, a **new account is created** using the provided `userId`. Otherwise, if the email address is already attached to an account, the **user ID is ignored**. Then, the user will receive an email with the one-time password. Use the returned user ID and secret and submit a request to the [POST /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) endpoint to complete the login process. The secret sent to the user's email is valid for 15 minutes. + * + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). * - * A user is limited to 10 active sessions at a time by default. [Learn more - * about session - * limits](https://appwrite.io/docs/authentication-security#limits). * - * @param {string} userId - * @param {string} email - * @param {boolean} phrase + * @param {string} params.userId - User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored. + * @param {string} params.email - User email. + * @param {boolean} params.phrase - Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow. * @throws {AppwriteException} * @returns {Promise} */ - createEmailToken(userId: string, email: string, phrase?: boolean): Promise { + createEmailToken(params: { userId: string, email: string, phrase?: boolean }): Promise; + /** + * Sends the user an email with a secret key for creating a session. If the email address has never been used, a **new account is created** using the provided `userId`. Otherwise, if the email address is already attached to an account, the **user ID is ignored**. Then, the user will receive an email with the one-time password. Use the returned user ID and secret and submit a request to the [POST /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) endpoint to complete the login process. The secret sent to the user's email is valid for 15 minutes. + * + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). + * + * + * @param {string} userId - User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored. + * @param {string} email - User email. + * @param {boolean} phrase - Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createEmailToken(userId: string, email: string, phrase?: boolean): Promise; + createEmailToken( + paramsOrFirst: { userId: string, email: string, phrase?: boolean } | string, + ...rest: [(string)?, (boolean)?] + ): Promise { + let params: { userId: string, email: string, phrase?: boolean }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { userId: string, email: string, phrase?: boolean }; + } else { + params = { + userId: paramsOrFirst as string, + email: rest[0] as string, + phrase: rest[1] as boolean + }; + } + + const userId = params.userId; + const email = params.email; + const phrase = params.phrase; + if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } @@ -1170,29 +2186,56 @@ export class Account extends Service { } /** - * Sends the user an email with a secret key for creating a session. If the - * provided user ID has not been registered, a new user will be created. When - * the user clicks the link in the email, the user is redirected back to the - * URL you provided with the secret key and userId values attached to the URL - * query string. Use the query string parameters to submit a request to the - * [POST - * /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - * endpoint to complete the login process. The link sent to the user's email - * address is valid for 1 hour. + * Sends the user an email with a secret key for creating a session. If the provided user ID has not been registered, a new user will be created. When the user clicks the link in the email, the user is redirected back to the URL you provided with the secret key and userId values attached to the URL query string. Use the query string parameters to submit a request to the [POST /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) endpoint to complete the login process. The link sent to the user's email address is valid for 1 hour. * - * A user is limited to 10 active sessions at a time by default. [Learn more - * about session - * limits](https://appwrite.io/docs/authentication-security#limits). + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). * * - * @param {string} userId - * @param {string} email - * @param {string} url - * @param {boolean} phrase + * @param {string} params.userId - Unique Id. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored. + * @param {string} params.email - User email. + * @param {string} params.url - URL to redirect the user back to your app from the magic URL login. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param {boolean} params.phrase - Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow. * @throws {AppwriteException} * @returns {Promise} */ - createMagicURLToken(userId: string, email: string, url?: string, phrase?: boolean): Promise { + createMagicURLToken(params: { userId: string, email: string, url?: string, phrase?: boolean }): Promise; + /** + * Sends the user an email with a secret key for creating a session. If the provided user ID has not been registered, a new user will be created. When the user clicks the link in the email, the user is redirected back to the URL you provided with the secret key and userId values attached to the URL query string. Use the query string parameters to submit a request to the [POST /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) endpoint to complete the login process. The link sent to the user's email address is valid for 1 hour. + * + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). + * + * + * @param {string} userId - Unique Id. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the email address has never been used, a new account is created using the provided userId. Otherwise, if the email address is already attached to an account, the user ID is ignored. + * @param {string} email - User email. + * @param {string} url - URL to redirect the user back to your app from the magic URL login. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param {boolean} phrase - Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createMagicURLToken(userId: string, email: string, url?: string, phrase?: boolean): Promise; + createMagicURLToken( + paramsOrFirst: { userId: string, email: string, url?: string, phrase?: boolean } | string, + ...rest: [(string)?, (string)?, (boolean)?] + ): Promise { + let params: { userId: string, email: string, url?: string, phrase?: boolean }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { userId: string, email: string, url?: string, phrase?: boolean }; + } else { + params = { + userId: paramsOrFirst as string, + email: rest[0] as string, + url: rest[1] as string, + phrase: rest[2] as boolean + }; + } + + const userId = params.userId; + const email = params.email; + const url = params.url; + const phrase = params.phrase; + if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } @@ -1227,29 +2270,58 @@ export class Account extends Service { } /** - * Allow the user to login to their account using the OAuth2 provider of their - * choice. Each OAuth2 provider should be enabled from the Appwrite console - * first. Use the success and failure arguments to provide a redirect URL's - * back to your app when login is completed. + * Allow the user to login to their account using the OAuth2 provider of their choice. Each OAuth2 provider should be enabled from the Appwrite console first. Use the success and failure arguments to provide a redirect URL's back to your app when login is completed. * - * If authentication succeeds, `userId` and `secret` of a token will be - * appended to the success URL as query parameters. These can be used to - * create a new session using the [Create - * session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - * endpoint. + * If authentication succeeds, `userId` and `secret` of a token will be appended to the success URL as query parameters. These can be used to create a new session using the [Create session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) endpoint. * - * A user is limited to 10 active sessions at a time by default. [Learn more - * about session - * limits](https://appwrite.io/docs/authentication-security#limits). + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). * - * @param {OAuthProvider} provider - * @param {string} success - * @param {string} failure - * @param {string[]} scopes + * @param {OAuthProvider} params.provider - OAuth2 Provider. Currently, supported providers are: amazon, apple, auth0, authentik, autodesk, bitbucket, bitly, box, dailymotion, discord, disqus, dropbox, etsy, facebook, figma, github, gitlab, google, linkedin, microsoft, notion, oidc, okta, paypal, paypalSandbox, podio, salesforce, slack, spotify, stripe, tradeshift, tradeshiftBox, twitch, wordpress, yahoo, yammer, yandex, zoho, zoom. + * @param {string} params.success - URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param {string} params.failure - URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param {string[]} params.scopes - A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of 100 scopes are allowed, each 4096 characters long. * @throws {AppwriteException} * @returns {void|string} */ - createOAuth2Token(provider: OAuthProvider, success?: string, failure?: string, scopes?: string[]): void | URL { + createOAuth2Token(params: { provider: OAuthProvider, success?: string, failure?: string, scopes?: string[] }): void | URL; + /** + * Allow the user to login to their account using the OAuth2 provider of their choice. Each OAuth2 provider should be enabled from the Appwrite console first. Use the success and failure arguments to provide a redirect URL's back to your app when login is completed. + * + * If authentication succeeds, `userId` and `secret` of a token will be appended to the success URL as query parameters. These can be used to create a new session using the [Create session](https://appwrite.io/docs/references/cloud/client-web/account#createSession) endpoint. + * + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). + * + * @param {OAuthProvider} provider - OAuth2 Provider. Currently, supported providers are: amazon, apple, auth0, authentik, autodesk, bitbucket, bitly, box, dailymotion, discord, disqus, dropbox, etsy, facebook, figma, github, gitlab, google, linkedin, microsoft, notion, oidc, okta, paypal, paypalSandbox, podio, salesforce, slack, spotify, stripe, tradeshift, tradeshiftBox, twitch, wordpress, yahoo, yammer, yandex, zoho, zoom. + * @param {string} success - URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param {string} failure - URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project's platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param {string[]} scopes - A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of 100 scopes are allowed, each 4096 characters long. + * @throws {AppwriteException} + * @returns {void | URL} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createOAuth2Token(provider: OAuthProvider, success?: string, failure?: string, scopes?: string[]): void | URL; + createOAuth2Token( + paramsOrFirst: { provider: OAuthProvider, success?: string, failure?: string, scopes?: string[] } | OAuthProvider, + ...rest: [(string)?, (string)?, (string[])?] + ): void | URL { + let params: { provider: OAuthProvider, success?: string, failure?: string, scopes?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'provider' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { provider: OAuthProvider, success?: string, failure?: string, scopes?: string[] }; + } else { + params = { + provider: paramsOrFirst as OAuthProvider, + success: rest[0] as string, + failure: rest[1] as string, + scopes: rest[2] as string[] + }; + } + + const provider = params.provider; + const success = params.success; + const failure = params.failure; + const scopes = params.scopes; + if (typeof provider === 'undefined') { throw new AppwriteException('Missing required parameter: "provider"'); } @@ -1280,23 +2352,46 @@ export class Account extends Service { } /** - * 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 - * /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) - * endpoint to complete the login process. The secret sent to the user's phone - * is valid for 15 minutes. + * 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 /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) endpoint to complete the login process. The secret sent to the user's phone is valid for 15 minutes. * - * A user is limited to 10 active sessions at a time by default. [Learn more - * about session - * limits](https://appwrite.io/docs/authentication-security#limits). + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). * - * @param {string} userId - * @param {string} phone + * @param {string} params.userId - Unique Id. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the phone number has never been used, a new account is created using the provided userId. Otherwise, if the phone number is already attached to an account, the user ID is ignored. + * @param {string} params.phone - Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. * @throws {AppwriteException} * @returns {Promise} */ - createPhoneToken(userId: string, phone: string): Promise { + createPhoneToken(params: { userId: string, phone: string }): Promise; + /** + * 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 /v1/account/sessions/token](https://appwrite.io/docs/references/cloud/client-web/account#createSession) endpoint to complete the login process. The secret sent to the user's phone is valid for 15 minutes. + * + * A user is limited to 10 active sessions at a time by default. [Learn more about session limits](https://appwrite.io/docs/authentication-security#limits). + * + * @param {string} userId - Unique Id. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. If the phone number has never been used, a new account is created using the provided userId. Otherwise, if the phone number is already attached to an account, the user ID is ignored. + * @param {string} phone - Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createPhoneToken(userId: string, phone: string): Promise; + createPhoneToken( + paramsOrFirst: { userId: string, phone: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { userId: string, phone: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { userId: string, phone: string }; + } else { + params = { + userId: paramsOrFirst as string, + phone: rest[0] as string + }; + } + + const userId = params.userId; + const phone = params.phone; + if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } @@ -1323,27 +2418,43 @@ export class Account extends Service { } /** - * Use this endpoint to send a verification message to your user email address - * to confirm they are the valid owners of that address. Both the **userId** - * and **secret** arguments will be passed as query parameters to the URL you - * have provided to be attached to the verification email. The provided URL - * should redirect the user back to your app and allow you to complete the - * verification process by verifying both the **userId** and **secret** - * parameters. Learn more about how to [complete the verification - * process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). - * The verification link sent to the user's email address is valid for 7 days. + * Use this endpoint to send a verification message to your user email address to confirm they are the valid owners of that address. Both the **userId** and **secret** arguments will be passed as query parameters to the URL you have provided to be attached to the verification email. The provided URL should redirect the user back to your app and allow you to complete the verification process by verifying both the **userId** and **secret** parameters. Learn more about how to [complete the verification process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). The verification link sent to the user's email address is valid for 7 days. * - * Please note that in order to avoid a [Redirect - * Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), - * the only valid redirect URLs are the ones from domains you have set when - * adding your platforms in the console interface. + * Please note that in order to avoid a [Redirect Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), the only valid redirect URLs are the ones from domains you have set when adding your platforms in the console interface. * * - * @param {string} url + * @param {string} params.url - URL to redirect the user back to your app from the verification email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. * @throws {AppwriteException} * @returns {Promise} */ - createVerification(url: string): Promise { + createVerification(params: { url: string }): Promise; + /** + * Use this endpoint to send a verification message to your user email address to confirm they are the valid owners of that address. Both the **userId** and **secret** arguments will be passed as query parameters to the URL you have provided to be attached to the verification email. The provided URL should redirect the user back to your app and allow you to complete the verification process by verifying both the **userId** and **secret** parameters. Learn more about how to [complete the verification process](https://appwrite.io/docs/references/cloud/client-web/account#updateVerification). The verification link sent to the user's email address is valid for 7 days. + * + * Please note that in order to avoid a [Redirect Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), the only valid redirect URLs are the ones from domains you have set when adding your platforms in the console interface. + * + * + * @param {string} url - URL to redirect the user back to your app from the verification email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createVerification(url: string): Promise; + createVerification( + paramsOrFirst: { url: string } | string + ): Promise { + let params: { url: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { url: string }; + } else { + params = { + url: paramsOrFirst as string + }; + } + + const url = params.url; + if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } @@ -1362,17 +2473,42 @@ export class Account extends Service { } /** - * Use this endpoint to complete the user email verification process. Use both - * the **userId** and **secret** parameters that were attached to your app URL - * to verify the user email ownership. If confirmed this route will return a - * 200 status code. + * Use this endpoint to complete the user email verification process. Use both the **userId** and **secret** parameters that were attached to your app URL to verify the user email ownership. If confirmed this route will return a 200 status code. * - * @param {string} userId - * @param {string} secret + * @param {string} params.userId - User ID. + * @param {string} params.secret - Valid verification token. * @throws {AppwriteException} * @returns {Promise} */ - updateVerification(userId: string, secret: string): Promise { + updateVerification(params: { userId: string, secret: string }): Promise; + /** + * Use this endpoint to complete the user email verification process. Use both the **userId** and **secret** parameters that were attached to your app URL to verify the user email ownership. If confirmed this route will return a 200 status code. + * + * @param {string} userId - User ID. + * @param {string} secret - Valid verification token. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateVerification(userId: string, secret: string): Promise; + updateVerification( + paramsOrFirst: { userId: string, secret: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { userId: string, secret: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { userId: string, secret: string }; + } else { + params = { + userId: paramsOrFirst as string, + secret: rest[0] as string + }; + } + + const userId = params.userId; + const secret = params.secret; + if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } @@ -1399,14 +2535,7 @@ export class Account extends Service { } /** - * Use this endpoint to send a verification SMS to the currently logged in - * user. This endpoint is meant for use after updating a user's phone number - * using the - * [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) - * endpoint. Learn more about how to [complete the verification - * process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). - * The verification code sent to the user's phone number is valid for 15 - * minutes. + * Use this endpoint to send a verification SMS to the currently logged in user. This endpoint is meant for use after updating a user's phone number using the [accountUpdatePhone](https://appwrite.io/docs/references/cloud/client-web/account#updatePhone) endpoint. Learn more about how to [complete the verification process](https://appwrite.io/docs/references/cloud/client-web/account#updatePhoneVerification). The verification code sent to the user's phone number is valid for 15 minutes. * * @throws {AppwriteException} * @returns {Promise} @@ -1422,17 +2551,42 @@ export class Account extends Service { } /** - * Use this endpoint to complete the user phone verification process. Use the - * **userId** and **secret** that were sent to your user's phone number to - * verify the user email ownership. If confirmed this route will return a 200 - * status code. + * Use this endpoint to complete the user phone verification process. Use the **userId** and **secret** that were sent to your user's phone number to verify the user email ownership. If confirmed this route will return a 200 status code. * - * @param {string} userId - * @param {string} secret + * @param {string} params.userId - User ID. + * @param {string} params.secret - Valid verification token. * @throws {AppwriteException} * @returns {Promise} */ - updatePhoneVerification(userId: string, secret: string): Promise { + updatePhoneVerification(params: { userId: string, secret: string }): Promise; + /** + * Use this endpoint to complete the user phone verification process. Use the **userId** and **secret** that were sent to your user's phone number to verify the user email ownership. If confirmed this route will return a 200 status code. + * + * @param {string} userId - User ID. + * @param {string} secret - Valid verification token. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updatePhoneVerification(userId: string, secret: string): Promise; + updatePhoneVerification( + paramsOrFirst: { userId: string, secret: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { userId: string, secret: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { userId: string, secret: string }; + } else { + params = { + userId: paramsOrFirst as string, + secret: rest[0] as string + }; + } + + const userId = params.userId; + const secret = params.secret; + if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } diff --git a/src/services/avatars.ts b/src/services/avatars.ts index 5a66f64f..2eb848f4 100644 --- a/src/services/avatars.ts +++ b/src/services/avatars.ts @@ -17,25 +17,54 @@ export class Avatars extends Service { } /** - * You can use this endpoint to show different browser icons to your users. - * The code argument receives the browser code as it appears in your user [GET - * /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) - * endpoint. Use width, height and quality arguments to change the output - * settings. + * You can use this endpoint to show different browser icons to your users. The code argument receives the browser code as it appears in your user [GET /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) endpoint. Use width, height and quality arguments to change the output settings. * - * When one dimension is specified and the other is 0, the image is scaled - * with preserved aspect ratio. If both dimensions are 0, the API provides an - * image at source quality. If dimensions are not specified, the default size - * of image returned is 100x100px. + * When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 100x100px. * - * @param {Browser} code - * @param {number} width - * @param {number} height - * @param {number} quality + * @param {Browser} params.code - Browser Code. + * @param {number} params.width - Image width. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} params.height - Image height. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} params.quality - Image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. * @throws {AppwriteException} * @returns {ArrayBuffer} */ - getBrowser(code: Browser, width?: number, height?: number, quality?: number): Promise { + getBrowser(params: { code: Browser, width?: number, height?: number, quality?: number }): Promise; + /** + * You can use this endpoint to show different browser icons to your users. The code argument receives the browser code as it appears in your user [GET /account/sessions](https://appwrite.io/docs/references/cloud/client-web/account#getSessions) endpoint. Use width, height and quality arguments to change the output settings. + * + * When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 100x100px. + * + * @param {Browser} code - Browser Code. + * @param {number} width - Image width. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} height - Image height. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} quality - Image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getBrowser(code: Browser, width?: number, height?: number, quality?: number): Promise; + getBrowser( + paramsOrFirst: { code: Browser, width?: number, height?: number, quality?: number } | Browser, + ...rest: [(number)?, (number)?, (number)?] + ): Promise { + let params: { code: Browser, width?: number, height?: number, quality?: number }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'code' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { code: Browser, width?: number, height?: number, quality?: number }; + } else { + params = { + code: paramsOrFirst as Browser, + width: rest[0] as number, + height: rest[1] as number, + quality: rest[2] as number + }; + } + + const code = params.code; + const width = params.width; + const height = params.height; + const quality = params.quality; + if (typeof code === 'undefined') { throw new AppwriteException('Missing required parameter: "code"'); } @@ -67,24 +96,56 @@ export class Avatars extends Service { } /** - * The credit card endpoint will return you the icon of the credit card - * provider you need. Use width, height and quality arguments to change the - * output settings. + * The credit card endpoint will return you the icon of the credit card provider you need. Use width, height and quality arguments to change the output settings. * - * When one dimension is specified and the other is 0, the image is scaled - * with preserved aspect ratio. If both dimensions are 0, the API provides an - * image at source quality. If dimensions are not specified, the default size - * of image returned is 100x100px. + * When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 100x100px. * * - * @param {CreditCard} code - * @param {number} width - * @param {number} height - * @param {number} quality + * @param {CreditCard} params.code - Credit Card Code. Possible values: amex, argencard, cabal, cencosud, diners, discover, elo, hipercard, jcb, mastercard, naranja, targeta-shopping, union-china-pay, visa, mir, maestro, rupay. + * @param {number} params.width - Image width. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} params.height - Image height. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} params.quality - Image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. * @throws {AppwriteException} * @returns {ArrayBuffer} */ - getCreditCard(code: CreditCard, width?: number, height?: number, quality?: number): Promise { + getCreditCard(params: { code: CreditCard, width?: number, height?: number, quality?: number }): Promise; + /** + * The credit card endpoint will return you the icon of the credit card provider you need. Use width, height and quality arguments to change the output settings. + * + * When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 100x100px. + * + * + * @param {CreditCard} code - Credit Card Code. Possible values: amex, argencard, cabal, cencosud, diners, discover, elo, hipercard, jcb, mastercard, naranja, targeta-shopping, union-china-pay, visa, mir, maestro, rupay. + * @param {number} width - Image width. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} height - Image height. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} quality - Image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getCreditCard(code: CreditCard, width?: number, height?: number, quality?: number): Promise; + getCreditCard( + paramsOrFirst: { code: CreditCard, width?: number, height?: number, quality?: number } | CreditCard, + ...rest: [(number)?, (number)?, (number)?] + ): Promise { + let params: { code: CreditCard, width?: number, height?: number, quality?: number }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'code' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { code: CreditCard, width?: number, height?: number, quality?: number }; + } else { + params = { + code: paramsOrFirst as CreditCard, + width: rest[0] as number, + height: rest[1] as number, + quality: rest[2] as number + }; + } + + const code = params.code; + const width = params.width; + const height = params.height; + const quality = params.quality; + if (typeof code === 'undefined') { throw new AppwriteException('Missing required parameter: "code"'); } @@ -116,16 +177,41 @@ export class Avatars extends Service { } /** - * Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - * website URL. + * Use this endpoint to fetch the favorite icon (AKA favicon) of any remote website URL. * * This endpoint does not follow HTTP redirects. * - * @param {string} url + * @param {string} params.url - Website URL which you want to fetch the favicon from. * @throws {AppwriteException} * @returns {ArrayBuffer} */ - getFavicon(url: string): Promise { + getFavicon(params: { url: string }): Promise; + /** + * Use this endpoint to fetch the favorite icon (AKA favicon) of any remote website URL. + * + * This endpoint does not follow HTTP redirects. + * + * @param {string} url - Website URL which you want to fetch the favicon from. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getFavicon(url: string): Promise; + getFavicon( + paramsOrFirst: { url: string } | string + ): Promise { + let params: { url: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { url: string }; + } else { + params = { + url: paramsOrFirst as string + }; + } + + const url = params.url; + if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } @@ -149,25 +235,56 @@ export class Avatars extends Service { } /** - * You can use this endpoint to show different country flags icons to your - * users. The code argument receives the 2 letter country code. Use width, - * height and quality arguments to change the output settings. Country codes - * follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + * You can use this endpoint to show different country flags icons to your users. The code argument receives the 2 letter country code. Use width, height and quality arguments to change the output settings. Country codes follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. * - * When one dimension is specified and the other is 0, the image is scaled - * with preserved aspect ratio. If both dimensions are 0, the API provides an - * image at source quality. If dimensions are not specified, the default size - * of image returned is 100x100px. + * When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 100x100px. * * - * @param {Flag} code - * @param {number} width - * @param {number} height - * @param {number} quality + * @param {Flag} params.code - Country Code. ISO Alpha-2 country code format. + * @param {number} params.width - Image width. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} params.height - Image height. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} params.quality - Image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. * @throws {AppwriteException} * @returns {ArrayBuffer} */ - getFlag(code: Flag, width?: number, height?: number, quality?: number): Promise { + getFlag(params: { code: Flag, width?: number, height?: number, quality?: number }): Promise; + /** + * You can use this endpoint to show different country flags icons to your users. The code argument receives the 2 letter country code. Use width, height and quality arguments to change the output settings. Country codes follow the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) standard. + * + * When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 100x100px. + * + * + * @param {Flag} code - Country Code. ISO Alpha-2 country code format. + * @param {number} width - Image width. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} height - Image height. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} quality - Image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getFlag(code: Flag, width?: number, height?: number, quality?: number): Promise; + getFlag( + paramsOrFirst: { code: Flag, width?: number, height?: number, quality?: number } | Flag, + ...rest: [(number)?, (number)?, (number)?] + ): Promise { + let params: { code: Flag, width?: number, height?: number, quality?: number }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'code' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { code: Flag, width?: number, height?: number, quality?: number }; + } else { + params = { + code: paramsOrFirst as Flag, + width: rest[0] as number, + height: rest[1] as number, + quality: rest[2] as number + }; + } + + const code = params.code; + const width = params.width; + const height = params.height; + const quality = params.quality; + if (typeof code === 'undefined') { throw new AppwriteException('Missing required parameter: "code"'); } @@ -199,25 +316,54 @@ export class Avatars extends Service { } /** - * Use this endpoint to fetch a remote image URL and crop it to any image size - * you want. This endpoint is very useful if you need to crop and display - * remote images in your app or in case you want to make sure a 3rd party - * image is properly served using a TLS protocol. + * Use this endpoint to fetch a remote image URL and crop it to any image size you want. This endpoint is very useful if you need to crop and display remote images in your app or in case you want to make sure a 3rd party image is properly served using a TLS protocol. * - * When one dimension is specified and the other is 0, the image is scaled - * with preserved aspect ratio. If both dimensions are 0, the API provides an - * image at source quality. If dimensions are not specified, the default size - * of image returned is 400x400px. + * When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 400x400px. * * This endpoint does not follow HTTP redirects. * - * @param {string} url - * @param {number} width - * @param {number} height + * @param {string} params.url - Image URL which you want to crop. + * @param {number} params.width - Resize preview image width, Pass an integer between 0 to 2000. Defaults to 400. + * @param {number} params.height - Resize preview image height, Pass an integer between 0 to 2000. Defaults to 400. * @throws {AppwriteException} * @returns {ArrayBuffer} */ - getImage(url: string, width?: number, height?: number): Promise { + getImage(params: { url: string, width?: number, height?: number }): Promise; + /** + * Use this endpoint to fetch a remote image URL and crop it to any image size you want. This endpoint is very useful if you need to crop and display remote images in your app or in case you want to make sure a 3rd party image is properly served using a TLS protocol. + * + * When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 400x400px. + * + * This endpoint does not follow HTTP redirects. + * + * @param {string} url - Image URL which you want to crop. + * @param {number} width - Resize preview image width, Pass an integer between 0 to 2000. Defaults to 400. + * @param {number} height - Resize preview image height, Pass an integer between 0 to 2000. Defaults to 400. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getImage(url: string, width?: number, height?: number): Promise; + getImage( + paramsOrFirst: { url: string, width?: number, height?: number } | string, + ...rest: [(number)?, (number)?] + ): Promise { + let params: { url: string, width?: number, height?: number }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { url: string, width?: number, height?: number }; + } else { + params = { + url: paramsOrFirst as string, + width: rest[0] as number, + height: rest[1] as number + }; + } + + const url = params.url; + const width = params.width; + const height = params.height; + if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } @@ -249,31 +395,60 @@ export class Avatars extends Service { } /** - * Use this endpoint to show your user initials avatar icon on your website or - * app. By default, this route will try to print your logged-in user name or - * email initials. You can also overwrite the user name if you pass the 'name' - * parameter. If no name is given and no user is logged, an empty avatar will - * be returned. + * Use this endpoint to show your user initials avatar icon on your website or app. By default, this route will try to print your logged-in user name or email initials. You can also overwrite the user name if you pass the 'name' parameter. If no name is given and no user is logged, an empty avatar will be returned. * - * You can use the color and background params to change the avatar colors. By - * default, a random theme will be selected. The random theme will persist for - * the user's initials when reloading the same theme will always return for - * the same initials. + * You can use the color and background params to change the avatar colors. By default, a random theme will be selected. The random theme will persist for the user's initials when reloading the same theme will always return for the same initials. * - * When one dimension is specified and the other is 0, the image is scaled - * with preserved aspect ratio. If both dimensions are 0, the API provides an - * image at source quality. If dimensions are not specified, the default size - * of image returned is 100x100px. + * When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 100x100px. * * - * @param {string} name - * @param {number} width - * @param {number} height - * @param {string} background + * @param {string} params.name - Full Name. When empty, current user name or email will be used. Max length: 128 chars. + * @param {number} params.width - Image width. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} params.height - Image height. Pass an integer between 0 to 2000. Defaults to 100. + * @param {string} params.background - Changes background color. By default a random color will be picked and stay will persistent to the given name. * @throws {AppwriteException} * @returns {ArrayBuffer} */ - getInitials(name?: string, width?: number, height?: number, background?: string): Promise { + getInitials(params?: { name?: string, width?: number, height?: number, background?: string }): Promise; + /** + * Use this endpoint to show your user initials avatar icon on your website or app. By default, this route will try to print your logged-in user name or email initials. You can also overwrite the user name if you pass the 'name' parameter. If no name is given and no user is logged, an empty avatar will be returned. + * + * You can use the color and background params to change the avatar colors. By default, a random theme will be selected. The random theme will persist for the user's initials when reloading the same theme will always return for the same initials. + * + * When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 100x100px. + * + * + * @param {string} name - Full Name. When empty, current user name or email will be used. Max length: 128 chars. + * @param {number} width - Image width. Pass an integer between 0 to 2000. Defaults to 100. + * @param {number} height - Image height. Pass an integer between 0 to 2000. Defaults to 100. + * @param {string} background - Changes background color. By default a random color will be picked and stay will persistent to the given name. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getInitials(name?: string, width?: number, height?: number, background?: string): Promise; + getInitials( + paramsOrFirst?: { name?: string, width?: number, height?: number, background?: string } | string, + ...rest: [(number)?, (number)?, (string)?] + ): Promise { + let params: { name?: string, width?: number, height?: number, background?: string }; + + if (!paramsOrFirst || (paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { name?: string, width?: number, height?: number, background?: string }; + } else { + params = { + name: paramsOrFirst as string, + width: rest[0] as number, + height: rest[1] as number, + background: rest[2] as string + }; + } + + const name = params.name; + const width = params.width; + const height = params.height; + const background = params.background; + const apiPath = '/avatars/initials'; const payload: Payload = {}; @@ -305,18 +480,52 @@ export class Avatars extends Service { } /** - * Converts a given plain text to a QR code image. You can use the query - * parameters to change the size and style of the resulting image. + * Converts a given plain text to a QR code image. You can use the query parameters to change the size and style of the resulting image. * * - * @param {string} text - * @param {number} size - * @param {number} margin - * @param {boolean} download + * @param {string} params.text - Plain text to be converted to QR code image. + * @param {number} params.size - QR code size. Pass an integer between 1 to 1000. Defaults to 400. + * @param {number} params.margin - Margin from edge. Pass an integer between 0 to 10. Defaults to 1. + * @param {boolean} params.download - Return resulting image with 'Content-Disposition: attachment ' headers for the browser to start downloading it. Pass 0 for no header, or 1 for otherwise. Default value is set to 0. * @throws {AppwriteException} * @returns {ArrayBuffer} */ - getQR(text: string, size?: number, margin?: number, download?: boolean): Promise { + getQR(params: { text: string, size?: number, margin?: number, download?: boolean }): Promise; + /** + * Converts a given plain text to a QR code image. You can use the query parameters to change the size and style of the resulting image. + * + * + * @param {string} text - Plain text to be converted to QR code image. + * @param {number} size - QR code size. Pass an integer between 1 to 1000. Defaults to 400. + * @param {number} margin - Margin from edge. Pass an integer between 0 to 10. Defaults to 1. + * @param {boolean} download - Return resulting image with 'Content-Disposition: attachment ' headers for the browser to start downloading it. Pass 0 for no header, or 1 for otherwise. Default value is set to 0. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getQR(text: string, size?: number, margin?: number, download?: boolean): Promise; + getQR( + paramsOrFirst: { text: string, size?: number, margin?: number, download?: boolean } | string, + ...rest: [(number)?, (number)?, (boolean)?] + ): Promise { + let params: { text: string, size?: number, margin?: number, download?: boolean }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { text: string, size?: number, margin?: number, download?: boolean }; + } else { + params = { + text: paramsOrFirst as string, + size: rest[0] as number, + margin: rest[1] as number, + download: rest[2] as boolean + }; + } + + const text = params.text; + const size = params.size; + const margin = params.margin; + const download = params.download; + if (typeof text === 'undefined') { throw new AppwriteException('Missing required parameter: "text"'); } diff --git a/src/services/databases.ts b/src/services/databases.ts index ca803325..1ae1b0e7 100644 --- a/src/services/databases.ts +++ b/src/services/databases.ts @@ -14,16 +14,47 @@ export class Databases extends Service { } /** - * Get a list of all the user's documents in a given collection. You can use - * the query params to filter your results. + * Get a list of all the user's documents in a given collection. You can use the query params to filter your results. * - * @param {string} databaseId - * @param {string} collectionId - * @param {string[]} queries + * @param {string} params.databaseId - Database ID. + * @param {string} params.collectionId - Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). + * @param {string[]} params.queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `TablesDB.listRows` instead. */ - listDocuments(databaseId: string, collectionId: string, queries?: string[]): Promise> { + listDocuments(params: { databaseId: string, collectionId: string, queries?: string[] }): Promise>; + /** + * Get a list of all the user's documents in a given collection. You can use the query params to filter your results. + * + * @param {string} databaseId - Database ID. + * @param {string} collectionId - Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). + * @param {string[]} queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + listDocuments(databaseId: string, collectionId: string, queries?: string[]): Promise>; + listDocuments( + paramsOrFirst: { databaseId: string, collectionId: string, queries?: string[] } | string, + ...rest: [(string)?, (string[])?] + ): Promise> { + let params: { databaseId: string, collectionId: string, queries?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, collectionId: string, queries?: string[] }; + } else { + params = { + databaseId: paramsOrFirst as string, + collectionId: rest[0] as string, + queries: rest[1] as string[] + }; + } + + const databaseId = params.databaseId; + const collectionId = params.collectionId; + const queries = params.queries; + if (typeof databaseId === 'undefined') { throw new AppwriteException('Missing required parameter: "databaseId"'); } @@ -45,20 +76,55 @@ export class Databases extends Service { } /** - * Create a new Document. Before using this route, you should create a new - * collection resource using either a [server - * integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - * API or directly from your database console. + * Create a new Document. Before using this route, you should create a new collection resource using either a [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) API or directly from your database console. * - * @param {string} databaseId - * @param {string} collectionId - * @param {string} documentId - * @param {object} data - * @param {string[]} permissions + * @param {string} params.databaseId - Database ID. + * @param {string} params.collectionId - Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). Make sure to define attributes before creating documents. + * @param {string} params.documentId - Document ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {Document extends Models.DefaultDocument ? Partial & Record : Partial & Omit} params.data - Document data as JSON object. + * @param {string[]} params.permissions - An array of permissions strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `TablesDB.createRow` instead. */ - createDocument(databaseId: string, collectionId: string, documentId: string, data: object, permissions?: string[]): Promise { + createDocument(params: { databaseId: string, collectionId: string, documentId: string, data: Document extends Models.DefaultDocument ? Partial & Record : Partial & Omit, permissions?: string[] }): Promise; + /** + * Create a new Document. Before using this route, you should create a new collection resource using either a [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) API or directly from your database console. + * + * @param {string} databaseId - Database ID. + * @param {string} collectionId - Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). Make sure to define attributes before creating documents. + * @param {string} documentId - Document ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {Document extends Models.DefaultDocument ? Partial & Record : Partial & Omit} data - Document data as JSON object. + * @param {string[]} permissions - An array of permissions strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createDocument(databaseId: string, collectionId: string, documentId: string, data: Document extends Models.DefaultDocument ? Partial & Record : Partial & Omit, permissions?: string[]): Promise; + createDocument( + paramsOrFirst: { databaseId: string, collectionId: string, documentId: string, data: Document extends Models.DefaultDocument ? Partial & Record : Partial & Omit, permissions?: string[] } | string, + ...rest: [(string)?, (string)?, (Document extends Models.DefaultDocument ? Partial & Record : Partial & Omit)?, (string[])?] + ): Promise { + let params: { databaseId: string, collectionId: string, documentId: string, data: Document extends Models.DefaultDocument ? Partial & Record : Partial & Omit, permissions?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, collectionId: string, documentId: string, data: Document extends Models.DefaultDocument ? Partial & Record : Partial & Omit, permissions?: string[] }; + } else { + params = { + databaseId: paramsOrFirst as string, + collectionId: rest[0] as string, + documentId: rest[1] as string, + data: rest[2] as Document extends Models.DefaultDocument ? Partial & Record : Partial & Omit, + permissions: rest[3] as string[] + }; + } + + const databaseId = params.databaseId; + const collectionId = params.collectionId; + const documentId = params.documentId; + const data = params.data; + const permissions = params.permissions; + if (typeof databaseId === 'undefined') { throw new AppwriteException('Missing required parameter: "databaseId"'); } @@ -75,6 +141,9 @@ export class Databases extends Service { throw new AppwriteException('Missing required parameter: "data"'); } + delete data?.$sequence; + delete data?.$collectionId; + delete data?.$databaseId; const apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); const payload: Payload = {}; @@ -97,17 +166,51 @@ export class Databases extends Service { } /** - * Get a document by its unique ID. This endpoint response returns a JSON - * object with the document data. + * Get a document by its unique ID. This endpoint response returns a JSON object with the document data. * - * @param {string} databaseId - * @param {string} collectionId - * @param {string} documentId - * @param {string[]} queries + * @param {string} params.databaseId - Database ID. + * @param {string} params.collectionId - Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). + * @param {string} params.documentId - Document ID. + * @param {string[]} params.queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `TablesDB.getRow` instead. + */ + getDocument(params: { databaseId: string, collectionId: string, documentId: string, queries?: string[] }): Promise; + /** + * Get a document by its unique ID. This endpoint response returns a JSON object with the document data. + * + * @param {string} databaseId - Database ID. + * @param {string} collectionId - Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). + * @param {string} documentId - Document ID. + * @param {string[]} queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. */ - getDocument(databaseId: string, collectionId: string, documentId: string, queries?: string[]): Promise { + getDocument(databaseId: string, collectionId: string, documentId: string, queries?: string[]): Promise; + getDocument( + paramsOrFirst: { databaseId: string, collectionId: string, documentId: string, queries?: string[] } | string, + ...rest: [(string)?, (string)?, (string[])?] + ): Promise { + let params: { databaseId: string, collectionId: string, documentId: string, queries?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, collectionId: string, documentId: string, queries?: string[] }; + } else { + params = { + databaseId: paramsOrFirst as string, + collectionId: rest[0] as string, + documentId: rest[1] as string, + queries: rest[2] as string[] + }; + } + + const databaseId = params.databaseId; + const collectionId = params.collectionId; + const documentId = params.documentId; + const queries = params.queries; + if (typeof databaseId === 'undefined') { throw new AppwriteException('Missing required parameter: "databaseId"'); } @@ -133,24 +236,55 @@ export class Databases extends Service { } /** - * **WARNING: Experimental Feature** - This endpoint is experimental and not - * yet officially supported. It may be subject to breaking changes or removal - * in future versions. - * - * Create or update a Document. Before using this route, you should create a - * new collection resource using either a [server - * integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - * API or directly from your database console. + * Create or update a Document. Before using this route, you should create a new collection resource using either a [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) API or directly from your database console. * - * @param {string} databaseId - * @param {string} collectionId - * @param {string} documentId - * @param {object} data - * @param {string[]} permissions + * @param {string} params.databaseId - Database ID. + * @param {string} params.collectionId - Collection ID. + * @param {string} params.documentId - Document ID. + * @param {Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>} params.data - Document data as JSON object. Include all required attributes of the document to be created or updated. + * @param {string[]} params.permissions - An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `TablesDB.upsertRow` instead. */ - upsertDocument(databaseId: string, collectionId: string, documentId: string, data: object, permissions?: string[]): Promise { + upsertDocument(params: { databaseId: string, collectionId: string, documentId: string, data: Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>, permissions?: string[] }): Promise; + /** + * Create or update a Document. Before using this route, you should create a new collection resource using either a [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) API or directly from your database console. + * + * @param {string} databaseId - Database ID. + * @param {string} collectionId - Collection ID. + * @param {string} documentId - Document ID. + * @param {Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>} data - Document data as JSON object. Include all required attributes of the document to be created or updated. + * @param {string[]} permissions - An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + upsertDocument(databaseId: string, collectionId: string, documentId: string, data: Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>, permissions?: string[]): Promise; + upsertDocument( + paramsOrFirst: { databaseId: string, collectionId: string, documentId: string, data: Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>, permissions?: string[] } | string, + ...rest: [(string)?, (string)?, (Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>)?, (string[])?] + ): Promise { + let params: { databaseId: string, collectionId: string, documentId: string, data: Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>, permissions?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, collectionId: string, documentId: string, data: Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>, permissions?: string[] }; + } else { + params = { + databaseId: paramsOrFirst as string, + collectionId: rest[0] as string, + documentId: rest[1] as string, + data: rest[2] as Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>, + permissions: rest[3] as string[] + }; + } + + const databaseId = params.databaseId; + const collectionId = params.collectionId; + const documentId = params.documentId; + const data = params.data; + const permissions = params.permissions; + if (typeof databaseId === 'undefined') { throw new AppwriteException('Missing required parameter: "databaseId"'); } @@ -167,6 +301,9 @@ export class Databases extends Service { throw new AppwriteException('Missing required parameter: "data"'); } + delete data?.$sequence; + delete data?.$collectionId; + delete data?.$databaseId; const apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); const payload: Payload = {}; @@ -185,18 +322,55 @@ export class Databases extends Service { } /** - * Update a document by its unique ID. Using the patch method you can pass - * only specific fields that will get updated. + * Update a document by its unique ID. Using the patch method you can pass only specific fields that will get updated. * - * @param {string} databaseId - * @param {string} collectionId - * @param {string} documentId - * @param {object} data - * @param {string[]} permissions + * @param {string} params.databaseId - Database ID. + * @param {string} params.collectionId - Collection ID. + * @param {string} params.documentId - Document ID. + * @param {Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>} params.data - Document data as JSON object. Include only attribute and value pairs to be updated. + * @param {string[]} params.permissions - An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `TablesDB.updateRow` instead. */ - updateDocument(databaseId: string, collectionId: string, documentId: string, data?: object, permissions?: string[]): Promise { + updateDocument(params: { databaseId: string, collectionId: string, documentId: string, data?: Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>, permissions?: string[] }): Promise; + /** + * Update a document by its unique ID. Using the patch method you can pass only specific fields that will get updated. + * + * @param {string} databaseId - Database ID. + * @param {string} collectionId - Collection ID. + * @param {string} documentId - Document ID. + * @param {Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>} data - Document data as JSON object. Include only attribute and value pairs to be updated. + * @param {string[]} permissions - An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateDocument(databaseId: string, collectionId: string, documentId: string, data?: Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>, permissions?: string[]): Promise; + updateDocument( + paramsOrFirst: { databaseId: string, collectionId: string, documentId: string, data?: Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>, permissions?: string[] } | string, + ...rest: [(string)?, (string)?, (Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>)?, (string[])?] + ): Promise { + let params: { databaseId: string, collectionId: string, documentId: string, data?: Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>, permissions?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, collectionId: string, documentId: string, data?: Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>, permissions?: string[] }; + } else { + params = { + databaseId: paramsOrFirst as string, + collectionId: rest[0] as string, + documentId: rest[1] as string, + data: rest[2] as Document extends Models.DefaultDocument ? Partial & Record : Partial & Partial>, + permissions: rest[3] as string[] + }; + } + + const databaseId = params.databaseId; + const collectionId = params.collectionId; + const documentId = params.documentId; + const data = params.data; + const permissions = params.permissions; + if (typeof databaseId === 'undefined') { throw new AppwriteException('Missing required parameter: "databaseId"'); } @@ -209,6 +383,9 @@ export class Databases extends Service { throw new AppwriteException('Missing required parameter: "documentId"'); } + delete data?.$sequence; + delete data?.$collectionId; + delete data?.$databaseId; const apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); const payload: Payload = {}; @@ -229,13 +406,45 @@ export class Databases extends Service { /** * Delete a document by its unique ID. * - * @param {string} databaseId - * @param {string} collectionId - * @param {string} documentId + * @param {string} params.databaseId - Database ID. + * @param {string} params.collectionId - Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). + * @param {string} params.documentId - Document ID. * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `TablesDB.deleteRow` instead. */ - deleteDocument(databaseId: string, collectionId: string, documentId: string): Promise<{}> { + deleteDocument(params: { databaseId: string, collectionId: string, documentId: string }): Promise<{}>; + /** + * Delete a document by its unique ID. + * + * @param {string} databaseId - Database ID. + * @param {string} collectionId - Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection). + * @param {string} documentId - Document ID. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + deleteDocument(databaseId: string, collectionId: string, documentId: string): Promise<{}>; + deleteDocument( + paramsOrFirst: { databaseId: string, collectionId: string, documentId: string } | string, + ...rest: [(string)?, (string)?] + ): Promise<{}> { + let params: { databaseId: string, collectionId: string, documentId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, collectionId: string, documentId: string }; + } else { + params = { + databaseId: paramsOrFirst as string, + collectionId: rest[0] as string, + documentId: rest[1] as string + }; + } + + const databaseId = params.databaseId; + const collectionId = params.collectionId; + const documentId = params.documentId; + if (typeof databaseId === 'undefined') { throw new AppwriteException('Missing required parameter: "databaseId"'); } @@ -260,16 +469,57 @@ export class Databases extends Service { /** * Decrement a specific attribute of a document by a given value. * - * @param {string} databaseId - * @param {string} collectionId - * @param {string} documentId - * @param {string} attribute - * @param {number} value - * @param {number} min + * @param {string} params.databaseId - Database ID. + * @param {string} params.collectionId - Collection ID. + * @param {string} params.documentId - Document ID. + * @param {string} params.attribute - Attribute key. + * @param {number} params.value - Value to increment the attribute by. The value must be a number. + * @param {number} params.min - Minimum value for the attribute. If the current value is lesser than this value, an exception will be thrown. * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `TablesDB.decrementRowColumn` instead. */ - decrementDocumentAttribute(databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, min?: number): Promise { + decrementDocumentAttribute(params: { databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, min?: number }): Promise; + /** + * Decrement a specific attribute of a document by a given value. + * + * @param {string} databaseId - Database ID. + * @param {string} collectionId - Collection ID. + * @param {string} documentId - Document ID. + * @param {string} attribute - Attribute key. + * @param {number} value - Value to increment the attribute by. The value must be a number. + * @param {number} min - Minimum value for the attribute. If the current value is lesser than this value, an exception will be thrown. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + decrementDocumentAttribute(databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, min?: number): Promise; + decrementDocumentAttribute( + paramsOrFirst: { databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, min?: number } | string, + ...rest: [(string)?, (string)?, (string)?, (number)?, (number)?] + ): Promise { + let params: { databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, min?: number }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, min?: number }; + } else { + params = { + databaseId: paramsOrFirst as string, + collectionId: rest[0] as string, + documentId: rest[1] as string, + attribute: rest[2] as string, + value: rest[3] as number, + min: rest[4] as number + }; + } + + const databaseId = params.databaseId; + const collectionId = params.collectionId; + const documentId = params.documentId; + const attribute = params.attribute; + const value = params.value; + const min = params.min; + if (typeof databaseId === 'undefined') { throw new AppwriteException('Missing required parameter: "databaseId"'); } @@ -306,16 +556,57 @@ export class Databases extends Service { /** * Increment a specific attribute of a document by a given value. * - * @param {string} databaseId - * @param {string} collectionId - * @param {string} documentId - * @param {string} attribute - * @param {number} value - * @param {number} max + * @param {string} params.databaseId - Database ID. + * @param {string} params.collectionId - Collection ID. + * @param {string} params.documentId - Document ID. + * @param {string} params.attribute - Attribute key. + * @param {number} params.value - Value to increment the attribute by. The value must be a number. + * @param {number} params.max - Maximum value for the attribute. If the current value is greater than this value, an error will be thrown. * @throws {AppwriteException} * @returns {Promise} + * @deprecated This API has been deprecated since 1.8.0. Please use `TablesDB.incrementRowColumn` instead. + */ + incrementDocumentAttribute(params: { databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, max?: number }): Promise; + /** + * Increment a specific attribute of a document by a given value. + * + * @param {string} databaseId - Database ID. + * @param {string} collectionId - Collection ID. + * @param {string} documentId - Document ID. + * @param {string} attribute - Attribute key. + * @param {number} value - Value to increment the attribute by. The value must be a number. + * @param {number} max - Maximum value for the attribute. If the current value is greater than this value, an error will be thrown. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. */ - incrementDocumentAttribute(databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, max?: number): Promise { + incrementDocumentAttribute(databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, max?: number): Promise; + incrementDocumentAttribute( + paramsOrFirst: { databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, max?: number } | string, + ...rest: [(string)?, (string)?, (string)?, (number)?, (number)?] + ): Promise { + let params: { databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, max?: number }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, max?: number }; + } else { + params = { + databaseId: paramsOrFirst as string, + collectionId: rest[0] as string, + documentId: rest[1] as string, + attribute: rest[2] as string, + value: rest[3] as number, + max: rest[4] as number + }; + } + + const databaseId = params.databaseId; + const collectionId = params.collectionId; + const documentId = params.documentId; + const attribute = params.attribute; + const value = params.value; + const max = params.max; + if (typeof databaseId === 'undefined') { throw new AppwriteException('Missing required parameter: "databaseId"'); } diff --git a/src/services/functions.ts b/src/services/functions.ts index 6b0134c7..8903514a 100644 --- a/src/services/functions.ts +++ b/src/services/functions.ts @@ -15,15 +15,42 @@ export class Functions extends Service { } /** - * Get a list of all the current user function execution logs. You can use the - * query params to filter your results. + * Get a list of all the current user function execution logs. You can use the query params to filter your results. * - * @param {string} functionId - * @param {string[]} queries + * @param {string} params.functionId - Function ID. + * @param {string[]} params.queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: trigger, status, responseStatusCode, duration, requestMethod, requestPath, deploymentId * @throws {AppwriteException} * @returns {Promise} */ - listExecutions(functionId: string, queries?: string[]): Promise { + listExecutions(params: { functionId: string, queries?: string[] }): Promise; + /** + * Get a list of all the current user function execution logs. You can use the query params to filter your results. + * + * @param {string} functionId - Function ID. + * @param {string[]} queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: trigger, status, responseStatusCode, duration, requestMethod, requestPath, deploymentId + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + listExecutions(functionId: string, queries?: string[]): Promise; + listExecutions( + paramsOrFirst: { functionId: string, queries?: string[] } | string, + ...rest: [(string[])?] + ): Promise { + let params: { functionId: string, queries?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { functionId: string, queries?: string[] }; + } else { + params = { + functionId: paramsOrFirst as string, + queries: rest[0] as string[] + }; + } + + const functionId = params.functionId; + const queries = params.queries; + if (typeof functionId === 'undefined') { throw new AppwriteException('Missing required parameter: "functionId"'); } @@ -41,22 +68,62 @@ export class Functions extends Service { } /** - * Trigger a function execution. The returned object will return you the - * current execution status. You can ping the `Get Execution` endpoint to get - * updates on the current execution status. Once this endpoint is called, your - * function execution process will start asynchronously. + * Trigger a function execution. The returned object will return you the current execution status. You can ping the `Get Execution` endpoint to get updates on the current execution status. Once this endpoint is called, your function execution process will start asynchronously. * - * @param {string} functionId - * @param {string} body - * @param {boolean} async - * @param {string} xpath - * @param {ExecutionMethod} method - * @param {object} headers - * @param {string} scheduledAt + * @param {string} params.functionId - Function ID. + * @param {string} params.body - HTTP body of execution. Default value is empty string. + * @param {boolean} params.async - Execute code in the background. Default value is false. + * @param {string} params.xpath - HTTP path of execution. Path can include query params. Default value is / + * @param {ExecutionMethod} params.method - HTTP method of execution. Default value is GET. + * @param {object} params.headers - HTTP headers of execution. Defaults to empty. + * @param {string} params.scheduledAt - Scheduled execution time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future with precision in minutes. * @throws {AppwriteException} * @returns {Promise} */ - createExecution(functionId: string, body?: string, async?: boolean, xpath?: string, method?: ExecutionMethod, headers?: object, scheduledAt?: string): Promise { + createExecution(params: { functionId: string, body?: string, async?: boolean, xpath?: string, method?: ExecutionMethod, headers?: object, scheduledAt?: string }): Promise; + /** + * Trigger a function execution. The returned object will return you the current execution status. You can ping the `Get Execution` endpoint to get updates on the current execution status. Once this endpoint is called, your function execution process will start asynchronously. + * + * @param {string} functionId - Function ID. + * @param {string} body - HTTP body of execution. Default value is empty string. + * @param {boolean} async - Execute code in the background. Default value is false. + * @param {string} xpath - HTTP path of execution. Path can include query params. Default value is / + * @param {ExecutionMethod} method - HTTP method of execution. Default value is GET. + * @param {object} headers - HTTP headers of execution. Defaults to empty. + * @param {string} scheduledAt - Scheduled execution time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. DateTime value must be in future with precision in minutes. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createExecution(functionId: string, body?: string, async?: boolean, xpath?: string, method?: ExecutionMethod, headers?: object, scheduledAt?: string): Promise; + createExecution( + paramsOrFirst: { functionId: string, body?: string, async?: boolean, xpath?: string, method?: ExecutionMethod, headers?: object, scheduledAt?: string } | string, + ...rest: [(string)?, (boolean)?, (string)?, (ExecutionMethod)?, (object)?, (string)?] + ): Promise { + let params: { functionId: string, body?: string, async?: boolean, xpath?: string, method?: ExecutionMethod, headers?: object, scheduledAt?: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { functionId: string, body?: string, async?: boolean, xpath?: string, method?: ExecutionMethod, headers?: object, scheduledAt?: string }; + } else { + params = { + functionId: paramsOrFirst as string, + body: rest[0] as string, + async: rest[1] as boolean, + xpath: rest[2] as string, + method: rest[3] as ExecutionMethod, + headers: rest[4] as object, + scheduledAt: rest[5] as string + }; + } + + const functionId = params.functionId; + const body = params.body; + const async = params.async; + const xpath = params.xpath; + const method = params.method; + const headers = params.headers; + const scheduledAt = params.scheduledAt; + if (typeof functionId === 'undefined') { throw new AppwriteException('Missing required parameter: "functionId"'); } @@ -97,12 +164,40 @@ export class Functions extends Service { /** * Get a function execution log by its unique ID. * - * @param {string} functionId - * @param {string} executionId + * @param {string} params.functionId - Function ID. + * @param {string} params.executionId - Execution ID. * @throws {AppwriteException} * @returns {Promise} */ - getExecution(functionId: string, executionId: string): Promise { + getExecution(params: { functionId: string, executionId: string }): Promise; + /** + * Get a function execution log by its unique ID. + * + * @param {string} functionId - Function ID. + * @param {string} executionId - Execution ID. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getExecution(functionId: string, executionId: string): Promise; + getExecution( + paramsOrFirst: { functionId: string, executionId: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { functionId: string, executionId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { functionId: string, executionId: string }; + } else { + params = { + functionId: paramsOrFirst as string, + executionId: rest[0] as string + }; + } + + const functionId = params.functionId; + const executionId = params.executionId; + if (typeof functionId === 'undefined') { throw new AppwriteException('Missing required parameter: "functionId"'); } diff --git a/src/services/graphql.ts b/src/services/graphql.ts index 8655f00c..4d67b695 100644 --- a/src/services/graphql.ts +++ b/src/services/graphql.ts @@ -16,11 +16,35 @@ export class Graphql extends Service { /** * Execute a GraphQL mutation. * - * @param {object} query + * @param {object} params.query - The query or queries to execute. * @throws {AppwriteException} * @returns {Promise} */ - query(query: object): Promise<{}> { + query(params: { query: object }): Promise<{}>; + /** + * Execute a GraphQL mutation. + * + * @param {object} query - The query or queries to execute. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + query(query: object): Promise<{}>; + query( + paramsOrFirst: { query: object } | object + ): Promise<{}> { + let params: { query: object }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'query' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { query: object }; + } else { + params = { + query: paramsOrFirst as object + }; + } + + const query = params.query; + if (typeof query === 'undefined') { throw new AppwriteException('Missing required parameter: "query"'); } @@ -42,11 +66,35 @@ export class Graphql extends Service { /** * Execute a GraphQL mutation. * - * @param {object} query + * @param {object} params.query - The query or queries to execute. * @throws {AppwriteException} * @returns {Promise} */ - mutation(query: object): Promise<{}> { + mutation(params: { query: object }): Promise<{}>; + /** + * Execute a GraphQL mutation. + * + * @param {object} query - The query or queries to execute. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + mutation(query: object): Promise<{}>; + mutation( + paramsOrFirst: { query: object } | object + ): Promise<{}> { + let params: { query: object }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst) && 'query' in paramsOrFirst)) { + params = (paramsOrFirst || {}) as { query: object }; + } else { + params = { + query: paramsOrFirst as object + }; + } + + const query = params.query; + if (typeof query === 'undefined') { throw new AppwriteException('Missing required parameter: "query"'); } diff --git a/src/services/locale.ts b/src/services/locale.ts index 7a29f954..eef30bcf 100644 --- a/src/services/locale.ts +++ b/src/services/locale.ts @@ -14,10 +14,7 @@ export class Locale extends Service { } /** - * Get the current user location based on IP. Returns an object with user - * country code, country name, continent name, continent code, ip address and - * suggested currency. You can use the locale header to get the data in a - * supported language. + * Get the current user location based on IP. Returns an object with user country code, country name, continent name, continent code, ip address and suggested currency. You can use the locale header to get the data in a supported language. * * ([IP Geolocation by DB-IP](https://db-ip.com)) * @@ -34,8 +31,7 @@ export class Locale extends Service { } /** - * List of all locale codes in [ISO - * 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + * List of all locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). * * @throws {AppwriteException} * @returns {Promise} @@ -50,8 +46,7 @@ export class Locale extends Service { } /** - * List of all continents. You can use the locale header to get the data in a - * supported language. + * List of all continents. You can use the locale header to get the data in a supported language. * * @throws {AppwriteException} * @returns {Promise} @@ -66,8 +61,7 @@ export class Locale extends Service { } /** - * List of all countries. You can use the locale header to get the data in a - * supported language. + * List of all countries. You can use the locale header to get the data in a supported language. * * @throws {AppwriteException} * @returns {Promise} @@ -82,8 +76,7 @@ export class Locale extends Service { } /** - * List of all countries that are currently members of the EU. You can use the - * locale header to get the data in a supported language. + * List of all countries that are currently members of the EU. You can use the locale header to get the data in a supported language. * * @throws {AppwriteException} * @returns {Promise} @@ -98,8 +91,7 @@ export class Locale extends Service { } /** - * List of all countries phone codes. You can use the locale header to get the - * data in a supported language. + * List of all countries phone codes. You can use the locale header to get the data in a supported language. * * @throws {AppwriteException} * @returns {Promise} @@ -114,9 +106,7 @@ export class Locale extends Service { } /** - * List of all currencies, including currency symbol, name, plural, and - * decimal digits for all major and minor currencies. You can use the locale - * header to get the data in a supported language. + * List of all currencies, including currency symbol, name, plural, and decimal digits for all major and minor currencies. You can use the locale header to get the data in a supported language. * * @throws {AppwriteException} * @returns {Promise} @@ -131,8 +121,7 @@ export class Locale extends Service { } /** - * List of all languages classified by ISO 639-1 including 2-letter code, name - * in English, and name in the respective language. + * List of all languages classified by ISO 639-1 including 2-letter code, name in English, and name in the respective language. * * @throws {AppwriteException} * @returns {Promise} diff --git a/src/services/messaging.ts b/src/services/messaging.ts index e6edd34d..7f0a9de6 100644 --- a/src/services/messaging.ts +++ b/src/services/messaging.ts @@ -16,13 +16,44 @@ export class Messaging extends Service { /** * Create a new subscriber. * - * @param {string} topicId - * @param {string} subscriberId - * @param {string} targetId + * @param {string} params.topicId - Topic ID. The topic ID to subscribe to. + * @param {string} params.subscriberId - Subscriber ID. Choose a custom Subscriber ID or a new Subscriber ID. + * @param {string} params.targetId - Target ID. The target ID to link to the specified Topic ID. * @throws {AppwriteException} * @returns {Promise} */ - createSubscriber(topicId: string, subscriberId: string, targetId: string): Promise { + createSubscriber(params: { topicId: string, subscriberId: string, targetId: string }): Promise; + /** + * Create a new subscriber. + * + * @param {string} topicId - Topic ID. The topic ID to subscribe to. + * @param {string} subscriberId - Subscriber ID. Choose a custom Subscriber ID or a new Subscriber ID. + * @param {string} targetId - Target ID. The target ID to link to the specified Topic ID. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createSubscriber(topicId: string, subscriberId: string, targetId: string): Promise; + createSubscriber( + paramsOrFirst: { topicId: string, subscriberId: string, targetId: string } | string, + ...rest: [(string)?, (string)?] + ): Promise { + let params: { topicId: string, subscriberId: string, targetId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { topicId: string, subscriberId: string, targetId: string }; + } else { + params = { + topicId: paramsOrFirst as string, + subscriberId: rest[0] as string, + targetId: rest[1] as string + }; + } + + const topicId = params.topicId; + const subscriberId = params.subscriberId; + const targetId = params.targetId; + if (typeof topicId === 'undefined') { throw new AppwriteException('Missing required parameter: "topicId"'); } @@ -55,12 +86,40 @@ export class Messaging extends Service { /** * Delete a subscriber by its unique ID. * - * @param {string} topicId - * @param {string} subscriberId + * @param {string} params.topicId - Topic ID. The topic ID subscribed to. + * @param {string} params.subscriberId - Subscriber ID. * @throws {AppwriteException} * @returns {Promise} */ - deleteSubscriber(topicId: string, subscriberId: string): Promise<{}> { + deleteSubscriber(params: { topicId: string, subscriberId: string }): Promise<{}>; + /** + * Delete a subscriber by its unique ID. + * + * @param {string} topicId - Topic ID. The topic ID subscribed to. + * @param {string} subscriberId - Subscriber ID. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + deleteSubscriber(topicId: string, subscriberId: string): Promise<{}>; + deleteSubscriber( + paramsOrFirst: { topicId: string, subscriberId: string } | string, + ...rest: [(string)?] + ): Promise<{}> { + let params: { topicId: string, subscriberId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { topicId: string, subscriberId: string }; + } else { + params = { + topicId: paramsOrFirst as string, + subscriberId: rest[0] as string + }; + } + + const topicId = params.topicId; + const subscriberId = params.subscriberId; + if (typeof topicId === 'undefined') { throw new AppwriteException('Missing required parameter: "topicId"'); } diff --git a/src/services/storage.ts b/src/services/storage.ts index e062b2fb..7b47ea23 100644 --- a/src/services/storage.ts +++ b/src/services/storage.ts @@ -16,16 +16,46 @@ export class Storage extends Service { } /** - * Get a list of all the user files. You can use the query params to filter - * your results. + * Get a list of all the user files. You can use the query params to filter your results. * - * @param {string} bucketId - * @param {string[]} queries - * @param {string} search + * @param {string} params.bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string[]} params.queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, signature, mimeType, sizeOriginal, chunksTotal, chunksUploaded + * @param {string} params.search - Search term to filter your list results. Max length: 256 chars. * @throws {AppwriteException} * @returns {Promise} */ - listFiles(bucketId: string, queries?: string[], search?: string): Promise { + listFiles(params: { bucketId: string, queries?: string[], search?: string }): Promise; + /** + * Get a list of all the user files. You can use the query params to filter your results. + * + * @param {string} bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string[]} queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, signature, mimeType, sizeOriginal, chunksTotal, chunksUploaded + * @param {string} search - Search term to filter your list results. Max length: 256 chars. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + listFiles(bucketId: string, queries?: string[], search?: string): Promise; + listFiles( + paramsOrFirst: { bucketId: string, queries?: string[], search?: string } | string, + ...rest: [(string[])?, (string)?] + ): Promise { + let params: { bucketId: string, queries?: string[], search?: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { bucketId: string, queries?: string[], search?: string }; + } else { + params = { + bucketId: paramsOrFirst as string, + queries: rest[0] as string[], + search: rest[1] as string + }; + } + + const bucketId = params.bucketId; + const queries = params.queries; + const search = params.search; + if (typeof bucketId === 'undefined') { throw new AppwriteException('Missing required parameter: "bucketId"'); } @@ -47,33 +77,67 @@ export class Storage extends Service { } /** - * Create a new file. Before using this route, you should create a new bucket - * resource using either a [server - * integration](https://appwrite.io/docs/server/storage#storageCreateBucket) - * API or directly from your Appwrite console. + * Create a new file. Before using this route, you should create a new bucket resource using either a [server integration](https://appwrite.io/docs/server/storage#storageCreateBucket) API or directly from your Appwrite console. * - * Larger files should be uploaded using multiple requests with the - * [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) - * header to send a partial request with a maximum supported chunk of `5MB`. - * The `content-range` header values should always be in bytes. + * Larger files should be uploaded using multiple requests with the [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) header to send a partial request with a maximum supported chunk of `5MB`. The `content-range` header values should always be in bytes. * - * When the first request is sent, the server will return the **File** object, - * and the subsequent part request must include the file's **id** in - * `x-appwrite-id` header to allow the server to know that the partial upload - * is for the existing file and not for a new one. + * When the first request is sent, the server will return the **File** object, and the subsequent part request must include the file's **id** in `x-appwrite-id` header to allow the server to know that the partial upload is for the existing file and not for a new one. * - * If you're creating a new file using one of the Appwrite SDKs, all the - * chunking logic will be managed by the SDK internally. + * If you're creating a new file using one of the Appwrite SDKs, all the chunking logic will be managed by the SDK internally. * * - * @param {string} bucketId - * @param {string} fileId - * @param {{name: string, type: string, size: number, uri: string}} file - * @param {string[]} permissions + * @param {string} params.bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} params.fileId - File ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {{name: string, type: string, size: number, uri: string}} params.file - Binary file. Appwrite SDKs provide helpers to handle file input. [Learn about file input](https://appwrite.io/docs/products/storage/upload-download#input-file). + * @param {string[]} params.permissions - An array of permission strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). * @throws {AppwriteException} * @returns {Promise} */ - async createFile(bucketId: string, fileId: string, file: {name: string, type: string, size: number, uri: string}, permissions?: string[], onProgress = (progress: UploadProgress) => {}): Promise { + async createFile(params: { bucketId: string, fileId: string, file: {name: string, type: string, size: number, uri: string}, permissions?: string[] , onProgress?: (progress: UploadProgress) => void }): Promise; + /** + * Create a new file. Before using this route, you should create a new bucket resource using either a [server integration](https://appwrite.io/docs/server/storage#storageCreateBucket) API or directly from your Appwrite console. + * + * Larger files should be uploaded using multiple requests with the [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) header to send a partial request with a maximum supported chunk of `5MB`. The `content-range` header values should always be in bytes. + * + * When the first request is sent, the server will return the **File** object, and the subsequent part request must include the file's **id** in `x-appwrite-id` header to allow the server to know that the partial upload is for the existing file and not for a new one. + * + * If you're creating a new file using one of the Appwrite SDKs, all the chunking logic will be managed by the SDK internally. + * + * + * @param {string} bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} fileId - File ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {{name: string, type: string, size: number, uri: string}} file - Binary file. Appwrite SDKs provide helpers to handle file input. [Learn about file input](https://appwrite.io/docs/products/storage/upload-download#input-file). + * @param {string[]} permissions - An array of permission strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + async createFile(bucketId: string, fileId: string, file: {name: string, type: string, size: number, uri: string}, permissions?: string[], onProgress?: (progress: UploadProgress) => void): Promise; + async createFile( + paramsOrFirst: { bucketId: string, fileId: string, file: {name: string, type: string, size: number, uri: string}, permissions?: string[], onProgress?: (progress: UploadProgress) => void } | string, + ...rest: [(string)?, ({name: string, type: string, size: number, uri: string})?, (string[])?,((progress: UploadProgress) => void)?] + ): Promise { + let params: { bucketId: string, fileId: string, file: {name: string, type: string, size: number, uri: string}, permissions?: string[] }; + let onProgress: ((progress: UploadProgress) => void); + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { bucketId: string, fileId: string, file: {name: string, type: string, size: number, uri: string}, permissions?: string[] }; + onProgress = paramsOrFirst?.onProgress as ((progress: UploadProgress) => void); + } else { + params = { + bucketId: paramsOrFirst as string, + fileId: rest[0] as string, + file: rest[1] as {name: string, type: string, size: number, uri: string}, + permissions: rest[2] as string[] + }; + onProgress = rest[3] as ((progress: UploadProgress) => void); + } + + const bucketId = params.bucketId; + const fileId = params.fileId; + const file = params.file; + const permissions = params.permissions; + if (typeof bucketId === 'undefined') { throw new AppwriteException('Missing required parameter: "bucketId"'); } @@ -162,15 +226,42 @@ export class Storage extends Service { } /** - * Get a file by its unique ID. This endpoint response returns a JSON object - * with the file metadata. + * Get a file by its unique ID. This endpoint response returns a JSON object with the file metadata. * - * @param {string} bucketId - * @param {string} fileId + * @param {string} params.bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} params.fileId - File ID. * @throws {AppwriteException} * @returns {Promise} */ - getFile(bucketId: string, fileId: string): Promise { + getFile(params: { bucketId: string, fileId: string }): Promise; + /** + * Get a file by its unique ID. This endpoint response returns a JSON object with the file metadata. + * + * @param {string} bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} fileId - File ID. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getFile(bucketId: string, fileId: string): Promise; + getFile( + paramsOrFirst: { bucketId: string, fileId: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { bucketId: string, fileId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { bucketId: string, fileId: string }; + } else { + params = { + bucketId: paramsOrFirst as string, + fileId: rest[0] as string + }; + } + + const bucketId = params.bucketId; + const fileId = params.fileId; + if (typeof bucketId === 'undefined') { throw new AppwriteException('Missing required parameter: "bucketId"'); } @@ -188,17 +279,50 @@ export class Storage extends Service { } /** - * Update a file by its unique ID. Only users with write permissions have - * access to update this resource. + * Update a file by its unique ID. Only users with write permissions have access to update this resource. * - * @param {string} bucketId - * @param {string} fileId - * @param {string} name - * @param {string[]} permissions + * @param {string} params.bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} params.fileId - File unique ID. + * @param {string} params.name - Name of the file + * @param {string[]} params.permissions - An array of permission string. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). * @throws {AppwriteException} * @returns {Promise} */ - updateFile(bucketId: string, fileId: string, name?: string, permissions?: string[]): Promise { + updateFile(params: { bucketId: string, fileId: string, name?: string, permissions?: string[] }): Promise; + /** + * Update a file by its unique ID. Only users with write permissions have access to update this resource. + * + * @param {string} bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} fileId - File unique ID. + * @param {string} name - Name of the file + * @param {string[]} permissions - An array of permission string. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateFile(bucketId: string, fileId: string, name?: string, permissions?: string[]): Promise; + updateFile( + paramsOrFirst: { bucketId: string, fileId: string, name?: string, permissions?: string[] } | string, + ...rest: [(string)?, (string)?, (string[])?] + ): Promise { + let params: { bucketId: string, fileId: string, name?: string, permissions?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { bucketId: string, fileId: string, name?: string, permissions?: string[] }; + } else { + params = { + bucketId: paramsOrFirst as string, + fileId: rest[0] as string, + name: rest[1] as string, + permissions: rest[2] as string[] + }; + } + + const bucketId = params.bucketId; + const fileId = params.fileId; + const name = params.name; + const permissions = params.permissions; + if (typeof bucketId === 'undefined') { throw new AppwriteException('Missing required parameter: "bucketId"'); } @@ -225,15 +349,42 @@ export class Storage extends Service { } /** - * Delete a file by its unique ID. Only users with write permissions have - * access to delete this resource. + * Delete a file by its unique ID. Only users with write permissions have access to delete this resource. * - * @param {string} bucketId - * @param {string} fileId + * @param {string} params.bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} params.fileId - File ID. * @throws {AppwriteException} * @returns {Promise} */ - deleteFile(bucketId: string, fileId: string): Promise<{}> { + deleteFile(params: { bucketId: string, fileId: string }): Promise<{}>; + /** + * Delete a file by its unique ID. Only users with write permissions have access to delete this resource. + * + * @param {string} bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} fileId - File ID. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + deleteFile(bucketId: string, fileId: string): Promise<{}>; + deleteFile( + paramsOrFirst: { bucketId: string, fileId: string } | string, + ...rest: [(string)?] + ): Promise<{}> { + let params: { bucketId: string, fileId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { bucketId: string, fileId: string }; + } else { + params = { + bucketId: paramsOrFirst as string, + fileId: rest[0] as string + }; + } + + const bucketId = params.bucketId; + const fileId = params.fileId; + if (typeof bucketId === 'undefined') { throw new AppwriteException('Missing required parameter: "bucketId"'); } @@ -252,17 +403,46 @@ export class Storage extends Service { } /** - * Get a file content by its unique ID. The endpoint response return with a - * 'Content-Disposition: attachment' header that tells the browser to start - * downloading the file to user downloads directory. + * Get a file content by its unique ID. The endpoint response return with a 'Content-Disposition: attachment' header that tells the browser to start downloading the file to user downloads directory. * - * @param {string} bucketId - * @param {string} fileId - * @param {string} token + * @param {string} params.bucketId - Storage bucket ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} params.fileId - File ID. + * @param {string} params.token - File token for accessing this file. * @throws {AppwriteException} * @returns {ArrayBuffer} */ - getFileDownload(bucketId: string, fileId: string, token?: string): Promise { + getFileDownload(params: { bucketId: string, fileId: string, token?: string }): Promise; + /** + * Get a file content by its unique ID. The endpoint response return with a 'Content-Disposition: attachment' header that tells the browser to start downloading the file to user downloads directory. + * + * @param {string} bucketId - Storage bucket ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} fileId - File ID. + * @param {string} token - File token for accessing this file. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getFileDownload(bucketId: string, fileId: string, token?: string): Promise; + getFileDownload( + paramsOrFirst: { bucketId: string, fileId: string, token?: string } | string, + ...rest: [(string)?, (string)?] + ): Promise { + let params: { bucketId: string, fileId: string, token?: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { bucketId: string, fileId: string, token?: string }; + } else { + params = { + bucketId: paramsOrFirst as string, + fileId: rest[0] as string, + token: rest[1] as string + }; + } + + const bucketId = params.bucketId; + const fileId = params.fileId; + const token = params.token; + if (typeof bucketId === 'undefined') { throw new AppwriteException('Missing required parameter: "bucketId"'); } @@ -290,30 +470,90 @@ export class Storage extends Service { } /** - * Get a file preview image. Currently, this method supports preview for image - * files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - * and spreadsheets, will return the file icon image. You can also pass query - * string arguments for cutting and resizing your preview image. Preview is - * supported only for image files smaller than 10MB. + * Get a file preview image. Currently, this method supports preview for image files (jpg, png, and gif), other supported formats, like pdf, docs, slides, and spreadsheets, will return the file icon image. You can also pass query string arguments for cutting and resizing your preview image. Preview is supported only for image files smaller than 10MB. * - * @param {string} bucketId - * @param {string} fileId - * @param {number} width - * @param {number} height - * @param {ImageGravity} gravity - * @param {number} quality - * @param {number} borderWidth - * @param {string} borderColor - * @param {number} borderRadius - * @param {number} opacity - * @param {number} rotation - * @param {string} background - * @param {ImageFormat} output - * @param {string} token + * @param {string} params.bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} params.fileId - File ID + * @param {number} params.width - Resize preview image width, Pass an integer between 0 to 4000. + * @param {number} params.height - Resize preview image height, Pass an integer between 0 to 4000. + * @param {ImageGravity} params.gravity - Image crop gravity. Can be one of center,top-left,top,top-right,left,right,bottom-left,bottom,bottom-right + * @param {number} params.quality - Preview image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. + * @param {number} params.borderWidth - Preview image border in pixels. Pass an integer between 0 to 100. Defaults to 0. + * @param {string} params.borderColor - Preview image border color. Use a valid HEX color, no # is needed for prefix. + * @param {number} params.borderRadius - Preview image border radius in pixels. Pass an integer between 0 to 4000. + * @param {number} params.opacity - Preview image opacity. Only works with images having an alpha channel (like png). Pass a number between 0 to 1. + * @param {number} params.rotation - Preview image rotation in degrees. Pass an integer between -360 and 360. + * @param {string} params.background - Preview image background color. Only works with transparent images (png). Use a valid HEX color, no # is needed for prefix. + * @param {ImageFormat} params.output - Output format type (jpeg, jpg, png, gif and webp). + * @param {string} params.token - File token for accessing this file. * @throws {AppwriteException} * @returns {ArrayBuffer} */ - getFilePreview(bucketId: string, fileId: string, width?: number, height?: number, gravity?: ImageGravity, quality?: number, borderWidth?: number, borderColor?: string, borderRadius?: number, opacity?: number, rotation?: number, background?: string, output?: ImageFormat, token?: string): Promise { + getFilePreview(params: { bucketId: string, fileId: string, width?: number, height?: number, gravity?: ImageGravity, quality?: number, borderWidth?: number, borderColor?: string, borderRadius?: number, opacity?: number, rotation?: number, background?: string, output?: ImageFormat, token?: string }): Promise; + /** + * Get a file preview image. Currently, this method supports preview for image files (jpg, png, and gif), other supported formats, like pdf, docs, slides, and spreadsheets, will return the file icon image. You can also pass query string arguments for cutting and resizing your preview image. Preview is supported only for image files smaller than 10MB. + * + * @param {string} bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} fileId - File ID + * @param {number} width - Resize preview image width, Pass an integer between 0 to 4000. + * @param {number} height - Resize preview image height, Pass an integer between 0 to 4000. + * @param {ImageGravity} gravity - Image crop gravity. Can be one of center,top-left,top,top-right,left,right,bottom-left,bottom,bottom-right + * @param {number} quality - Preview image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality. + * @param {number} borderWidth - Preview image border in pixels. Pass an integer between 0 to 100. Defaults to 0. + * @param {string} borderColor - Preview image border color. Use a valid HEX color, no # is needed for prefix. + * @param {number} borderRadius - Preview image border radius in pixels. Pass an integer between 0 to 4000. + * @param {number} opacity - Preview image opacity. Only works with images having an alpha channel (like png). Pass a number between 0 to 1. + * @param {number} rotation - Preview image rotation in degrees. Pass an integer between -360 and 360. + * @param {string} background - Preview image background color. Only works with transparent images (png). Use a valid HEX color, no # is needed for prefix. + * @param {ImageFormat} output - Output format type (jpeg, jpg, png, gif and webp). + * @param {string} token - File token for accessing this file. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getFilePreview(bucketId: string, fileId: string, width?: number, height?: number, gravity?: ImageGravity, quality?: number, borderWidth?: number, borderColor?: string, borderRadius?: number, opacity?: number, rotation?: number, background?: string, output?: ImageFormat, token?: string): Promise; + getFilePreview( + paramsOrFirst: { bucketId: string, fileId: string, width?: number, height?: number, gravity?: ImageGravity, quality?: number, borderWidth?: number, borderColor?: string, borderRadius?: number, opacity?: number, rotation?: number, background?: string, output?: ImageFormat, token?: string } | string, + ...rest: [(string)?, (number)?, (number)?, (ImageGravity)?, (number)?, (number)?, (string)?, (number)?, (number)?, (number)?, (string)?, (ImageFormat)?, (string)?] + ): Promise { + let params: { bucketId: string, fileId: string, width?: number, height?: number, gravity?: ImageGravity, quality?: number, borderWidth?: number, borderColor?: string, borderRadius?: number, opacity?: number, rotation?: number, background?: string, output?: ImageFormat, token?: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { bucketId: string, fileId: string, width?: number, height?: number, gravity?: ImageGravity, quality?: number, borderWidth?: number, borderColor?: string, borderRadius?: number, opacity?: number, rotation?: number, background?: string, output?: ImageFormat, token?: string }; + } else { + params = { + bucketId: paramsOrFirst as string, + fileId: rest[0] as string, + width: rest[1] as number, + height: rest[2] as number, + gravity: rest[3] as ImageGravity, + quality: rest[4] as number, + borderWidth: rest[5] as number, + borderColor: rest[6] as string, + borderRadius: rest[7] as number, + opacity: rest[8] as number, + rotation: rest[9] as number, + background: rest[10] as string, + output: rest[11] as ImageFormat, + token: rest[12] as string + }; + } + + const bucketId = params.bucketId; + const fileId = params.fileId; + const width = params.width; + const height = params.height; + const gravity = params.gravity; + const quality = params.quality; + const borderWidth = params.borderWidth; + const borderColor = params.borderColor; + const borderRadius = params.borderRadius; + const opacity = params.opacity; + const rotation = params.rotation; + const background = params.background; + const output = params.output; + const token = params.token; + if (typeof bucketId === 'undefined') { throw new AppwriteException('Missing required parameter: "bucketId"'); } @@ -385,17 +625,46 @@ export class Storage extends Service { } /** - * Get a file content by its unique ID. This endpoint is similar to the - * download method but returns with no 'Content-Disposition: attachment' - * header. + * Get a file content by its unique ID. This endpoint is similar to the download method but returns with no 'Content-Disposition: attachment' header. * - * @param {string} bucketId - * @param {string} fileId - * @param {string} token + * @param {string} params.bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} params.fileId - File ID. + * @param {string} params.token - File token for accessing this file. * @throws {AppwriteException} * @returns {ArrayBuffer} */ - getFileView(bucketId: string, fileId: string, token?: string): Promise { + getFileView(params: { bucketId: string, fileId: string, token?: string }): Promise; + /** + * Get a file content by its unique ID. This endpoint is similar to the download method but returns with no 'Content-Disposition: attachment' header. + * + * @param {string} bucketId - Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](https://appwrite.io/docs/server/storage#createBucket). + * @param {string} fileId - File ID. + * @param {string} token - File token for accessing this file. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getFileView(bucketId: string, fileId: string, token?: string): Promise; + getFileView( + paramsOrFirst: { bucketId: string, fileId: string, token?: string } | string, + ...rest: [(string)?, (string)?] + ): Promise { + let params: { bucketId: string, fileId: string, token?: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { bucketId: string, fileId: string, token?: string }; + } else { + params = { + bucketId: paramsOrFirst as string, + fileId: rest[0] as string, + token: rest[1] as string + }; + } + + const bucketId = params.bucketId; + const fileId = params.fileId; + const token = params.token; + if (typeof bucketId === 'undefined') { throw new AppwriteException('Missing required parameter: "bucketId"'); } diff --git a/src/services/tables-db.ts b/src/services/tables-db.ts new file mode 100644 index 00000000..b3b12b9e --- /dev/null +++ b/src/services/tables-db.ts @@ -0,0 +1,621 @@ +import { Service } from '../service'; +import { AppwriteException, Client } from '../client'; +import type { Models } from '../models'; +import type { UploadProgress, Payload } from '../client'; +import * as FileSystem from 'expo-file-system'; +import { Platform } from 'react-native'; + + +export class TablesDB extends Service { + + constructor(client: Client) + { + super(client); + } + + /** + * Get a list of all the user's rows in a given table. You can use the query params to filter your results. + * + * @param {string} params.databaseId - Database ID. + * @param {string} params.tableId - Table ID. You can create a new table using the TableDB service [server integration](https://appwrite.io/docs/server/tablesdbdb#tablesdbCreate). + * @param {string[]} params.queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @throws {AppwriteException} + * @returns {Promise} + */ + listRows(params: { databaseId: string, tableId: string, queries?: string[] }): Promise>; + /** + * Get a list of all the user's rows in a given table. You can use the query params to filter your results. + * + * @param {string} databaseId - Database ID. + * @param {string} tableId - Table ID. You can create a new table using the TableDB service [server integration](https://appwrite.io/docs/server/tablesdbdb#tablesdbCreate). + * @param {string[]} queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + listRows(databaseId: string, tableId: string, queries?: string[]): Promise>; + listRows( + paramsOrFirst: { databaseId: string, tableId: string, queries?: string[] } | string, + ...rest: [(string)?, (string[])?] + ): Promise> { + let params: { databaseId: string, tableId: string, queries?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, tableId: string, queries?: string[] }; + } else { + params = { + databaseId: paramsOrFirst as string, + tableId: rest[0] as string, + queries: rest[1] as string[] + }; + } + + const databaseId = params.databaseId; + const tableId = params.tableId; + const queries = params.queries; + + if (typeof databaseId === 'undefined') { + throw new AppwriteException('Missing required parameter: "databaseId"'); + } + + if (typeof tableId === 'undefined') { + throw new AppwriteException('Missing required parameter: "tableId"'); + } + + const apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); + const payload: Payload = {}; + + if (typeof queries !== 'undefined') { + payload['queries'] = queries; + } + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('get', uri, { + }, payload); + } + + /** + * Create a new Row. Before using this route, you should create a new table resource using either a [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreateTable) API or directly from your database console. + * + * @param {string} params.databaseId - Database ID. + * @param {string} params.tableId - Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreate). Make sure to define columns before creating rows. + * @param {string} params.rowId - Row ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {Row extends Models.DefaultRow ? Partial & Record : Partial & Omit} params.data - Row data as JSON object. + * @param {string[]} params.permissions - An array of permissions strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @throws {AppwriteException} + * @returns {Promise} + */ + createRow(params: { databaseId: string, tableId: string, rowId: string, data: Row extends Models.DefaultRow ? Partial & Record : Partial & Omit, permissions?: string[] }): Promise; + /** + * Create a new Row. Before using this route, you should create a new table resource using either a [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreateTable) API or directly from your database console. + * + * @param {string} databaseId - Database ID. + * @param {string} tableId - Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreate). Make sure to define columns before creating rows. + * @param {string} rowId - Row ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {Row extends Models.DefaultRow ? Partial & Record : Partial & Omit} data - Row data as JSON object. + * @param {string[]} permissions - An array of permissions strings. By default, only the current user is granted all permissions. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createRow(databaseId: string, tableId: string, rowId: string, data: Row extends Models.DefaultRow ? Partial & Record : Partial & Omit, permissions?: string[]): Promise; + createRow( + paramsOrFirst: { databaseId: string, tableId: string, rowId: string, data: Row extends Models.DefaultRow ? Partial & Record : Partial & Omit, permissions?: string[] } | string, + ...rest: [(string)?, (string)?, (Row extends Models.DefaultRow ? Partial & Record : Partial & Omit)?, (string[])?] + ): Promise { + let params: { databaseId: string, tableId: string, rowId: string, data: Row extends Models.DefaultRow ? Partial & Record : Partial & Omit, permissions?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, tableId: string, rowId: string, data: Row extends Models.DefaultRow ? Partial & Record : Partial & Omit, permissions?: string[] }; + } else { + params = { + databaseId: paramsOrFirst as string, + tableId: rest[0] as string, + rowId: rest[1] as string, + data: rest[2] as Row extends Models.DefaultRow ? Partial & Record : Partial & Omit, + permissions: rest[3] as string[] + }; + } + + const databaseId = params.databaseId; + const tableId = params.tableId; + const rowId = params.rowId; + const data = params.data; + const permissions = params.permissions; + + if (typeof databaseId === 'undefined') { + throw new AppwriteException('Missing required parameter: "databaseId"'); + } + + if (typeof tableId === 'undefined') { + throw new AppwriteException('Missing required parameter: "tableId"'); + } + + if (typeof rowId === 'undefined') { + throw new AppwriteException('Missing required parameter: "rowId"'); + } + + if (typeof data === 'undefined') { + throw new AppwriteException('Missing required parameter: "data"'); + } + + const apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); + const payload: Payload = {}; + + if (typeof rowId !== 'undefined') { + payload['rowId'] = rowId; + } + + if (typeof data !== 'undefined') { + payload['data'] = data; + } + + if (typeof permissions !== 'undefined') { + payload['permissions'] = permissions; + } + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('post', uri, { + 'content-type': 'application/json', + }, payload); + } + + /** + * Get a row by its unique ID. This endpoint response returns a JSON object with the row data. + * + * @param {string} params.databaseId - Database ID. + * @param {string} params.tableId - Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreate). + * @param {string} params.rowId - Row ID. + * @param {string[]} params.queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @throws {AppwriteException} + * @returns {Promise} + */ + getRow(params: { databaseId: string, tableId: string, rowId: string, queries?: string[] }): Promise; + /** + * Get a row by its unique ID. This endpoint response returns a JSON object with the row data. + * + * @param {string} databaseId - Database ID. + * @param {string} tableId - Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreate). + * @param {string} rowId - Row ID. + * @param {string[]} queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getRow(databaseId: string, tableId: string, rowId: string, queries?: string[]): Promise; + getRow( + paramsOrFirst: { databaseId: string, tableId: string, rowId: string, queries?: string[] } | string, + ...rest: [(string)?, (string)?, (string[])?] + ): Promise { + let params: { databaseId: string, tableId: string, rowId: string, queries?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, tableId: string, rowId: string, queries?: string[] }; + } else { + params = { + databaseId: paramsOrFirst as string, + tableId: rest[0] as string, + rowId: rest[1] as string, + queries: rest[2] as string[] + }; + } + + const databaseId = params.databaseId; + const tableId = params.tableId; + const rowId = params.rowId; + const queries = params.queries; + + if (typeof databaseId === 'undefined') { + throw new AppwriteException('Missing required parameter: "databaseId"'); + } + + if (typeof tableId === 'undefined') { + throw new AppwriteException('Missing required parameter: "tableId"'); + } + + if (typeof rowId === 'undefined') { + throw new AppwriteException('Missing required parameter: "rowId"'); + } + + const apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId); + const payload: Payload = {}; + + if (typeof queries !== 'undefined') { + payload['queries'] = queries; + } + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('get', uri, { + }, payload); + } + + /** + * Create or update a Row. Before using this route, you should create a new table resource using either a [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreateTable) API or directly from your database console. + * + * @param {string} params.databaseId - Database ID. + * @param {string} params.tableId - Table ID. + * @param {string} params.rowId - Row ID. + * @param {Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>} params.data - Row data as JSON object. Include all required columns of the row to be created or updated. + * @param {string[]} params.permissions - An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @throws {AppwriteException} + * @returns {Promise} + */ + upsertRow(params: { databaseId: string, tableId: string, rowId: string, data?: Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>, permissions?: string[] }): Promise; + /** + * Create or update a Row. Before using this route, you should create a new table resource using either a [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreateTable) API or directly from your database console. + * + * @param {string} databaseId - Database ID. + * @param {string} tableId - Table ID. + * @param {string} rowId - Row ID. + * @param {Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>} data - Row data as JSON object. Include all required columns of the row to be created or updated. + * @param {string[]} permissions - An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + upsertRow(databaseId: string, tableId: string, rowId: string, data?: Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>, permissions?: string[]): Promise; + upsertRow( + paramsOrFirst: { databaseId: string, tableId: string, rowId: string, data?: Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>, permissions?: string[] } | string, + ...rest: [(string)?, (string)?, (Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>)?, (string[])?] + ): Promise { + let params: { databaseId: string, tableId: string, rowId: string, data?: Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>, permissions?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, tableId: string, rowId: string, data?: Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>, permissions?: string[] }; + } else { + params = { + databaseId: paramsOrFirst as string, + tableId: rest[0] as string, + rowId: rest[1] as string, + data: rest[2] as Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>, + permissions: rest[3] as string[] + }; + } + + const databaseId = params.databaseId; + const tableId = params.tableId; + const rowId = params.rowId; + const data = params.data; + const permissions = params.permissions; + + if (typeof databaseId === 'undefined') { + throw new AppwriteException('Missing required parameter: "databaseId"'); + } + + if (typeof tableId === 'undefined') { + throw new AppwriteException('Missing required parameter: "tableId"'); + } + + if (typeof rowId === 'undefined') { + throw new AppwriteException('Missing required parameter: "rowId"'); + } + + const apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId); + const payload: Payload = {}; + + if (typeof data !== 'undefined') { + payload['data'] = data; + } + + if (typeof permissions !== 'undefined') { + payload['permissions'] = permissions; + } + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('put', uri, { + 'content-type': 'application/json', + }, payload); + } + + /** + * Update a row by its unique ID. Using the patch method you can pass only specific fields that will get updated. + * + * @param {string} params.databaseId - Database ID. + * @param {string} params.tableId - Table ID. + * @param {string} params.rowId - Row ID. + * @param {Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>} params.data - Row data as JSON object. Include only columns and value pairs to be updated. + * @param {string[]} params.permissions - An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @throws {AppwriteException} + * @returns {Promise} + */ + updateRow(params: { databaseId: string, tableId: string, rowId: string, data?: Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>, permissions?: string[] }): Promise; + /** + * Update a row by its unique ID. Using the patch method you can pass only specific fields that will get updated. + * + * @param {string} databaseId - Database ID. + * @param {string} tableId - Table ID. + * @param {string} rowId - Row ID. + * @param {Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>} data - Row data as JSON object. Include only columns and value pairs to be updated. + * @param {string[]} permissions - An array of permissions strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions). + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateRow(databaseId: string, tableId: string, rowId: string, data?: Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>, permissions?: string[]): Promise; + updateRow( + paramsOrFirst: { databaseId: string, tableId: string, rowId: string, data?: Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>, permissions?: string[] } | string, + ...rest: [(string)?, (string)?, (Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>)?, (string[])?] + ): Promise { + let params: { databaseId: string, tableId: string, rowId: string, data?: Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>, permissions?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, tableId: string, rowId: string, data?: Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>, permissions?: string[] }; + } else { + params = { + databaseId: paramsOrFirst as string, + tableId: rest[0] as string, + rowId: rest[1] as string, + data: rest[2] as Row extends Models.DefaultRow ? Partial & Record : Partial & Partial>, + permissions: rest[3] as string[] + }; + } + + const databaseId = params.databaseId; + const tableId = params.tableId; + const rowId = params.rowId; + const data = params.data; + const permissions = params.permissions; + + if (typeof databaseId === 'undefined') { + throw new AppwriteException('Missing required parameter: "databaseId"'); + } + + if (typeof tableId === 'undefined') { + throw new AppwriteException('Missing required parameter: "tableId"'); + } + + if (typeof rowId === 'undefined') { + throw new AppwriteException('Missing required parameter: "rowId"'); + } + + const apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId); + const payload: Payload = {}; + + if (typeof data !== 'undefined') { + payload['data'] = data; + } + + if (typeof permissions !== 'undefined') { + payload['permissions'] = permissions; + } + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('patch', uri, { + 'content-type': 'application/json', + }, payload); + } + + /** + * Delete a row by its unique ID. + * + * @param {string} params.databaseId - Database ID. + * @param {string} params.tableId - Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreate). + * @param {string} params.rowId - Row ID. + * @throws {AppwriteException} + * @returns {Promise} + */ + deleteRow(params: { databaseId: string, tableId: string, rowId: string }): Promise<{}>; + /** + * Delete a row by its unique ID. + * + * @param {string} databaseId - Database ID. + * @param {string} tableId - Table ID. You can create a new table using the Database service [server integration](https://appwrite.io/docs/server/tablesdb#tablesDBCreate). + * @param {string} rowId - Row ID. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + deleteRow(databaseId: string, tableId: string, rowId: string): Promise<{}>; + deleteRow( + paramsOrFirst: { databaseId: string, tableId: string, rowId: string } | string, + ...rest: [(string)?, (string)?] + ): Promise<{}> { + let params: { databaseId: string, tableId: string, rowId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, tableId: string, rowId: string }; + } else { + params = { + databaseId: paramsOrFirst as string, + tableId: rest[0] as string, + rowId: rest[1] as string + }; + } + + const databaseId = params.databaseId; + const tableId = params.tableId; + const rowId = params.rowId; + + if (typeof databaseId === 'undefined') { + throw new AppwriteException('Missing required parameter: "databaseId"'); + } + + if (typeof tableId === 'undefined') { + throw new AppwriteException('Missing required parameter: "tableId"'); + } + + if (typeof rowId === 'undefined') { + throw new AppwriteException('Missing required parameter: "rowId"'); + } + + const apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId); + const payload: Payload = {}; + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('delete', uri, { + 'content-type': 'application/json', + }, payload); + } + + /** + * Decrement a specific column of a row by a given value. + * + * @param {string} params.databaseId - Database ID. + * @param {string} params.tableId - Table ID. + * @param {string} params.rowId - Row ID. + * @param {string} params.column - Column key. + * @param {number} params.value - Value to increment the column by. The value must be a number. + * @param {number} params.min - Minimum value for the column. If the current value is lesser than this value, an exception will be thrown. + * @throws {AppwriteException} + * @returns {Promise} + */ + decrementRowColumn(params: { databaseId: string, tableId: string, rowId: string, column: string, value?: number, min?: number }): Promise; + /** + * Decrement a specific column of a row by a given value. + * + * @param {string} databaseId - Database ID. + * @param {string} tableId - Table ID. + * @param {string} rowId - Row ID. + * @param {string} column - Column key. + * @param {number} value - Value to increment the column by. The value must be a number. + * @param {number} min - Minimum value for the column. If the current value is lesser than this value, an exception will be thrown. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + decrementRowColumn(databaseId: string, tableId: string, rowId: string, column: string, value?: number, min?: number): Promise; + decrementRowColumn( + paramsOrFirst: { databaseId: string, tableId: string, rowId: string, column: string, value?: number, min?: number } | string, + ...rest: [(string)?, (string)?, (string)?, (number)?, (number)?] + ): Promise { + let params: { databaseId: string, tableId: string, rowId: string, column: string, value?: number, min?: number }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, tableId: string, rowId: string, column: string, value?: number, min?: number }; + } else { + params = { + databaseId: paramsOrFirst as string, + tableId: rest[0] as string, + rowId: rest[1] as string, + column: rest[2] as string, + value: rest[3] as number, + min: rest[4] as number + }; + } + + const databaseId = params.databaseId; + const tableId = params.tableId; + const rowId = params.rowId; + const column = params.column; + const value = params.value; + const min = params.min; + + if (typeof databaseId === 'undefined') { + throw new AppwriteException('Missing required parameter: "databaseId"'); + } + + if (typeof tableId === 'undefined') { + throw new AppwriteException('Missing required parameter: "tableId"'); + } + + if (typeof rowId === 'undefined') { + throw new AppwriteException('Missing required parameter: "rowId"'); + } + + if (typeof column === 'undefined') { + throw new AppwriteException('Missing required parameter: "column"'); + } + + const apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/decrement'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId).replace('{column}', column); + const payload: Payload = {}; + + if (typeof value !== 'undefined') { + payload['value'] = value; + } + + if (typeof min !== 'undefined') { + payload['min'] = min; + } + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('patch', uri, { + 'content-type': 'application/json', + }, payload); + } + + /** + * Increment a specific column of a row by a given value. + * + * @param {string} params.databaseId - Database ID. + * @param {string} params.tableId - Table ID. + * @param {string} params.rowId - Row ID. + * @param {string} params.column - Column key. + * @param {number} params.value - Value to increment the column by. The value must be a number. + * @param {number} params.max - Maximum value for the column. If the current value is greater than this value, an error will be thrown. + * @throws {AppwriteException} + * @returns {Promise} + */ + incrementRowColumn(params: { databaseId: string, tableId: string, rowId: string, column: string, value?: number, max?: number }): Promise; + /** + * Increment a specific column of a row by a given value. + * + * @param {string} databaseId - Database ID. + * @param {string} tableId - Table ID. + * @param {string} rowId - Row ID. + * @param {string} column - Column key. + * @param {number} value - Value to increment the column by. The value must be a number. + * @param {number} max - Maximum value for the column. If the current value is greater than this value, an error will be thrown. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + incrementRowColumn(databaseId: string, tableId: string, rowId: string, column: string, value?: number, max?: number): Promise; + incrementRowColumn( + paramsOrFirst: { databaseId: string, tableId: string, rowId: string, column: string, value?: number, max?: number } | string, + ...rest: [(string)?, (string)?, (string)?, (number)?, (number)?] + ): Promise { + let params: { databaseId: string, tableId: string, rowId: string, column: string, value?: number, max?: number }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { databaseId: string, tableId: string, rowId: string, column: string, value?: number, max?: number }; + } else { + params = { + databaseId: paramsOrFirst as string, + tableId: rest[0] as string, + rowId: rest[1] as string, + column: rest[2] as string, + value: rest[3] as number, + max: rest[4] as number + }; + } + + const databaseId = params.databaseId; + const tableId = params.tableId; + const rowId = params.rowId; + const column = params.column; + const value = params.value; + const max = params.max; + + if (typeof databaseId === 'undefined') { + throw new AppwriteException('Missing required parameter: "databaseId"'); + } + + if (typeof tableId === 'undefined') { + throw new AppwriteException('Missing required parameter: "tableId"'); + } + + if (typeof rowId === 'undefined') { + throw new AppwriteException('Missing required parameter: "rowId"'); + } + + if (typeof column === 'undefined') { + throw new AppwriteException('Missing required parameter: "column"'); + } + + const apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows/{rowId}/{column}/increment'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{rowId}', rowId).replace('{column}', column); + const payload: Payload = {}; + + if (typeof value !== 'undefined') { + payload['value'] = value; + } + + if (typeof max !== 'undefined') { + payload['max'] = max; + } + + const uri = new URL(this.client.config.endpoint + apiPath); + return this.client.call('patch', uri, { + 'content-type': 'application/json', + }, payload); + } +}; diff --git a/src/services/teams.ts b/src/services/teams.ts index d45f7e93..b15f29ae 100644 --- a/src/services/teams.ts +++ b/src/services/teams.ts @@ -14,15 +14,42 @@ export class Teams extends Service { } /** - * Get a list of all the teams in which the current user is a member. You can - * use the parameters to filter your results. + * Get a list of all the teams in which the current user is a member. You can use the parameters to filter your results. * - * @param {string[]} queries - * @param {string} search + * @param {string[]} params.queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, total, billingPlan + * @param {string} params.search - Search term to filter your list results. Max length: 256 chars. * @throws {AppwriteException} * @returns {Promise} */ - list(queries?: string[], search?: string): Promise> { + list(params?: { queries?: string[], search?: string }): Promise>; + /** + * Get a list of all the teams in which the current user is a member. You can use the parameters to filter your results. + * + * @param {string[]} queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: name, total, billingPlan + * @param {string} search - Search term to filter your list results. Max length: 256 chars. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + list(queries?: string[], search?: string): Promise>; + list( + paramsOrFirst?: { queries?: string[], search?: string } | string[], + ...rest: [(string)?] + ): Promise> { + let params: { queries?: string[], search?: string }; + + if (!paramsOrFirst || (paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { queries?: string[], search?: string }; + } else { + params = { + queries: paramsOrFirst as string[], + search: rest[0] as string + }; + } + + const queries = params.queries; + const search = params.search; + const apiPath = '/teams'; const payload: Payload = {}; @@ -40,17 +67,46 @@ export class Teams extends Service { } /** - * Create a new team. The user who creates the team will automatically be - * assigned as the owner of the team. Only the users with the owner role can - * invite new members, add new owners and delete or update the team. + * Create a new team. The user who creates the team will automatically be assigned as the owner of the team. Only the users with the owner role can invite new members, add new owners and delete or update the team. * - * @param {string} teamId - * @param {string} name - * @param {string[]} roles + * @param {string} params.teamId - Team ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {string} params.name - Team name. Max length: 128 chars. + * @param {string[]} params.roles - Array of strings. Use this param to set the roles in the team for the user who created it. The default role is **owner**. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. * @throws {AppwriteException} * @returns {Promise} */ - create(teamId: string, name: string, roles?: string[]): Promise> { + create(params: { teamId: string, name: string, roles?: string[] }): Promise>; + /** + * Create a new team. The user who creates the team will automatically be assigned as the owner of the team. Only the users with the owner role can invite new members, add new owners and delete or update the team. + * + * @param {string} teamId - Team ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars. + * @param {string} name - Team name. Max length: 128 chars. + * @param {string[]} roles - Array of strings. Use this param to set the roles in the team for the user who created it. The default role is **owner**. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + create(teamId: string, name: string, roles?: string[]): Promise>; + create( + paramsOrFirst: { teamId: string, name: string, roles?: string[] } | string, + ...rest: [(string)?, (string[])?] + ): Promise> { + let params: { teamId: string, name: string, roles?: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { teamId: string, name: string, roles?: string[] }; + } else { + params = { + teamId: paramsOrFirst as string, + name: rest[0] as string, + roles: rest[1] as string[] + }; + } + + const teamId = params.teamId; + const name = params.name; + const roles = params.roles; + if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } @@ -83,11 +139,35 @@ export class Teams extends Service { /** * Get a team by its ID. All team members have read access for this resource. * - * @param {string} teamId + * @param {string} params.teamId - Team ID. * @throws {AppwriteException} * @returns {Promise} */ - get(teamId: string): Promise> { + get(params: { teamId: string }): Promise>; + /** + * Get a team by its ID. All team members have read access for this resource. + * + * @param {string} teamId - Team ID. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + get(teamId: string): Promise>; + get( + paramsOrFirst: { teamId: string } | string + ): Promise> { + let params: { teamId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { teamId: string }; + } else { + params = { + teamId: paramsOrFirst as string + }; + } + + const teamId = params.teamId; + if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } @@ -103,12 +183,40 @@ export class Teams extends Service { /** * Update the team's name by its unique ID. * - * @param {string} teamId - * @param {string} name + * @param {string} params.teamId - Team ID. + * @param {string} params.name - New team name. Max length: 128 chars. * @throws {AppwriteException} * @returns {Promise} */ - updateName(teamId: string, name: string): Promise> { + updateName(params: { teamId: string, name: string }): Promise>; + /** + * Update the team's name by its unique ID. + * + * @param {string} teamId - Team ID. + * @param {string} name - New team name. Max length: 128 chars. + * @throws {AppwriteException} + * @returns {Promise>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateName(teamId: string, name: string): Promise>; + updateName( + paramsOrFirst: { teamId: string, name: string } | string, + ...rest: [(string)?] + ): Promise> { + let params: { teamId: string, name: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { teamId: string, name: string }; + } else { + params = { + teamId: paramsOrFirst as string, + name: rest[0] as string + }; + } + + const teamId = params.teamId; + const name = params.name; + if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } @@ -131,14 +239,37 @@ export class Teams extends Service { } /** - * Delete a team using its ID. Only team members with the owner role can - * delete the team. + * Delete a team using its ID. Only team members with the owner role can delete the team. * - * @param {string} teamId + * @param {string} params.teamId - Team ID. * @throws {AppwriteException} * @returns {Promise} */ - delete(teamId: string): Promise<{}> { + delete(params: { teamId: string }): Promise<{}>; + /** + * Delete a team using its ID. Only team members with the owner role can delete the team. + * + * @param {string} teamId - Team ID. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + delete(teamId: string): Promise<{}>; + delete( + paramsOrFirst: { teamId: string } | string + ): Promise<{}> { + let params: { teamId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { teamId: string }; + } else { + params = { + teamId: paramsOrFirst as string + }; + } + + const teamId = params.teamId; + if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } @@ -153,17 +284,46 @@ export class Teams extends Service { } /** - * Use this endpoint to list a team's members using the team's ID. All team - * members have read access to this endpoint. Hide sensitive attributes from - * the response by toggling membership privacy in the Console. + * Use this endpoint to list a team's members using the team's ID. All team members have read access to this endpoint. Hide sensitive attributes from the response by toggling membership privacy in the Console. * - * @param {string} teamId - * @param {string[]} queries - * @param {string} search + * @param {string} params.teamId - Team ID. + * @param {string[]} params.queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, teamId, invited, joined, confirm, roles + * @param {string} params.search - Search term to filter your list results. Max length: 256 chars. * @throws {AppwriteException} * @returns {Promise} */ - listMemberships(teamId: string, queries?: string[], search?: string): Promise { + listMemberships(params: { teamId: string, queries?: string[], search?: string }): Promise; + /** + * Use this endpoint to list a team's members using the team's ID. All team members have read access to this endpoint. Hide sensitive attributes from the response by toggling membership privacy in the Console. + * + * @param {string} teamId - Team ID. + * @param {string[]} queries - Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of 100 queries are allowed, each 4096 characters long. You may filter on the following attributes: userId, teamId, invited, joined, confirm, roles + * @param {string} search - Search term to filter your list results. Max length: 256 chars. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + listMemberships(teamId: string, queries?: string[], search?: string): Promise; + listMemberships( + paramsOrFirst: { teamId: string, queries?: string[], search?: string } | string, + ...rest: [(string[])?, (string)?] + ): Promise { + let params: { teamId: string, queries?: string[], search?: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { teamId: string, queries?: string[], search?: string }; + } else { + params = { + teamId: paramsOrFirst as string, + queries: rest[0] as string[], + search: rest[1] as string + }; + } + + const teamId = params.teamId; + const queries = params.queries; + const search = params.search; + if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } @@ -185,39 +345,76 @@ export class Teams extends Service { } /** - * Invite a new member to join your team. Provide an ID for existing users, or - * invite unregistered users using an email or phone number. If initiated from - * a Client SDK, Appwrite will send an email or sms with a link to join the - * team to the invited user, and an account will be created for them if one - * doesn't exist. If initiated from a Server SDK, the new member will be added - * automatically to the team. + * Invite a new member to join your team. Provide an ID for existing users, or invite unregistered users using an email or phone number. If initiated from a Client SDK, Appwrite will send an email or sms with a link to join the team to the invited user, and an account will be created for them if one doesn't exist. If initiated from a Server SDK, the new member will be added automatically to the team. * - * You only need to provide one of a user ID, email, or phone number. Appwrite - * will prioritize accepting the user ID > email > phone number if you provide - * more than one of these parameters. + * You only need to provide one of a user ID, email, or phone number. Appwrite will prioritize accepting the user ID > email > phone number if you provide more than one of these parameters. * - * Use the `url` parameter to redirect the user from the invitation email to - * your app. After the user is redirected, use the [Update Team Membership - * Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) - * endpoint to allow the user to accept the invitation to the team. + * Use the `url` parameter to redirect the user from the invitation email to your app. After the user is redirected, use the [Update Team Membership Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) endpoint to allow the user to accept the invitation to the team. * - * Please note that to avoid a [Redirect - * Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) - * Appwrite will accept the only redirect URLs under the domains you have - * added as a platform on the Appwrite Console. + * Please note that to avoid a [Redirect Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) Appwrite will accept the only redirect URLs under the domains you have added as a platform on the Appwrite Console. * * - * @param {string} teamId - * @param {string[]} roles - * @param {string} email - * @param {string} userId - * @param {string} phone - * @param {string} url - * @param {string} name + * @param {string} params.teamId - Team ID. + * @param {string[]} params.roles - Array of strings. Use this param to set the user roles in the team. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. + * @param {string} params.email - Email of the new team member. + * @param {string} params.userId - ID of the user to be added to a team. + * @param {string} params.phone - Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. + * @param {string} params.url - URL to redirect the user back to your app from the invitation email. This parameter is not required when an API key is supplied. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param {string} params.name - Name of the new team member. Max length: 128 chars. * @throws {AppwriteException} * @returns {Promise} */ - createMembership(teamId: string, roles: string[], email?: string, userId?: string, phone?: string, url?: string, name?: string): Promise { + createMembership(params: { teamId: string, roles: string[], email?: string, userId?: string, phone?: string, url?: string, name?: string }): Promise; + /** + * Invite a new member to join your team. Provide an ID for existing users, or invite unregistered users using an email or phone number. If initiated from a Client SDK, Appwrite will send an email or sms with a link to join the team to the invited user, and an account will be created for them if one doesn't exist. If initiated from a Server SDK, the new member will be added automatically to the team. + * + * You only need to provide one of a user ID, email, or phone number. Appwrite will prioritize accepting the user ID > email > phone number if you provide more than one of these parameters. + * + * Use the `url` parameter to redirect the user from the invitation email to your app. After the user is redirected, use the [Update Team Membership Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) endpoint to allow the user to accept the invitation to the team. + * + * Please note that to avoid a [Redirect Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) Appwrite will accept the only redirect URLs under the domains you have added as a platform on the Appwrite Console. + * + * + * @param {string} teamId - Team ID. + * @param {string[]} roles - Array of strings. Use this param to set the user roles in the team. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. + * @param {string} email - Email of the new team member. + * @param {string} userId - ID of the user to be added to a team. + * @param {string} phone - Phone number. Format this number with a leading '+' and a country code, e.g., +16175551212. + * @param {string} url - URL to redirect the user back to your app from the invitation email. This parameter is not required when an API key is supplied. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API. + * @param {string} name - Name of the new team member. Max length: 128 chars. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + createMembership(teamId: string, roles: string[], email?: string, userId?: string, phone?: string, url?: string, name?: string): Promise; + createMembership( + paramsOrFirst: { teamId: string, roles: string[], email?: string, userId?: string, phone?: string, url?: string, name?: string } | string, + ...rest: [(string[])?, (string)?, (string)?, (string)?, (string)?, (string)?] + ): Promise { + let params: { teamId: string, roles: string[], email?: string, userId?: string, phone?: string, url?: string, name?: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { teamId: string, roles: string[], email?: string, userId?: string, phone?: string, url?: string, name?: string }; + } else { + params = { + teamId: paramsOrFirst as string, + roles: rest[0] as string[], + email: rest[1] as string, + userId: rest[2] as string, + phone: rest[3] as string, + url: rest[4] as string, + name: rest[5] as string + }; + } + + const teamId = params.teamId; + const roles = params.roles; + const email = params.email; + const userId = params.userId; + const phone = params.phone; + const url = params.url; + const name = params.name; + if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } @@ -260,16 +457,42 @@ export class Teams extends Service { } /** - * Get a team member by the membership unique id. All team members have read - * access for this resource. Hide sensitive attributes from the response by - * toggling membership privacy in the Console. + * Get a team member by the membership unique id. All team members have read access for this resource. Hide sensitive attributes from the response by toggling membership privacy in the Console. * - * @param {string} teamId - * @param {string} membershipId + * @param {string} params.teamId - Team ID. + * @param {string} params.membershipId - Membership ID. * @throws {AppwriteException} * @returns {Promise} */ - getMembership(teamId: string, membershipId: string): Promise { + getMembership(params: { teamId: string, membershipId: string }): Promise; + /** + * Get a team member by the membership unique id. All team members have read access for this resource. Hide sensitive attributes from the response by toggling membership privacy in the Console. + * + * @param {string} teamId - Team ID. + * @param {string} membershipId - Membership ID. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getMembership(teamId: string, membershipId: string): Promise; + getMembership( + paramsOrFirst: { teamId: string, membershipId: string } | string, + ...rest: [(string)?] + ): Promise { + let params: { teamId: string, membershipId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { teamId: string, membershipId: string }; + } else { + params = { + teamId: paramsOrFirst as string, + membershipId: rest[0] as string + }; + } + + const teamId = params.teamId; + const membershipId = params.membershipId; + if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } @@ -287,18 +510,48 @@ export class Teams extends Service { } /** - * Modify the roles of a team member. Only team members with the owner role - * have access to this endpoint. Learn more about [roles and - * permissions](https://appwrite.io/docs/permissions). + * Modify the roles of a team member. Only team members with the owner role have access to this endpoint. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). * * - * @param {string} teamId - * @param {string} membershipId - * @param {string[]} roles + * @param {string} params.teamId - Team ID. + * @param {string} params.membershipId - Membership ID. + * @param {string[]} params.roles - An array of strings. Use this param to set the user's roles in the team. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. * @throws {AppwriteException} * @returns {Promise} */ - updateMembership(teamId: string, membershipId: string, roles: string[]): Promise { + updateMembership(params: { teamId: string, membershipId: string, roles: string[] }): Promise; + /** + * Modify the roles of a team member. Only team members with the owner role have access to this endpoint. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). + * + * + * @param {string} teamId - Team ID. + * @param {string} membershipId - Membership ID. + * @param {string[]} roles - An array of strings. Use this param to set the user's roles in the team. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of 100 roles are allowed, each 32 characters long. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateMembership(teamId: string, membershipId: string, roles: string[]): Promise; + updateMembership( + paramsOrFirst: { teamId: string, membershipId: string, roles: string[] } | string, + ...rest: [(string)?, (string[])?] + ): Promise { + let params: { teamId: string, membershipId: string, roles: string[] }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { teamId: string, membershipId: string, roles: string[] }; + } else { + params = { + teamId: paramsOrFirst as string, + membershipId: rest[0] as string, + roles: rest[1] as string[] + }; + } + + const teamId = params.teamId; + const membershipId = params.membershipId; + const roles = params.roles; + if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } @@ -325,16 +578,42 @@ export class Teams extends Service { } /** - * This endpoint allows a user to leave a team or for a team owner to delete - * the membership of any other team member. You can also use this endpoint to - * delete a user membership even if it is not accepted. + * This endpoint allows a user to leave a team or for a team owner to delete the membership of any other team member. You can also use this endpoint to delete a user membership even if it is not accepted. * - * @param {string} teamId - * @param {string} membershipId + * @param {string} params.teamId - Team ID. + * @param {string} params.membershipId - Membership ID. * @throws {AppwriteException} * @returns {Promise} */ - deleteMembership(teamId: string, membershipId: string): Promise<{}> { + deleteMembership(params: { teamId: string, membershipId: string }): Promise<{}>; + /** + * This endpoint allows a user to leave a team or for a team owner to delete the membership of any other team member. You can also use this endpoint to delete a user membership even if it is not accepted. + * + * @param {string} teamId - Team ID. + * @param {string} membershipId - Membership ID. + * @throws {AppwriteException} + * @returns {Promise<{}>} + * @deprecated Use the object parameter style method for a better developer experience. + */ + deleteMembership(teamId: string, membershipId: string): Promise<{}>; + deleteMembership( + paramsOrFirst: { teamId: string, membershipId: string } | string, + ...rest: [(string)?] + ): Promise<{}> { + let params: { teamId: string, membershipId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { teamId: string, membershipId: string }; + } else { + params = { + teamId: paramsOrFirst as string, + membershipId: rest[0] as string + }; + } + + const teamId = params.teamId; + const membershipId = params.membershipId; + if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } @@ -353,22 +632,56 @@ export class Teams extends Service { } /** - * Use this endpoint to allow a user to accept an invitation to join a team - * after being redirected back to your app from the invitation email received - * by the user. + * Use this endpoint to allow a user to accept an invitation to join a team after being redirected back to your app from the invitation email received by the user. * - * If the request is successful, a session for the user is automatically - * created. + * If the request is successful, a session for the user is automatically created. * * - * @param {string} teamId - * @param {string} membershipId - * @param {string} userId - * @param {string} secret + * @param {string} params.teamId - Team ID. + * @param {string} params.membershipId - Membership ID. + * @param {string} params.userId - User ID. + * @param {string} params.secret - Secret key. * @throws {AppwriteException} * @returns {Promise} */ - updateMembershipStatus(teamId: string, membershipId: string, userId: string, secret: string): Promise { + updateMembershipStatus(params: { teamId: string, membershipId: string, userId: string, secret: string }): Promise; + /** + * Use this endpoint to allow a user to accept an invitation to join a team after being redirected back to your app from the invitation email received by the user. + * + * If the request is successful, a session for the user is automatically created. + * + * + * @param {string} teamId - Team ID. + * @param {string} membershipId - Membership ID. + * @param {string} userId - User ID. + * @param {string} secret - Secret key. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updateMembershipStatus(teamId: string, membershipId: string, userId: string, secret: string): Promise; + updateMembershipStatus( + paramsOrFirst: { teamId: string, membershipId: string, userId: string, secret: string } | string, + ...rest: [(string)?, (string)?, (string)?] + ): Promise { + let params: { teamId: string, membershipId: string, userId: string, secret: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { teamId: string, membershipId: string, userId: string, secret: string }; + } else { + params = { + teamId: paramsOrFirst as string, + membershipId: rest[0] as string, + userId: rest[1] as string, + secret: rest[2] as string + }; + } + + const teamId = params.teamId; + const membershipId = params.membershipId; + const userId = params.userId; + const secret = params.secret; + if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } @@ -403,15 +716,37 @@ export class Teams extends Service { } /** - * Get the team's shared preferences by its unique ID. If a preference doesn't - * need to be shared by all team members, prefer storing them in [user - * preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + * Get the team's shared preferences by its unique ID. If a preference doesn't need to be shared by all team members, prefer storing them in [user preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). * - * @param {string} teamId + * @param {string} params.teamId - Team ID. * @throws {AppwriteException} * @returns {Promise} */ - getPrefs(teamId: string): Promise { + getPrefs(params: { teamId: string }): Promise; + /** + * Get the team's shared preferences by its unique ID. If a preference doesn't need to be shared by all team members, prefer storing them in [user preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs). + * + * @param {string} teamId - Team ID. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getPrefs(teamId: string): Promise; + getPrefs( + paramsOrFirst: { teamId: string } | string + ): Promise { + let params: { teamId: string }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { teamId: string }; + } else { + params = { + teamId: paramsOrFirst as string + }; + } + + const teamId = params.teamId; + if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } @@ -425,16 +760,42 @@ export class Teams extends Service { } /** - * Update the team's preferences by its unique ID. The object you pass is - * stored as is and replaces any previous value. The maximum allowed prefs - * size is 64kB and throws an error if exceeded. + * Update the team's preferences by its unique ID. The object you pass is stored as is and replaces any previous value. The maximum allowed prefs size is 64kB and throws an error if exceeded. * - * @param {string} teamId - * @param {object} prefs + * @param {string} params.teamId - Team ID. + * @param {object} params.prefs - Prefs key-value JSON object. * @throws {AppwriteException} * @returns {Promise} */ - updatePrefs(teamId: string, prefs: object): Promise { + updatePrefs(params: { teamId: string, prefs: object }): Promise; + /** + * Update the team's preferences by its unique ID. The object you pass is stored as is and replaces any previous value. The maximum allowed prefs size is 64kB and throws an error if exceeded. + * + * @param {string} teamId - Team ID. + * @param {object} prefs - Prefs key-value JSON object. + * @throws {AppwriteException} + * @returns {Promise} + * @deprecated Use the object parameter style method for a better developer experience. + */ + updatePrefs(teamId: string, prefs: object): Promise; + updatePrefs( + paramsOrFirst: { teamId: string, prefs: object } | string, + ...rest: [(object)?] + ): Promise { + let params: { teamId: string, prefs: object }; + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { teamId: string, prefs: object }; + } else { + params = { + teamId: paramsOrFirst as string, + prefs: rest[0] as object + }; + } + + const teamId = params.teamId; + const prefs = params.prefs; + if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); }