diff --git a/README.md b/README.md index f878dfd..4538da3 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ # Appwrite Web SDK ![License](https://img.shields.io/github/license/appwrite/sdk-for-web.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-web/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-web/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 Web 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) @@ -33,18 +33,20 @@ import { Client, Account } from "appwrite"; To install with a CDN (content delivery network) add the following scripts to the bottom of your tag, but before you use any Appwrite services: ```html - + ``` ## Getting Started ### Add your Web Platform + For you to init your SDK and interact with Appwrite services you need to add a web platform to your project. To add a new platform, go to your Appwrite console, choose the project you created in the step before and click the 'Add Platform' button. From the options, choose to add a **Web** platform and add your client app hostname. By adding your hostname to your project platform you are allowing cross-domain communication between your project and the Appwrite API. ### 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 @@ -58,6 +60,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 @@ -74,6 +77,7 @@ account.create(ID.unique(), "email@example.com", "password", "Walter O'Brien") ``` ### Full Example + ```js // Init your Web SDK const client = new Client(); @@ -94,7 +98,83 @@ account.create(ID.unique(), "email@example.com", "password", "Walter O'Brien") }); ``` +### Type Safety with Models + +The Appwrite Web 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 Web 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/getting-started-for-web) - 📜 [Appwrite Docs](https://appwrite.io/docs) diff --git a/docs/examples/account/create-email-password-session.md b/docs/examples/account/create-email-password-session.md index 3438ffb..26a745a 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 e7cab7c..e0c4cda 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 58% rename from docs/examples/account/create-magic-u-r-l-token.md rename to docs/examples/account/create-magic-url-token.md index ba87bd9..16d3567 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 5104815..154be4e 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 e9f6f08..1328305 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 2cc7441..d9041f2 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 57% rename from docs/examples/account/create-o-auth2token.md rename to docs/examples/account/create-o-auth-2-session.md index 5f0aab3..b451e25 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 57% rename from docs/examples/account/create-o-auth2session.md rename to docs/examples/account/create-o-auth-2-token.md index caad309..0fce114 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 481e57d..60d032e 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 c987e3d..1f973e1 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 f0a400d..2195ed9 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 b6d7ef8..4858f9f 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 4a3b314..0325e40 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 bf2dbec..dbb374d 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 f34baaa..4843449 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 d113514..2b1a878 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 79bb06e..1a09b32 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 4d27221..bf17ffc 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 850488b..527ebd9 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 29af110..8c4bdd7 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 54c569b..28cc409 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 17c214f..ec763f9 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 c9fa7da..80151d9 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 9e02fc9..96dcec5 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 71% rename from docs/examples/account/update-magic-u-r-l-session.md rename to docs/examples/account/update-magic-url-session.md index 47501c5..c126f7c 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 74eedd8..f5ce65e 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 01a09dd..016533c 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 24ff10b..3ab0385 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 81% rename from docs/examples/account/update-m-f-a.md rename to docs/examples/account/update-mfa.md index 58b6a06..4d20604 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 d6a6946..6a9ba82 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 575779e..743335b 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 092205e..39d0d36 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 1b85178..6be1b77 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 0c5ff21..912b2e5 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 b9e88ea..98ea841 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 3475a22..57fdd6b 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 328e50e..d975647 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 4ccc829..4c9890b 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 6d15aee..b5fea5c 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 08512d1..a0deff3 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 fb631a4..af0599a 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 85317f1..2e976c6 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 bfbc6c2..76e7733 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 36f88ec..b8fe0f0 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 321c448..01c1830 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 65% rename from docs/examples/avatars/get-q-r.md rename to docs/examples/avatars/get-qr.md index cbbabbc..53202d8 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 916cc92..5c561ab 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 10d785a..98629c4 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 c9a1e9f..4192085 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 a2836fc..b3a7558 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 4b32be9..8adb5d8 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 d00ac56..fb1d508 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 c0e06fc..bf35548 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 cfefe06..c56bc55 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 8f07523..b8c955b 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 9b88f81..1e9a367 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 9ec5063..159882c 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 0e7466a..5771af0 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 f9cd9b7..c367d07 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 2548709..59b7603 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 3d5d0a4..dfe2d06 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 20a4220..999fcb2 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 - document.getElementById('uploader').files[0], // file - ["read("any")"] // permissions (optional) -); +const result = await storage.createFile({ + bucketId: '', + fileId: '', + file: document.getElementById('uploader').files[0], + permissions: ["read("any")"] // optional +}); console.log(result); diff --git a/docs/examples/storage/delete-file.md b/docs/examples/storage/delete-file.md index 373cdc0..101b878 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 3ebb8f8..8454be4 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 ffc64c9..c4e855b 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 add5a6f..edc28f1 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 10bd9fb..41c41b6 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 f2c3ccb..154212d 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 1432b85..96e1dc5 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 0000000..aafe71f --- /dev/null +++ b/docs/examples/tablesdb/create-row.md @@ -0,0 +1,17 @@ +import { Client, TablesDB } from "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 0000000..59f66d9 --- /dev/null +++ b/docs/examples/tablesdb/decrement-row-column.md @@ -0,0 +1,18 @@ +import { Client, TablesDB } from "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 0000000..637114d --- /dev/null +++ b/docs/examples/tablesdb/delete-row.md @@ -0,0 +1,15 @@ +import { Client, TablesDB } from "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 0000000..4e43643 --- /dev/null +++ b/docs/examples/tablesdb/get-row.md @@ -0,0 +1,16 @@ +import { Client, TablesDB } from "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 0000000..a7f3a8c --- /dev/null +++ b/docs/examples/tablesdb/increment-row-column.md @@ -0,0 +1,18 @@ +import { Client, TablesDB } from "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 0000000..63149aa --- /dev/null +++ b/docs/examples/tablesdb/list-rows.md @@ -0,0 +1,15 @@ +import { Client, TablesDB } from "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 0000000..1dba006 --- /dev/null +++ b/docs/examples/tablesdb/update-row.md @@ -0,0 +1,17 @@ +import { Client, TablesDB } from "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 0000000..1add1c4 --- /dev/null +++ b/docs/examples/tablesdb/upsert-row.md @@ -0,0 +1,17 @@ +import { Client, TablesDB } from "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 8802e25..c72da99 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 b23f220..a156156 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 2f360c3..95e5fde 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 5fd7f5d..7299f0f 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 cd253fd..a6d4186 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 a7f346f..98c7605 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 539bdcf..c910429 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 e8cc39b..d4e3420 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 4ca13ce..df57f25 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 89cc13c..8fe6108 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 fd6ffff..5db27e0 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 d91939f..db1ff4c 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 d7d4c36..0844353 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 cdedd7d..528433f 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "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": "18.2.0", + "version": "19.0.0", "license": "BSD-3-Clause", "main": "dist/cjs/sdk.js", "exports": { @@ -27,7 +27,7 @@ "devDependencies": { "@rollup/plugin-typescript": "8.3.2", "playwright": "1.15.0", - "rollup": "2.75.4", + "rollup": "2.79.2", "serve-handler": "6.1.0", "tslib": "2.4.0", "typescript": "4.7.2" diff --git a/src/client.ts b/src/client.ts index 30cde12..93641a2 100644 --- a/src/client.ts +++ b/src/client.ts @@ -316,8 +316,8 @@ class Client { 'x-sdk-name': 'Web', 'x-sdk-platform': 'client', 'x-sdk-language': 'web', - 'x-sdk-version': '18.2.0', - 'X-Appwrite-Response-Format': '1.7.0', + 'x-sdk-version': '19.0.0', + 'X-Appwrite-Response-Format': '1.8.0', }; /** diff --git a/src/index.ts b/src/index.ts index dba6f9d..8cae5d3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,7 @@ /** * Appwrite Web SDK * - * This SDK is compatible with Appwrite server version 1.7.x. + * This SDK is compatible with Appwrite server version 1.8.x. * For older versions, please check * [previous releases](https://github.com/appwrite/sdk-for-web/releases). */ @@ -14,6 +14,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 62002ff..6d2ff3c 100644 --- a/src/models.ts +++ b/src/models.ts @@ -5,12 +5,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; /** @@ -24,7 +38,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; /** @@ -38,7 +52,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; /** @@ -52,7 +66,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; /** @@ -66,7 +80,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; /** @@ -80,7 +94,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; /** @@ -94,7 +108,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; /** @@ -108,7 +122,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; /** @@ -122,7 +136,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; /** @@ -136,7 +150,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; /** @@ -150,7 +164,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; /** @@ -164,7 +178,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; /** @@ -178,7 +192,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; /** @@ -192,7 +206,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; /** @@ -201,6 +215,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 */ @@ -240,12 +293,6 @@ export namespace Models { [__default]: true; }; - export type DataWithoutDocumentKeys = { - [K in string]: any; - } & { - [K in keyof Document]?: never; - }; - /** * Log */ @@ -539,12 +586,6 @@ export namespace Models { [__default]: true; }; - export type DataWithoutPreferencesKeys = { - [K in string]: any; - } & { - [K in keyof Preferences]?: never; - }; - /** * Session */ @@ -770,7 +811,7 @@ export namespace Models { */ country: string; /** - * Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. + * Continent code. A two character continent code "AF" for Africa, "AN" for Antarctica, "AS" for Asia, "EU" for Europe, "NA" for North America, "OC" for Oceania, and "SA" for South America. */ continentCode: string; /** @@ -952,7 +993,7 @@ export namespace Models { */ $createdAt: string; /** - * Execution upate date in ISO 8601 format. + * Execution update date in ISO 8601 format. */ $updatedAt: string; /** @@ -963,6 +1004,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 acad038..ed016cb 100644 --- a/src/query.ts +++ b/src/query.ts @@ -241,6 +241,94 @@ export class Query { 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(); + /** * Combine multiple queries using logical OR operator. * diff --git a/src/services/account.ts b/src/services/account.ts index a75cc5b..d859317 100644 --- a/src/services/account.ts +++ b/src/services/account.ts @@ -1,6 +1,7 @@ import { Service } from '../service'; import { AppwriteException, Client, type Payload, UploadProgress } from '../client'; import type { Models } from '../models'; + import { AuthenticatorType } from '../enums/authenticator-type'; import { AuthenticationFactor } from '../enums/authentication-factor'; import { OAuthProvider } from '../enums/o-auth-provider'; @@ -19,6 +20,7 @@ export class Account { * @returns {Promise>} */ get(): Promise> { + const apiPath = '/account'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -37,14 +39,48 @@ export class Account { /** * 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 + * @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(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(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"'); } @@ -54,6 +90,7 @@ export class Account { if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } + const apiPath = '/account'; const payload: Payload = {}; if (typeof userId !== 'undefined') { @@ -87,18 +124,49 @@ export class Account { * 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"'); } if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } + const apiPath = '/account/email'; const payload: Payload = {}; if (typeof email !== 'undefined') { @@ -124,11 +192,36 @@ export class Account { /** * 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 = {}; if (typeof queries !== 'undefined') { @@ -150,14 +243,39 @@ export class Account { /** * Delete an identity by its unique ID. * - * @param {string} identityId + * @param {string} params.identityId - Identity ID. + * @throws {AppwriteException} + * @returns {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(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"'); } + const apiPath = '/account/identities/{identityId}'.replace('{identityId}', identityId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -181,6 +299,7 @@ export class Account { * @returns {Promise} */ createJWT(): Promise { + const apiPath = '/account/jwts'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -200,11 +319,36 @@ export class Account { /** * 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 = {}; if (typeof queries !== 'undefined') { @@ -226,14 +370,39 @@ export class Account { /** * 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"'); } + const apiPath = '/account/mfa'; const payload: Payload = {}; if (typeof mfa !== 'undefined') { @@ -256,14 +425,92 @@ export class Account { /** * 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( + 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); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'post', + uri, + apiHeaders, + payload + ); + } + + /** + * 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} params.type - Type of authenticator. Must be `totp` * @throws {AppwriteException} * @returns {Promise} */ - createMfaAuthenticator(type: AuthenticatorType): 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); @@ -283,18 +530,111 @@ export class Account { /** * Verify an authenticator app after adding it using the [add authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) method. * - * @param {AuthenticatorType} type - * @param {string} otp + * @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(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); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'put', + uri, + apiHeaders, + 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"'); + } + 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') { @@ -317,14 +657,92 @@ export class Account { /** * 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(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"'); + } + + const apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type); + const payload: Payload = {}; + const uri = new URL(this.client.config.endpoint + apiPath); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'delete', + uri, + apiHeaders, + payload + ); + } + + /** + * Delete an authenticator for a user by ID. + * + * @param {AuthenticatorType} params.type - Type of authenticator. + * @throws {AppwriteException} + * @returns {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"'); } + const apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -344,14 +762,40 @@ export class Account { /** * 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(factor: AuthenticationFactor): 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') { @@ -371,21 +815,172 @@ export class Account { ); } + /** + * Begin the process of MFA verification after sign-in. Finish the flow with [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) method. + * + * @param {AuthenticationFactor} params.factor - Factor used for verification. Must be one of following: `email`, `phone`, `totp`, `recoveryCode`. + * @throws {AppwriteException} + * @returns {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); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'post', + uri, + apiHeaders, + 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 - * @param {string} otp + * @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(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); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'put', + uri, + apiHeaders, + 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"'); + } + if (typeof otp === 'undefined') { + throw new AppwriteException('Missing required parameter: "otp"'); + } + const apiPath = '/account/mfa/challenge'; const payload: Payload = {}; if (typeof challengeId !== 'undefined') { @@ -413,8 +1008,33 @@ export class Account { * * @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'; + const payload: Payload = {}; + const uri = new URL(this.client.config.endpoint + apiPath); + + const apiHeaders: { [header: string]: string } = { + } + + return this.client.call( + 'get', + uri, + apiHeaders, + payload + ); + } + + /** + * 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); @@ -435,8 +1055,33 @@ export class Account { * * @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'; + const payload: Payload = {}; + const uri = new URL(this.client.config.endpoint + apiPath); + + const apiHeaders: { [header: string]: string } = { + } + + return this.client.call( + 'get', + uri, + apiHeaders, + 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} + */ + getMFARecoveryCodes(): Promise { + const apiPath = '/account/mfa/recovery-codes'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -453,12 +1098,38 @@ export class Account { } /** - * 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. + * 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 = {}; + const uri = new URL(this.client.config.endpoint + apiPath); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'post', + uri, + apiHeaders, + 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} + */ + createMFARecoveryCodes(): Promise { + const apiPath = '/account/mfa/recovery-codes'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -480,8 +1151,34 @@ export class Account { * * @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'; + const payload: Payload = {}; + const uri = new URL(this.client.config.endpoint + apiPath); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'patch', + uri, + apiHeaders, + 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); @@ -501,14 +1198,39 @@ export class Account { /** * 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(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(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"'); } + const apiPath = '/account/name'; const payload: Payload = {}; if (typeof name !== 'undefined') { @@ -531,15 +1253,44 @@ export class Account { /** * 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"'); } + const apiPath = '/account/password'; const payload: Payload = {}; if (typeof password !== 'undefined') { @@ -563,20 +1314,49 @@ export class Account { } /** - * 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"'); } if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } + const apiPath = '/account/phone'; const payload: Payload = {}; if (typeof phone !== 'undefined') { @@ -606,6 +1386,7 @@ export class Account { * @returns {Promise} */ getPrefs(): Promise { + const apiPath = '/account/prefs'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -624,14 +1405,39 @@ export class Account { /** * 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 + * @param {Partial} params.prefs - Prefs key-value JSON object. + * @throws {AppwriteException} + * @returns {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(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"'); } + const apiPath = '/account/prefs'; const payload: Payload = {}; if (typeof prefs !== 'undefined') { @@ -652,20 +1458,49 @@ export class Account { } /** - * 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} 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(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 - * @param {string} url + * @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(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"'); } if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } + const apiPath = '/account/recovery'; const payload: Payload = {}; if (typeof email !== 'undefined') { @@ -693,13 +1528,46 @@ export class Account { * * 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(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(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"'); } @@ -709,6 +1577,7 @@ export class Account { if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } + const apiPath = '/account/recovery'; const payload: Payload = {}; if (typeof userId !== 'undefined') { @@ -741,6 +1610,7 @@ export class Account { * @returns {Promise} */ listSessions(): Promise { + const apiPath = '/account/sessions'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -763,6 +1633,7 @@ export class Account { * @returns {Promise<{}>} */ deleteSessions(): Promise<{}> { + const apiPath = '/account/sessions'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -786,6 +1657,7 @@ export class Account { * @returns {Promise} */ createAnonymousSession(): Promise { + const apiPath = '/account/sessions/anonymous'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -807,18 +1679,49 @@ export class Account { * * 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(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(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"'); } if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } + const apiPath = '/account/sessions/email'; const payload: Payload = {}; if (typeof email !== 'undefined') { @@ -844,18 +1747,48 @@ export class Account { /** * 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(userId: string, secret: string): Promise { + 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( + 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"'); } if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } + const apiPath = '/account/sessions/magic-url'; const payload: Payload = {}; if (typeof userId !== 'undefined') { @@ -879,24 +1812,64 @@ export class Account { } /** - * 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. + * + * 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} 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(params: { provider: OAuthProvider, success?: string, failure?: string, scopes?: string[] }): void | string; + /** + * 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 - * @param {string} success - * @param {string} failure - * @param {string[]} scopes + * @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 | string} + * @deprecated Use the object parameter style method for a better developer experience. */ - createOAuth2Session(provider: OAuthProvider, success?: string, failure?: string, scopes?: string[]): void | string { + createOAuth2Session(provider: OAuthProvider, success?: string, failure?: string, scopes?: string[]): void | string; + createOAuth2Session( + paramsOrFirst: { provider: OAuthProvider, success?: string, failure?: string, scopes?: string[] } | OAuthProvider, + ...rest: [(string)?, (string)?, (string[])?] + ): void | string { + 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"'); } + const apiPath = '/account/sessions/oauth2/{provider}'.replace('{provider}', provider); const payload: Payload = {}; if (typeof success !== 'undefined') { @@ -930,18 +1903,48 @@ export class Account { /** * 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"'); } if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } + const apiPath = '/account/sessions/phone'; const payload: Payload = {}; if (typeof userId !== 'undefined') { @@ -967,18 +1970,47 @@ export class Account { /** * 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"'); } if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } + const apiPath = '/account/sessions/token'; const payload: Payload = {}; if (typeof userId !== 'undefined') { @@ -1002,16 +2034,41 @@ export class Account { } /** - * 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} params.sessionId - Session ID. Use the string 'current' to get the current device session. + * @throws {AppwriteException} + * @returns {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 + * @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(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"'); } + const apiPath = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -1028,16 +2085,41 @@ export class Account { } /** - * 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} params.sessionId - Session ID. Use the string 'current' to update the current device session. + * @throws {AppwriteException} + * @returns {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 + * @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(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"'); } + const apiPath = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -1055,16 +2137,41 @@ export class Account { } /** - * 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} params.sessionId - Session ID. Use the string 'current' to delete the current device session. + * @throws {AppwriteException} + * @returns {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 + * @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(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"'); } + const apiPath = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -1088,6 +2195,7 @@ export class Account { * @returns {Promise>} */ updateStatus(): Promise> { + const apiPath = '/account/status'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -1107,19 +2215,51 @@ export class Account { /** * 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(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(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"'); } if (typeof identifier === 'undefined') { throw new AppwriteException('Missing required parameter: "identifier"'); } + const apiPath = '/account/targets/push'; const payload: Payload = {}; if (typeof targetId !== 'undefined') { @@ -1146,20 +2286,49 @@ export class Account { } /** - * 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} params.targetId - Target ID. + * @param {string} params.identifier - The target identifier (token, email, phone etc.) + * @throws {AppwriteException} + * @returns {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 - * @param {string} identifier + * @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(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"'); } if (typeof identifier === 'undefined') { throw new AppwriteException('Missing required parameter: "identifier"'); } + const apiPath = '/account/targets/{targetId}/push'.replace('{targetId}', targetId); const payload: Payload = {}; if (typeof identifier !== 'undefined') { @@ -1182,14 +2351,39 @@ export class Account { /** * 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(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(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"'); } + const apiPath = '/account/targets/{targetId}/push'.replace('{targetId}', targetId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -1207,23 +2401,59 @@ export class Account { } /** - * 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). + * + * + * @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(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 - * @param {string} email - * @param {boolean} phrase + * @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(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"'); } if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } + const apiPath = '/account/tokens/email'; const payload: Payload = {}; if (typeof userId !== 'undefined') { @@ -1250,25 +2480,63 @@ export class Account { } /** - * 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). * * - * @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"'); } if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } + const apiPath = '/account/tokens/magic-url'; const payload: Payload = {}; if (typeof userId !== 'undefined') { @@ -1298,23 +2566,62 @@ export class Account { } /** - * 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. + * + * 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} 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(params: { provider: OAuthProvider, success?: string, failure?: string, scopes?: string[] }): void | string; + /** + * 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 - * @param {string} success - * @param {string} failure - * @param {string[]} scopes + * @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 | string} + * @deprecated Use the object parameter style method for a better developer experience. */ - createOAuth2Token(provider: OAuthProvider, success?: string, failure?: string, scopes?: string[]): void | string { + createOAuth2Token(provider: OAuthProvider, success?: string, failure?: string, scopes?: string[]): void | string; + createOAuth2Token( + paramsOrFirst: { provider: OAuthProvider, success?: string, failure?: string, scopes?: string[] } | OAuthProvider, + ...rest: [(string)?, (string)?, (string[])?] + ): void | string { + 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"'); } + const apiPath = '/account/tokens/oauth2/{provider}'.replace('{provider}', provider); const payload: Payload = {}; if (typeof success !== 'undefined') { @@ -1346,22 +2653,53 @@ export class Account { } /** - * 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). + * + * @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(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 - * @param {string} phone + * @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(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"'); } if (typeof phone === 'undefined') { throw new AppwriteException('Missing required parameter: "phone"'); } + const apiPath = '/account/tokens/phone'; const payload: Payload = {}; if (typeof userId !== 'undefined') { @@ -1385,19 +2723,47 @@ export class Account { } /** - * 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. + * + * + * @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(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 + * @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(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"'); } + const apiPath = '/account/verification'; const payload: Payload = {}; if (typeof url !== 'undefined') { @@ -1420,18 +2786,47 @@ export class Account { /** * 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"'); } if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } + const apiPath = '/account/verification'; const payload: Payload = {}; if (typeof userId !== 'undefined') { @@ -1455,12 +2850,13 @@ export class Account { } /** - * 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} */ createPhoneVerification(): Promise { + const apiPath = '/account/verification/phone'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -1478,20 +2874,49 @@ export class Account { } /** - * 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} params.userId - User ID. + * @param {string} params.secret - Valid verification token. + * @throws {AppwriteException} + * @returns {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 - * @param {string} secret + * @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(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"'); } if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } + const apiPath = '/account/verification/phone'; const payload: Payload = {}; if (typeof userId !== 'undefined') { diff --git a/src/services/avatars.ts b/src/services/avatars.ts index 4275fce..d878c1b 100644 --- a/src/services/avatars.ts +++ b/src/services/avatars.ts @@ -1,6 +1,7 @@ import { Service } from '../service'; import { AppwriteException, Client, type Payload, UploadProgress } from '../client'; import type { Models } from '../models'; + import { Browser } from '../enums/browser'; import { CreditCard } from '../enums/credit-card'; import { Flag } from '../enums/flag'; @@ -17,17 +18,54 @@ export class Avatars { * * 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 {string} + */ + getBrowser(params: { code: Browser, width?: number, height?: number, quality?: number }): string; + /** + * 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 {string} + * @deprecated Use the object parameter style method for a better developer experience. */ - getBrowser(code: Browser, width?: number, height?: number, quality?: number): string { + getBrowser(code: Browser, width?: number, height?: number, quality?: number): string; + getBrowser( + paramsOrFirst: { code: Browser, width?: number, height?: number, quality?: number } | Browser, + ...rest: [(number)?, (number)?, (number)?] + ): string { + 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"'); } + const apiPath = '/avatars/browsers/{code}'.replace('{code}', code); const payload: Payload = {}; if (typeof width !== 'undefined') { @@ -59,17 +97,55 @@ export class Avatars { * 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 {string} + */ + getCreditCard(params: { code: CreditCard, width?: number, height?: number, quality?: number }): string; + /** + * 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 {string} + * @deprecated Use the object parameter style method for a better developer experience. */ - getCreditCard(code: CreditCard, width?: number, height?: number, quality?: number): string { + getCreditCard(code: CreditCard, width?: number, height?: number, quality?: number): string; + getCreditCard( + paramsOrFirst: { code: CreditCard, width?: number, height?: number, quality?: number } | CreditCard, + ...rest: [(number)?, (number)?, (number)?] + ): string { + 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"'); } + const apiPath = '/avatars/credit-cards/{code}'.replace('{code}', code); const payload: Payload = {}; if (typeof width !== 'undefined') { @@ -100,14 +176,41 @@ export class Avatars { * * 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 {string} + */ + getFavicon(params: { url: string }): string; + /** + * 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 {string} + * @deprecated Use the object parameter style method for a better developer experience. */ - getFavicon(url: string): string { + getFavicon(url: string): string; + getFavicon( + paramsOrFirst: { url: string } | string + ): string { + 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"'); } + const apiPath = '/avatars/favicon'; const payload: Payload = {}; if (typeof url !== 'undefined') { @@ -133,17 +236,55 @@ export class Avatars { * 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 {string} + */ + getFlag(params: { code: Flag, width?: number, height?: number, quality?: number }): string; + /** + * 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 {string} + * @deprecated Use the object parameter style method for a better developer experience. */ - getFlag(code: Flag, width?: number, height?: number, quality?: number): string { + getFlag(code: Flag, width?: number, height?: number, quality?: number): string; + getFlag( + paramsOrFirst: { code: Flag, width?: number, height?: number, quality?: number } | Flag, + ...rest: [(number)?, (number)?, (number)?] + ): string { + 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"'); } + const apiPath = '/avatars/flags/{code}'.replace('{code}', code); const payload: Payload = {}; if (typeof width !== 'undefined') { @@ -176,16 +317,52 @@ export class Avatars { * * 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 {string} + */ + getImage(params: { url: string, width?: number, height?: number }): string; + /** + * 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 {string} + * @deprecated Use the object parameter style method for a better developer experience. */ - getImage(url: string, width?: number, height?: number): string { + getImage(url: string, width?: number, height?: number): string; + getImage( + paramsOrFirst: { url: string, width?: number, height?: number } | string, + ...rest: [(number)?, (number)?] + ): string { + 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"'); } + const apiPath = '/avatars/image'; const payload: Payload = {}; if (typeof url !== 'undefined') { @@ -212,21 +389,61 @@ export class Avatars { } /** - * 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. + * + * 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} 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 {string} + */ + getInitials(params?: { name?: string, width?: number, height?: number, background?: string }): string; + /** + * 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. * * - * @param {string} name - * @param {number} width - * @param {number} height - * @param {string} background + * @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 {string} + * @deprecated Use the object parameter style method for a better developer experience. */ - getInitials(name?: string, width?: number, height?: number, background?: string): string { + getInitials(name?: string, width?: number, height?: number, background?: string): string; + getInitials( + paramsOrFirst?: { name?: string, width?: number, height?: number, background?: string } | string, + ...rest: [(number)?, (number)?, (string)?] + ): string { + 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 = {}; if (typeof name !== 'undefined') { @@ -259,17 +476,53 @@ export class Avatars { * 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 {string} */ - getQR(text: string, size?: number, margin?: number, download?: boolean): string { + getQR(params: { text: string, size?: number, margin?: number, download?: boolean }): string; + /** + * 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 {string} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getQR(text: string, size?: number, margin?: number, download?: boolean): string; + getQR( + paramsOrFirst: { text: string, size?: number, margin?: number, download?: boolean } | string, + ...rest: [(number)?, (number)?, (boolean)?] + ): string { + 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"'); } + const apiPath = '/avatars/qr'; const payload: Payload = {}; if (typeof text !== 'undefined') { diff --git a/src/services/databases.ts b/src/services/databases.ts index 792b08e..f9657af 100644 --- a/src/services/databases.ts +++ b/src/services/databases.ts @@ -2,6 +2,7 @@ import { Service } from '../service'; import { AppwriteException, Client, type Payload, UploadProgress } from '../client'; import type { Models } from '../models'; + export class Databases { client: Client; @@ -10,21 +11,54 @@ export class Databases { } /** - * 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} 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(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 - * @param {string} collectionId - * @param {string[]} queries + * @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(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"'); } if (typeof collectionId === 'undefined') { throw new AppwriteException('Missing required parameter: "collectionId"'); } + const apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); const payload: Payload = {}; if (typeof queries !== 'undefined') { @@ -46,15 +80,53 @@ export class Databases { /** * 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 {Document extends Models.DefaultDocument ? Models.DataWithoutDocumentKeys : Omit} 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: Document extends Models.DefaultDocument ? Models.DataWithoutDocumentKeys : Omit, 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"'); } @@ -67,6 +139,10 @@ export class Databases { if (typeof data === 'undefined') { 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 = {}; if (typeof documentId !== 'undefined') { @@ -95,14 +171,49 @@ export class Databases { /** * 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(databaseId: string, collectionId: string, documentId: string, queries?: string[]): Promise { + 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( + 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"'); } @@ -112,6 +223,7 @@ export class Databases { if (typeof documentId === 'undefined') { throw new AppwriteException('Missing required parameter: "documentId"'); } + const apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); const payload: Payload = {}; if (typeof queries !== 'undefined') { @@ -131,19 +243,55 @@ export class Databases { } /** - * **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. * - * @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"'); } @@ -156,6 +304,10 @@ export class Databases { if (typeof data === 'undefined') { 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 = {}; if (typeof data !== 'undefined') { @@ -181,15 +333,53 @@ export class Databases { /** * 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 {Partial>} 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?: Partial>, 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"'); } @@ -199,6 +389,10 @@ export class Databases { if (typeof documentId === 'undefined') { 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 = {}; if (typeof data !== 'undefined') { @@ -224,13 +418,45 @@ export class Databases { /** * 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"'); } @@ -240,6 +466,7 @@ export class Databases { if (typeof documentId === 'undefined') { throw new AppwriteException('Missing required parameter: "documentId"'); } + const apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -259,16 +486,57 @@ export class Databases { /** * 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"'); } @@ -281,6 +549,7 @@ export class Databases { if (typeof attribute === 'undefined') { throw new AppwriteException('Missing required parameter: "attribute"'); } + const apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/decrement'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId).replace('{attribute}', attribute); const payload: Payload = {}; if (typeof value !== 'undefined') { @@ -306,16 +575,57 @@ export class Databases { /** * 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(databaseId: string, collectionId: string, documentId: string, attribute: string, value?: number, max?: number): Promise { + 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( + 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"'); } @@ -328,6 +638,7 @@ export class Databases { if (typeof attribute === 'undefined') { throw new AppwriteException('Missing required parameter: "attribute"'); } + const apiPath = '/databases/{databaseId}/collections/{collectionId}/documents/{documentId}/{attribute}/increment'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{documentId}', documentId).replace('{attribute}', attribute); const payload: Payload = {}; if (typeof value !== 'undefined') { diff --git a/src/services/functions.ts b/src/services/functions.ts index af21c86..00af834 100644 --- a/src/services/functions.ts +++ b/src/services/functions.ts @@ -1,6 +1,7 @@ import { Service } from '../service'; import { AppwriteException, Client, type Payload, UploadProgress } from '../client'; import type { Models } from '../models'; + import { ExecutionMethod } from '../enums/execution-method'; export class Functions { @@ -13,15 +14,44 @@ export class Functions { /** * 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(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(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"'); } + const apiPath = '/functions/{functionId}/executions'.replace('{functionId}', functionId); const payload: Payload = {}; if (typeof queries !== 'undefined') { @@ -43,20 +73,64 @@ export class Functions { /** * 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(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(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"'); } + const apiPath = '/functions/{functionId}/executions'.replace('{functionId}', functionId); const payload: Payload = {}; if (typeof body !== 'undefined') { @@ -94,18 +168,47 @@ export class Functions { /** * 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(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(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"'); } if (typeof executionId === 'undefined') { throw new AppwriteException('Missing required parameter: "executionId"'); } + const apiPath = '/functions/{functionId}/executions/{executionId}'.replace('{functionId}', functionId).replace('{executionId}', executionId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); diff --git a/src/services/graphql.ts b/src/services/graphql.ts index 9499d1b..f53c29a 100644 --- a/src/services/graphql.ts +++ b/src/services/graphql.ts @@ -2,6 +2,7 @@ import { Service } from '../service'; import { AppwriteException, Client, type Payload, UploadProgress } from '../client'; import type { Models } from '../models'; + export class Graphql { client: Client; @@ -12,14 +13,39 @@ export class Graphql { /** * Execute a GraphQL mutation. * - * @param {object} query + * @param {object} params.query - The query or queries to execute. + * @throws {AppwriteException} + * @returns {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(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"'); } + const apiPath = '/graphql'; const payload: Payload = {}; if (typeof query !== 'undefined') { @@ -43,14 +69,39 @@ export class Graphql { /** * 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"'); } + const apiPath = '/graphql/mutation'; const payload: Payload = {}; if (typeof query !== 'undefined') { diff --git a/src/services/locale.ts b/src/services/locale.ts index f9d62c4..fe85eeb 100644 --- a/src/services/locale.ts +++ b/src/services/locale.ts @@ -2,6 +2,7 @@ import { Service } from '../service'; import { AppwriteException, Client, type Payload, UploadProgress } from '../client'; import type { Models } from '../models'; + export class Locale { client: Client; @@ -18,6 +19,7 @@ export class Locale { * @returns {Promise} */ get(): Promise { + const apiPath = '/locale'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -40,6 +42,7 @@ export class Locale { * @returns {Promise} */ listCodes(): Promise { + const apiPath = '/locale/codes'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -62,6 +65,7 @@ export class Locale { * @returns {Promise} */ listContinents(): Promise { + const apiPath = '/locale/continents'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -84,6 +88,7 @@ export class Locale { * @returns {Promise} */ listCountries(): Promise { + const apiPath = '/locale/countries'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -106,6 +111,7 @@ export class Locale { * @returns {Promise} */ listCountriesEU(): Promise { + const apiPath = '/locale/countries/eu'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -128,6 +134,7 @@ export class Locale { * @returns {Promise} */ listCountriesPhones(): Promise { + const apiPath = '/locale/countries/phones'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -150,6 +157,7 @@ export class Locale { * @returns {Promise} */ listCurrencies(): Promise { + const apiPath = '/locale/currencies'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -172,6 +180,7 @@ export class Locale { * @returns {Promise} */ listLanguages(): Promise { + const apiPath = '/locale/languages'; const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); diff --git a/src/services/messaging.ts b/src/services/messaging.ts index ce1f85d..a35120d 100644 --- a/src/services/messaging.ts +++ b/src/services/messaging.ts @@ -2,6 +2,7 @@ import { Service } from '../service'; import { AppwriteException, Client, type Payload, UploadProgress } from '../client'; import type { Models } from '../models'; + export class Messaging { client: Client; @@ -12,13 +13,44 @@ export class Messaging { /** * 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(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(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"'); } @@ -28,6 +60,7 @@ export class Messaging { if (typeof targetId === 'undefined') { throw new AppwriteException('Missing required parameter: "targetId"'); } + const apiPath = '/messaging/topics/{topicId}/subscribers'.replace('{topicId}', topicId); const payload: Payload = {}; if (typeof subscriberId !== 'undefined') { @@ -53,18 +86,47 @@ export class Messaging { /** * 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"'); } if (typeof subscriberId === 'undefined') { throw new AppwriteException('Missing required parameter: "subscriberId"'); } + const apiPath = '/messaging/topics/{topicId}/subscribers/{subscriberId}'.replace('{topicId}', topicId).replace('{subscriberId}', subscriberId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); diff --git a/src/services/storage.ts b/src/services/storage.ts index 43b8368..c0b6ac6 100644 --- a/src/services/storage.ts +++ b/src/services/storage.ts @@ -1,6 +1,7 @@ import { Service } from '../service'; import { AppwriteException, Client, type Payload, UploadProgress } from '../client'; import type { Models } from '../models'; + import { ImageGravity } from '../enums/image-gravity'; import { ImageFormat } from '../enums/image-format'; @@ -14,16 +15,48 @@ export class Storage { /** * 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(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(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"'); } + const apiPath = '/storage/buckets/{bucketId}/files'.replace('{bucketId}', bucketId); const payload: Payload = {}; if (typeof queries !== 'undefined') { @@ -50,19 +83,63 @@ export class Storage { * * 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. + * + * + * @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 {File} 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} + */ + createFile(params: { bucketId: string, fileId: string, file: File, 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. + * 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 {File} file - * @param {string[]} permissions + * @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 {File} 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. */ - createFile(bucketId: string, fileId: string, file: File, permissions?: string[], onProgress = (progress: UploadProgress) => {}): Promise { + createFile(bucketId: string, fileId: string, file: File, permissions?: string[], onProgress?: (progress: UploadProgress) => void): Promise; + createFile( + paramsOrFirst: { bucketId: string, fileId: string, file: File, permissions?: string[], onProgress?: (progress: UploadProgress) => void } | string, + ...rest: [(string)?, (File)?, (string[])?,((progress: UploadProgress) => void)?] + ): Promise { + let params: { bucketId: string, fileId: string, file: File, permissions?: string[] }; + let onProgress: ((progress: UploadProgress) => void); + + if ((paramsOrFirst && typeof paramsOrFirst === 'object' && !Array.isArray(paramsOrFirst))) { + params = (paramsOrFirst || {}) as { bucketId: string, fileId: string, file: File, permissions?: string[] }; + onProgress = paramsOrFirst?.onProgress as ((progress: UploadProgress) => void); + } else { + params = { + bucketId: paramsOrFirst as string, + fileId: rest[0] as string, + file: rest[1] as File, + 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"'); } @@ -72,6 +149,7 @@ export class Storage { if (typeof file === 'undefined') { throw new AppwriteException('Missing required parameter: "file"'); } + const apiPath = '/storage/buckets/{bucketId}/files'.replace('{bucketId}', bucketId); const payload: Payload = {}; if (typeof fileId !== 'undefined') { @@ -101,18 +179,47 @@ export class Storage { /** * 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(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(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"'); } if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } + const apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -131,20 +238,55 @@ export class Storage { /** * 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"'); } if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } + const apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); const payload: Payload = {}; if (typeof name !== 'undefined') { @@ -170,18 +312,47 @@ export class Storage { /** * 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(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(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"'); } if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } + const apiPath = '/storage/buckets/{bucketId}/files/{fileId}'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -199,21 +370,53 @@ export class Storage { } /** - * 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 {string} */ - getFileDownload(bucketId: string, fileId: string, token?: string): string { + getFileDownload(params: { bucketId: string, fileId: string, token?: string }): string; + /** + * 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 {string} + * @deprecated Use the object parameter style method for a better developer experience. + */ + getFileDownload(bucketId: string, fileId: string, token?: string): string; + getFileDownload( + paramsOrFirst: { bucketId: string, fileId: string, token?: string } | string, + ...rest: [(string)?, (string)?] + ): string { + 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"'); } if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } + const apiPath = '/storage/buckets/{bucketId}/files/{fileId}/download'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); const payload: Payload = {}; if (typeof token !== 'undefined') { @@ -236,30 +439,95 @@ export class Storage { /** * 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 {string} + */ + 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 }): string; + /** + * 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 {string} + * @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): string { + 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): string; + 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)?] + ): string { + 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"'); } if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } + const apiPath = '/storage/buckets/{bucketId}/files/{fileId}/preview'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); const payload: Payload = {}; if (typeof width !== 'undefined') { @@ -313,21 +581,53 @@ export class Storage { } /** - * 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} 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 {string} + */ + getFileView(params: { bucketId: string, fileId: string, token?: string }): string; + /** + * 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} 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 {string} + * @deprecated Use the object parameter style method for a better developer experience. */ - getFileView(bucketId: string, fileId: string, token?: string): string { + getFileView(bucketId: string, fileId: string, token?: string): string; + getFileView( + paramsOrFirst: { bucketId: string, fileId: string, token?: string } | string, + ...rest: [(string)?, (string)?] + ): string { + 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"'); } if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } + const apiPath = '/storage/buckets/{bucketId}/files/{fileId}/view'.replace('{bucketId}', bucketId).replace('{fileId}', fileId); const payload: Payload = {}; if (typeof token !== 'undefined') { diff --git a/src/services/tables-db.ts b/src/services/tables-db.ts new file mode 100644 index 0000000..3fd996b --- /dev/null +++ b/src/services/tables-db.ts @@ -0,0 +1,643 @@ +import { Service } from '../service'; +import { AppwriteException, Client, type Payload, UploadProgress } from '../client'; +import type { Models } from '../models'; + + +export class TablesDB { + client: Client; + + constructor(client: Client) { + this.client = 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); + + const apiHeaders: { [header: string]: string } = { + } + + return this.client.call( + 'get', + uri, + apiHeaders, + 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); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'post', + uri, + apiHeaders, + 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); + + const apiHeaders: { [header: string]: string } = { + } + + return this.client.call( + 'get', + uri, + apiHeaders, + 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); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'put', + uri, + apiHeaders, + 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); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'patch', + uri, + apiHeaders, + 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); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'delete', + uri, + apiHeaders, + 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); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'patch', + uri, + apiHeaders, + 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); + + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + + return this.client.call( + 'patch', + uri, + apiHeaders, + payload + ); + } +} diff --git a/src/services/teams.ts b/src/services/teams.ts index 0b9564a..01fe8a1 100644 --- a/src/services/teams.ts +++ b/src/services/teams.ts @@ -2,6 +2,7 @@ import { Service } from '../service'; import { AppwriteException, Client, type Payload, UploadProgress } from '../client'; import type { Models } from '../models'; + export class Teams { client: Client; @@ -12,12 +13,41 @@ export class Teams { /** * 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(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(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 = {}; if (typeof queries !== 'undefined') { @@ -42,19 +72,51 @@ export class Teams { /** * 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(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(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"'); } if (typeof name === 'undefined') { throw new AppwriteException('Missing required parameter: "name"'); } + const apiPath = '/teams'; const payload: Payload = {}; if (typeof teamId !== 'undefined') { @@ -83,14 +145,39 @@ export class Teams { /** * 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(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(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"'); } + const apiPath = '/teams/{teamId}'.replace('{teamId}', teamId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -107,20 +194,49 @@ export class Teams { } /** - * Update the team's name by its unique ID. + * 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"'); } if (typeof name === 'undefined') { throw new AppwriteException('Missing required parameter: "name"'); } + const apiPath = '/teams/{teamId}'.replace('{teamId}', teamId); const payload: Payload = {}; if (typeof name !== 'undefined') { @@ -143,14 +259,39 @@ export class Teams { /** * 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(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(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"'); } + const apiPath = '/teams/{teamId}'.replace('{teamId}', teamId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -168,18 +309,50 @@ export class Teams { } /** - * 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"'); } + const apiPath = '/teams/{teamId}/memberships'.replace('{teamId}', teamId); const payload: Payload = {}; if (typeof queries !== 'undefined') { @@ -202,32 +375,83 @@ export class Teams { } /** - * 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. + * + * 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} 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(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. + * 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 - * @param {string[]} roles - * @param {string} email - * @param {string} userId - * @param {string} phone - * @param {string} url - * @param {string} name + * @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(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"'); } if (typeof roles === 'undefined') { throw new AppwriteException('Missing required parameter: "roles"'); } + const apiPath = '/teams/{teamId}/memberships'.replace('{teamId}', teamId); const payload: Payload = {}; if (typeof email !== 'undefined') { @@ -265,18 +489,47 @@ export class Teams { /** * 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(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(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"'); } if (typeof membershipId === 'undefined') { throw new AppwriteException('Missing required parameter: "membershipId"'); } + const apiPath = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -296,13 +549,45 @@ export class Teams { * 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(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(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"'); } @@ -312,6 +597,7 @@ export class Teams { if (typeof roles === 'undefined') { throw new AppwriteException('Missing required parameter: "roles"'); } + const apiPath = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); const payload: Payload = {}; if (typeof roles !== 'undefined') { @@ -334,18 +620,47 @@ export class Teams { /** * 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(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(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"'); } if (typeof membershipId === 'undefined') { throw new AppwriteException('Missing required parameter: "membershipId"'); } + const apiPath = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -368,14 +683,51 @@ export class Teams { * 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(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(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"'); } @@ -388,6 +740,7 @@ export class Teams { if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } + const apiPath = '/teams/{teamId}/memberships/{membershipId}/status'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); const payload: Payload = {}; if (typeof userId !== 'undefined') { @@ -411,16 +764,41 @@ export class Teams { } /** - * 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"'); } + const apiPath = '/teams/{teamId}/prefs'.replace('{teamId}', teamId); const payload: Payload = {}; const uri = new URL(this.client.config.endpoint + apiPath); @@ -437,20 +815,49 @@ export class Teams { } /** - * 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"'); } if (typeof prefs === 'undefined') { throw new AppwriteException('Missing required parameter: "prefs"'); } + const apiPath = '/teams/{teamId}/prefs'.replace('{teamId}', teamId); const payload: Payload = {}; if (typeof prefs !== 'undefined') {